babylon.viewer.max.js 4.9 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694
  1. (function universalModuleDefinition(root, factory) {
  2. var amdDependencies = [];
  3. if(typeof exports === 'object' && typeof module === 'object') {
  4. module.exports = factory();
  5. } else if(typeof define === 'function' && define.amd) {
  6. define("babylonjs-viewer", amdDependencies, factory);
  7. } else if(typeof exports === 'object') {
  8. exports["babylonjs-viewer"] = factory();
  9. } else {
  10. root["BabylonViewer"] = factory();
  11. }
  12. })(this, function() {
  13. var BabylonViewer =
  14. /******/ (function(modules) { // webpackBootstrap
  15. /******/ // The module cache
  16. /******/ var installedModules = {};
  17. /******/
  18. /******/ // The require function
  19. /******/ function __webpack_require__(moduleId) {
  20. /******/
  21. /******/ // Check if module is in cache
  22. /******/ if(installedModules[moduleId]) {
  23. /******/ return installedModules[moduleId].exports;
  24. /******/ }
  25. /******/ // Create a new module (and put it into the cache)
  26. /******/ var module = installedModules[moduleId] = {
  27. /******/ i: moduleId,
  28. /******/ l: false,
  29. /******/ exports: {}
  30. /******/ };
  31. /******/
  32. /******/ // Execute the module function
  33. /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  34. /******/
  35. /******/ // Flag the module as loaded
  36. /******/ module.l = true;
  37. /******/
  38. /******/ // Return the exports of the module
  39. /******/ return module.exports;
  40. /******/ }
  41. /******/
  42. /******/
  43. /******/ // expose the modules object (__webpack_modules__)
  44. /******/ __webpack_require__.m = modules;
  45. /******/
  46. /******/ // expose the module cache
  47. /******/ __webpack_require__.c = installedModules;
  48. /******/
  49. /******/ // define getter function for harmony exports
  50. /******/ __webpack_require__.d = function(exports, name, getter) {
  51. /******/ if(!__webpack_require__.o(exports, name)) {
  52. /******/ Object.defineProperty(exports, name, {
  53. /******/ configurable: false,
  54. /******/ enumerable: true,
  55. /******/ get: getter
  56. /******/ });
  57. /******/ }
  58. /******/ };
  59. /******/
  60. /******/ // getDefaultExport function for compatibility with non-harmony modules
  61. /******/ __webpack_require__.n = function(module) {
  62. /******/ var getter = module && module.__esModule ?
  63. /******/ function getDefault() { return module['default']; } :
  64. /******/ function getModuleExports() { return module; };
  65. /******/ __webpack_require__.d(getter, 'a', getter);
  66. /******/ return getter;
  67. /******/ };
  68. /******/
  69. /******/ // Object.prototype.hasOwnProperty.call
  70. /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
  71. /******/
  72. /******/ // __webpack_public_path__
  73. /******/ __webpack_require__.p = "";
  74. /******/
  75. /******/ // Load entry module and return exports
  76. /******/ return __webpack_require__(__webpack_require__.s = 16);
  77. /******/ })
  78. /************************************************************************/
  79. /******/ ([
  80. /* 0 */
  81. /***/ (function(module, exports, __webpack_require__) {
  82. /* WEBPACK VAR INJECTION */(function(global) {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;
  87. var OIMO = root.OIMO;
  88. if(true) {
  89. try { CANNON = CANNON || __webpack_require__(19); } catch(e) {}
  90. try { OIMO = OIMO || __webpack_require__(20); } catch(e) {}
  91. module.exports = factory(CANNON,OIMO);
  92. } else if(typeof define === 'function' && define.amd) {
  93. if(require.specified && require.specified("cannon")) amdDependencies.push("cannon");
  94. if(require.specified && require.specified("oimo")) amdDependencies.push("oimo");
  95. define("babylonjs", amdDependencies, factory);
  96. } else if(typeof exports === 'object') {
  97. try { CANNON = CANNON || require("cannon"); } catch(e) {}
  98. try { OIMO = OIMO || require("oimo"); } catch(e) {}
  99. exports["babylonjs"] = factory(CANNON,OIMO);
  100. } else {
  101. root["BABYLON"] = factory(CANNON,OIMO);
  102. }
  103. })(this, function(CANNON,OIMO) {
  104. CANNON = CANNON || this.CANNON;
  105. OIMO = OIMO || this.OIMO;
  106. "use strict";
  107. var BABYLON;
  108. (function (BABYLON) {
  109. /**
  110. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  111. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  112. */
  113. var EffectFallbacks = /** @class */ (function () {
  114. function EffectFallbacks() {
  115. this._defines = {};
  116. this._currentRank = 32;
  117. this._maxRank = -1;
  118. }
  119. /**
  120. * Removes the fallback from the bound mesh.
  121. */
  122. EffectFallbacks.prototype.unBindMesh = function () {
  123. this._mesh = null;
  124. };
  125. /**
  126. * Adds a fallback on the specified property.
  127. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  128. * @param define The name of the define in the shader
  129. */
  130. EffectFallbacks.prototype.addFallback = function (rank, define) {
  131. if (!this._defines[rank]) {
  132. if (rank < this._currentRank) {
  133. this._currentRank = rank;
  134. }
  135. if (rank > this._maxRank) {
  136. this._maxRank = rank;
  137. }
  138. this._defines[rank] = new Array();
  139. }
  140. this._defines[rank].push(define);
  141. };
  142. /**
  143. * Sets the mesh to use CPU skinning when needing to fallback.
  144. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  145. * @param mesh The mesh to use the fallbacks.
  146. */
  147. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  148. this._mesh = mesh;
  149. if (rank < this._currentRank) {
  150. this._currentRank = rank;
  151. }
  152. if (rank > this._maxRank) {
  153. this._maxRank = rank;
  154. }
  155. };
  156. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  157. /**
  158. * Checks to see if more fallbacks are still availible.
  159. */
  160. get: function () {
  161. return this._currentRank <= this._maxRank;
  162. },
  163. enumerable: true,
  164. configurable: true
  165. });
  166. /**
  167. * Removes the defines that shoould be removed when falling back.
  168. * @param currentDefines defines the current define statements for the shader.
  169. * @param effect defines the current effect we try to compile
  170. * @returns The resulting defines with defines of the current rank removed.
  171. */
  172. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  173. // First we try to switch to CPU skinning
  174. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  175. this._mesh.computeBonesUsingShaders = false;
  176. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  177. var scene = this._mesh.getScene();
  178. for (var index = 0; index < scene.meshes.length; index++) {
  179. var otherMesh = scene.meshes[index];
  180. if (!otherMesh.material) {
  181. continue;
  182. }
  183. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  184. continue;
  185. }
  186. if (otherMesh.material.getEffect() === effect) {
  187. otherMesh.computeBonesUsingShaders = false;
  188. }
  189. else {
  190. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  191. var subMesh = _a[_i];
  192. var subMeshEffect = subMesh.effect;
  193. if (subMeshEffect === effect) {
  194. otherMesh.computeBonesUsingShaders = false;
  195. break;
  196. }
  197. }
  198. }
  199. }
  200. }
  201. else {
  202. var currentFallbacks = this._defines[this._currentRank];
  203. if (currentFallbacks) {
  204. for (var index = 0; index < currentFallbacks.length; index++) {
  205. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  206. }
  207. }
  208. this._currentRank++;
  209. }
  210. return currentDefines;
  211. };
  212. return EffectFallbacks;
  213. }());
  214. BABYLON.EffectFallbacks = EffectFallbacks;
  215. /**
  216. * Options to be used when creating an effect.
  217. */
  218. var EffectCreationOptions = /** @class */ (function () {
  219. function EffectCreationOptions() {
  220. }
  221. return EffectCreationOptions;
  222. }());
  223. BABYLON.EffectCreationOptions = EffectCreationOptions;
  224. /**
  225. * Effect containing vertex and fragment shader that can be executed on an object.
  226. */
  227. var Effect = /** @class */ (function () {
  228. /**
  229. * Instantiates an effect.
  230. * An effect can be used to create/manage/execute vertex and fragment shaders.
  231. * @param baseName Name of the effect.
  232. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  233. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  234. * @param samplers List of sampler variables that will be passed to the shader.
  235. * @param engine Engine to be used to render the effect
  236. * @param defines Define statements to be added to the shader.
  237. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  238. * @param onCompiled Callback that will be called when the shader is compiled.
  239. * @param onError Callback that will be called if an error occurs during shader compilation.
  240. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  241. */
  242. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  243. if (samplers === void 0) { samplers = null; }
  244. if (defines === void 0) { defines = null; }
  245. if (fallbacks === void 0) { fallbacks = null; }
  246. if (onCompiled === void 0) { onCompiled = null; }
  247. if (onError === void 0) { onError = null; }
  248. var _this = this;
  249. /**
  250. * Unique ID of the effect.
  251. */
  252. this.uniqueId = 0;
  253. /**
  254. * Observable that will be called when the shader is compiled.
  255. */
  256. this.onCompileObservable = new BABYLON.Observable();
  257. /**
  258. * Observable that will be called if an error occurs during shader compilation.
  259. */
  260. this.onErrorObservable = new BABYLON.Observable();
  261. /**
  262. * Observable that will be called when effect is bound.
  263. */
  264. this.onBindObservable = new BABYLON.Observable();
  265. this._uniformBuffersNames = {};
  266. this._isReady = false;
  267. this._compilationError = "";
  268. this.name = baseName;
  269. if (attributesNamesOrOptions.attributes) {
  270. var options = attributesNamesOrOptions;
  271. this._engine = uniformsNamesOrEngine;
  272. this._attributesNames = options.attributes;
  273. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  274. this._samplers = options.samplers;
  275. this.defines = options.defines;
  276. this.onError = options.onError;
  277. this.onCompiled = options.onCompiled;
  278. this._fallbacks = options.fallbacks;
  279. this._indexParameters = options.indexParameters;
  280. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  281. if (options.uniformBuffersNames) {
  282. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  283. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  284. }
  285. }
  286. }
  287. else {
  288. this._engine = engine;
  289. this.defines = defines;
  290. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  291. this._samplers = samplers;
  292. this._attributesNames = attributesNamesOrOptions;
  293. this.onError = onError;
  294. this.onCompiled = onCompiled;
  295. this._indexParameters = indexParameters;
  296. this._fallbacks = fallbacks;
  297. }
  298. this.uniqueId = Effect._uniqueIdSeed++;
  299. if (this._getFromCache(baseName)) {
  300. this._prepareEffect();
  301. return;
  302. }
  303. var vertexSource;
  304. var fragmentSource;
  305. if (baseName.vertexElement) {
  306. vertexSource = document.getElementById(baseName.vertexElement);
  307. if (!vertexSource) {
  308. vertexSource = baseName.vertexElement;
  309. }
  310. }
  311. else {
  312. vertexSource = baseName.vertex || baseName;
  313. }
  314. if (baseName.fragmentElement) {
  315. fragmentSource = document.getElementById(baseName.fragmentElement);
  316. if (!fragmentSource) {
  317. fragmentSource = baseName.fragmentElement;
  318. }
  319. }
  320. else {
  321. fragmentSource = baseName.fragment || baseName;
  322. }
  323. var finalVertexCode;
  324. this._loadVertexShaderAsync(vertexSource)
  325. .then(function (vertexCode) {
  326. return _this._processIncludesAsync(vertexCode);
  327. })
  328. .then(function (vertexCodeWithIncludes) {
  329. finalVertexCode = _this._processShaderConversion(vertexCodeWithIncludes, false);
  330. return _this._loadFragmentShaderAsync(fragmentSource);
  331. })
  332. .then(function (fragmentCode) {
  333. return _this._processIncludesAsync(fragmentCode);
  334. })
  335. .then(function (fragmentCodeWithIncludes) {
  336. var migratedFragmentCode = _this._processShaderConversion(fragmentCodeWithIncludes, true);
  337. if (baseName) {
  338. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  339. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  340. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + finalVertexCode;
  341. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  342. }
  343. else {
  344. _this._vertexSourceCode = finalVertexCode;
  345. _this._fragmentSourceCode = migratedFragmentCode;
  346. }
  347. _this._setInCache(baseName);
  348. _this._prepareEffect();
  349. });
  350. }
  351. Effect.prototype._getSourceCacheKey = function (baseName) {
  352. var cacheKey = baseName;
  353. if (this._indexParameters) {
  354. for (var key in this._indexParameters) {
  355. if (this._indexParameters.hasOwnProperty(key)) {
  356. cacheKey += "|";
  357. cacheKey += key;
  358. cacheKey += "_";
  359. cacheKey += this._indexParameters[key];
  360. }
  361. }
  362. }
  363. return cacheKey;
  364. };
  365. Effect.prototype._getFromCache = function (baseName) {
  366. if (typeof baseName !== "string") {
  367. return false;
  368. }
  369. var cacheKey = this._getSourceCacheKey(baseName);
  370. var sources = Effect._sourceCache[cacheKey];
  371. if (!sources) {
  372. return false;
  373. }
  374. this._vertexSourceCode = sources.vertex;
  375. this._fragmentSourceCode = sources.fragment;
  376. return true;
  377. };
  378. Effect.prototype._setInCache = function (baseName) {
  379. if (typeof baseName !== "string") {
  380. return;
  381. }
  382. var cacheKey = this._getSourceCacheKey(baseName);
  383. Effect._sourceCache[cacheKey] = {
  384. vertex: this._vertexSourceCode,
  385. fragment: this._fragmentSourceCode
  386. };
  387. };
  388. Object.defineProperty(Effect.prototype, "key", {
  389. /**
  390. * Unique key for this effect
  391. */
  392. get: function () {
  393. return this._key;
  394. },
  395. enumerable: true,
  396. configurable: true
  397. });
  398. /**
  399. * If the effect has been compiled and prepared.
  400. * @returns if the effect is compiled and prepared.
  401. */
  402. Effect.prototype.isReady = function () {
  403. return this._isReady;
  404. };
  405. /**
  406. * The engine the effect was initialized with.
  407. * @returns the engine.
  408. */
  409. Effect.prototype.getEngine = function () {
  410. return this._engine;
  411. };
  412. /**
  413. * The compiled webGL program for the effect
  414. * @returns the webGL program.
  415. */
  416. Effect.prototype.getProgram = function () {
  417. return this._program;
  418. };
  419. /**
  420. * The set of names of attribute variables for the shader.
  421. * @returns An array of attribute names.
  422. */
  423. Effect.prototype.getAttributesNames = function () {
  424. return this._attributesNames;
  425. };
  426. /**
  427. * Returns the attribute at the given index.
  428. * @param index The index of the attribute.
  429. * @returns The location of the attribute.
  430. */
  431. Effect.prototype.getAttributeLocation = function (index) {
  432. return this._attributes[index];
  433. };
  434. /**
  435. * Returns the attribute based on the name of the variable.
  436. * @param name of the attribute to look up.
  437. * @returns the attribute location.
  438. */
  439. Effect.prototype.getAttributeLocationByName = function (name) {
  440. var index = this._attributesNames.indexOf(name);
  441. return this._attributes[index];
  442. };
  443. /**
  444. * The number of attributes.
  445. * @returns the numnber of attributes.
  446. */
  447. Effect.prototype.getAttributesCount = function () {
  448. return this._attributes.length;
  449. };
  450. /**
  451. * Gets the index of a uniform variable.
  452. * @param uniformName of the uniform to look up.
  453. * @returns the index.
  454. */
  455. Effect.prototype.getUniformIndex = function (uniformName) {
  456. return this._uniformsNames.indexOf(uniformName);
  457. };
  458. /**
  459. * Returns the attribute based on the name of the variable.
  460. * @param uniformName of the uniform to look up.
  461. * @returns the location of the uniform.
  462. */
  463. Effect.prototype.getUniform = function (uniformName) {
  464. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  465. };
  466. /**
  467. * Returns an array of sampler variable names
  468. * @returns The array of sampler variable neames.
  469. */
  470. Effect.prototype.getSamplers = function () {
  471. return this._samplers;
  472. };
  473. /**
  474. * The error from the last compilation.
  475. * @returns the error string.
  476. */
  477. Effect.prototype.getCompilationError = function () {
  478. return this._compilationError;
  479. };
  480. /**
  481. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  482. * @param func The callback to be used.
  483. */
  484. Effect.prototype.executeWhenCompiled = function (func) {
  485. if (this.isReady()) {
  486. func(this);
  487. return;
  488. }
  489. this.onCompileObservable.add(function (effect) {
  490. func(effect);
  491. });
  492. };
  493. /** @ignore */
  494. Effect.prototype._loadVertexShaderAsync = function (vertex) {
  495. if (BABYLON.Tools.IsWindowObjectExist()) {
  496. // DOM element ?
  497. if (vertex instanceof HTMLElement) {
  498. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  499. return Promise.resolve(vertexCode);
  500. }
  501. }
  502. // Base64 encoded ?
  503. if (vertex.substr(0, 7) === "base64:") {
  504. var vertexBinary = window.atob(vertex.substr(7));
  505. return Promise.resolve(vertexBinary);
  506. }
  507. // Is in local store ?
  508. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  509. return Promise.resolve(Effect.ShadersStore[vertex + "VertexShader"]);
  510. }
  511. var vertexShaderUrl;
  512. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  513. vertexShaderUrl = vertex;
  514. }
  515. else {
  516. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  517. }
  518. // Vertex shader
  519. return this._engine._loadFileAsync(vertexShaderUrl + ".vertex.fx");
  520. };
  521. /** @ignore */
  522. Effect.prototype._loadFragmentShaderAsync = function (fragment) {
  523. if (BABYLON.Tools.IsWindowObjectExist()) {
  524. // DOM element ?
  525. if (fragment instanceof HTMLElement) {
  526. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  527. return Promise.resolve(fragmentCode);
  528. }
  529. }
  530. // Base64 encoded ?
  531. if (fragment.substr(0, 7) === "base64:") {
  532. var fragmentBinary = window.atob(fragment.substr(7));
  533. return Promise.resolve(fragmentBinary);
  534. }
  535. // Is in local store ?
  536. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  537. return Promise.resolve(Effect.ShadersStore[fragment + "PixelShader"]);
  538. }
  539. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  540. return Promise.resolve(Effect.ShadersStore[fragment + "FragmentShader"]);
  541. }
  542. var fragmentShaderUrl;
  543. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  544. fragmentShaderUrl = fragment;
  545. }
  546. else {
  547. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  548. }
  549. // Fragment shader
  550. return this._engine._loadFileAsync(fragmentShaderUrl + ".fragment.fx");
  551. };
  552. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  553. // Rebuild shaders source code
  554. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  555. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  556. vertexCode = prefix + vertexCode;
  557. fragmentCode = prefix + fragmentCode;
  558. // Number lines of shaders source code
  559. var i = 2;
  560. var regex = /\n/gm;
  561. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  562. i = 2;
  563. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  564. // Dump shaders name and formatted source code
  565. if (this.name.vertexElement) {
  566. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  567. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  568. }
  569. else if (this.name.vertex) {
  570. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  571. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  572. }
  573. else {
  574. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  575. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  576. }
  577. };
  578. ;
  579. Effect.prototype._processShaderConversion = function (sourceCode, isFragment) {
  580. var preparedSourceCode = this._processPrecision(sourceCode);
  581. if (this._engine.webGLVersion == 1) {
  582. return preparedSourceCode;
  583. }
  584. // Already converted
  585. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  586. return preparedSourceCode.replace("#version 300 es", "");
  587. }
  588. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  589. // Remove extensions
  590. // #extension GL_OES_standard_derivatives : enable
  591. // #extension GL_EXT_shader_texture_lod : enable
  592. // #extension GL_EXT_frag_depth : enable
  593. // #extension GL_EXT_draw_buffers : require
  594. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  595. var result = preparedSourceCode.replace(regex, "");
  596. // Migrate to GLSL v300
  597. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  598. result = result.replace(/attribute[ \t]/g, "in ");
  599. result = result.replace(/[ \t]attribute/g, " in");
  600. if (isFragment) {
  601. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  602. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  603. result = result.replace(/texture2D\s*\(/g, "texture(");
  604. result = result.replace(/textureCube\s*\(/g, "texture(");
  605. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  606. result = result.replace(/gl_FragColor/g, "glFragColor");
  607. result = result.replace(/gl_FragData/g, "glFragData");
  608. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  609. }
  610. return result;
  611. };
  612. Effect.prototype._processIncludesAsync = function (sourceCode) {
  613. var _this = this;
  614. return new Promise(function (resolve, reject) {
  615. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  616. var match = regex.exec(sourceCode);
  617. var returnValue = sourceCode;
  618. while (match != null) {
  619. var includeFile = match[1];
  620. // Uniform declaration
  621. if (includeFile.indexOf("__decl__") !== -1) {
  622. includeFile = includeFile.replace(/__decl__/, "");
  623. if (_this._engine.supportsUniformBuffers) {
  624. includeFile = includeFile.replace(/Vertex/, "Ubo");
  625. includeFile = includeFile.replace(/Fragment/, "Ubo");
  626. }
  627. includeFile = includeFile + "Declaration";
  628. }
  629. if (Effect.IncludesShadersStore[includeFile]) {
  630. // Substitution
  631. var includeContent = Effect.IncludesShadersStore[includeFile];
  632. if (match[2]) {
  633. var splits = match[3].split(",");
  634. for (var index = 0; index < splits.length; index += 2) {
  635. var source = new RegExp(splits[index], "g");
  636. var dest = splits[index + 1];
  637. includeContent = includeContent.replace(source, dest);
  638. }
  639. }
  640. if (match[4]) {
  641. var indexString = match[5];
  642. if (indexString.indexOf("..") !== -1) {
  643. var indexSplits = indexString.split("..");
  644. var minIndex = parseInt(indexSplits[0]);
  645. var maxIndex = parseInt(indexSplits[1]);
  646. var sourceIncludeContent = includeContent.slice(0);
  647. includeContent = "";
  648. if (isNaN(maxIndex)) {
  649. maxIndex = _this._indexParameters[indexSplits[1]];
  650. }
  651. for (var i = minIndex; i < maxIndex; i++) {
  652. if (!_this._engine.supportsUniformBuffers) {
  653. // Ubo replacement
  654. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  655. return p1 + "{X}";
  656. });
  657. }
  658. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  659. }
  660. }
  661. else {
  662. if (!_this._engine.supportsUniformBuffers) {
  663. // Ubo replacement
  664. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  665. return p1 + "{X}";
  666. });
  667. }
  668. includeContent = includeContent.replace(/\{X\}/g, indexString);
  669. }
  670. }
  671. // Replace
  672. returnValue = returnValue.replace(match[0], includeContent);
  673. }
  674. else {
  675. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  676. _this._engine._loadFileAsync(includeShaderUrl)
  677. .then(function (fileContent) {
  678. Effect.IncludesShadersStore[includeFile] = fileContent;
  679. return _this._processIncludesAsync(returnValue);
  680. })
  681. .then(function (returnValue) {
  682. resolve(returnValue);
  683. });
  684. return;
  685. }
  686. match = regex.exec(sourceCode);
  687. }
  688. resolve(returnValue);
  689. });
  690. };
  691. Effect.prototype._processPrecision = function (source) {
  692. if (source.indexOf("precision highp float") === -1) {
  693. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  694. source = "precision mediump float;\n" + source;
  695. }
  696. else {
  697. source = "precision highp float;\n" + source;
  698. }
  699. }
  700. else {
  701. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  702. source = source.replace("precision highp float", "precision mediump float");
  703. }
  704. }
  705. return source;
  706. };
  707. /**
  708. * Recompiles the webGL program
  709. * @param vertexSourceCode The source code for the vertex shader.
  710. * @param fragmentSourceCode The source code for the fragment shader.
  711. * @param onCompiled Callback called when completed.
  712. * @param onError Callback called on error.
  713. */
  714. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  715. var _this = this;
  716. this._isReady = false;
  717. this._vertexSourceCodeOverride = vertexSourceCode;
  718. this._fragmentSourceCodeOverride = fragmentSourceCode;
  719. this.onError = function (effect, error) {
  720. if (onError) {
  721. onError(error);
  722. }
  723. };
  724. this.onCompiled = function () {
  725. var scenes = _this.getEngine().scenes;
  726. for (var i = 0; i < scenes.length; i++) {
  727. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  728. }
  729. if (onCompiled) {
  730. onCompiled(_this._program);
  731. }
  732. };
  733. this._fallbacks = null;
  734. this._prepareEffect();
  735. };
  736. /**
  737. * Gets the uniform locations of the the specified variable names
  738. * @param names THe names of the variables to lookup.
  739. * @returns Array of locations in the same order as variable names.
  740. */
  741. Effect.prototype.getSpecificUniformLocations = function (names) {
  742. var engine = this._engine;
  743. return engine.getUniforms(this._program, names);
  744. };
  745. /**
  746. * Prepares the effect
  747. */
  748. Effect.prototype._prepareEffect = function () {
  749. var attributesNames = this._attributesNames;
  750. var defines = this.defines;
  751. var fallbacks = this._fallbacks;
  752. this._valueCache = {};
  753. var previousProgram = this._program;
  754. try {
  755. var engine = this._engine;
  756. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  757. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  758. }
  759. else {
  760. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  761. }
  762. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  763. if (engine.supportsUniformBuffers) {
  764. for (var name in this._uniformBuffersNames) {
  765. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  766. }
  767. }
  768. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  769. this._attributes = engine.getAttributes(this._program, attributesNames);
  770. var index;
  771. for (index = 0; index < this._samplers.length; index++) {
  772. var sampler = this.getUniform(this._samplers[index]);
  773. if (sampler == null) {
  774. this._samplers.splice(index, 1);
  775. index--;
  776. }
  777. }
  778. engine.bindSamplers(this);
  779. this._compilationError = "";
  780. this._isReady = true;
  781. if (this.onCompiled) {
  782. this.onCompiled(this);
  783. }
  784. this.onCompileObservable.notifyObservers(this);
  785. this.onCompileObservable.clear();
  786. // Unbind mesh reference in fallbacks
  787. if (this._fallbacks) {
  788. this._fallbacks.unBindMesh();
  789. }
  790. if (previousProgram) {
  791. this.getEngine()._deleteProgram(previousProgram);
  792. }
  793. }
  794. catch (e) {
  795. this._compilationError = e.message;
  796. // Let's go through fallbacks then
  797. BABYLON.Tools.Error("Unable to compile effect:");
  798. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  799. return " " + uniform;
  800. }));
  801. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  802. return " " + attribute;
  803. }));
  804. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  805. BABYLON.Tools.Error("Error: " + this._compilationError);
  806. if (previousProgram) {
  807. this._program = previousProgram;
  808. this._isReady = true;
  809. if (this.onError) {
  810. this.onError(this, this._compilationError);
  811. }
  812. this.onErrorObservable.notifyObservers(this);
  813. }
  814. if (fallbacks && fallbacks.isMoreFallbacks) {
  815. BABYLON.Tools.Error("Trying next fallback.");
  816. this.defines = fallbacks.reduce(this.defines, this);
  817. this._prepareEffect();
  818. }
  819. else {
  820. if (this.onError) {
  821. this.onError(this, this._compilationError);
  822. }
  823. this.onErrorObservable.notifyObservers(this);
  824. this.onErrorObservable.clear();
  825. // Unbind mesh reference in fallbacks
  826. if (this._fallbacks) {
  827. this._fallbacks.unBindMesh();
  828. }
  829. }
  830. }
  831. };
  832. Object.defineProperty(Effect.prototype, "isSupported", {
  833. /**
  834. * Checks if the effect is supported. (Must be called after compilation)
  835. */
  836. get: function () {
  837. return this._compilationError === "";
  838. },
  839. enumerable: true,
  840. configurable: true
  841. });
  842. /**
  843. * Binds a texture to the engine to be used as output of the shader.
  844. * @param channel Name of the output variable.
  845. * @param texture Texture to bind.
  846. */
  847. Effect.prototype._bindTexture = function (channel, texture) {
  848. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  849. };
  850. /**
  851. * Sets a texture on the engine to be used in the shader.
  852. * @param channel Name of the sampler variable.
  853. * @param texture Texture to set.
  854. */
  855. Effect.prototype.setTexture = function (channel, texture) {
  856. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  857. };
  858. /**
  859. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  860. * @param channel Name of the sampler variable.
  861. * @param texture Texture to set.
  862. */
  863. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  864. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  865. };
  866. /**
  867. * Sets an array of textures on the engine to be used in the shader.
  868. * @param channel Name of the variable.
  869. * @param textures Textures to set.
  870. */
  871. Effect.prototype.setTextureArray = function (channel, textures) {
  872. if (this._samplers.indexOf(channel + "Ex") === -1) {
  873. var initialPos = this._samplers.indexOf(channel);
  874. for (var index = 1; index < textures.length; index++) {
  875. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  876. }
  877. }
  878. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  879. };
  880. /**
  881. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  882. * 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)
  883. * @param channel Name of the sampler variable.
  884. * @param postProcess Post process to get the input texture from.
  885. */
  886. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  887. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  888. };
  889. /**
  890. * Sets the output texture of the passed in post process to be input of this effect.
  891. * @param channel Name of the sampler variable.
  892. * @param postProcess Post process to get the output texture from.
  893. */
  894. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  895. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  896. };
  897. /** @ignore */
  898. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  899. var cache = this._valueCache[uniformName];
  900. var flag = matrix.updateFlag;
  901. if (cache !== undefined && cache === flag) {
  902. return false;
  903. }
  904. this._valueCache[uniformName] = flag;
  905. return true;
  906. };
  907. /** @ignore */
  908. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  909. var cache = this._valueCache[uniformName];
  910. if (!cache) {
  911. cache = [x, y];
  912. this._valueCache[uniformName] = cache;
  913. return true;
  914. }
  915. var changed = false;
  916. if (cache[0] !== x) {
  917. cache[0] = x;
  918. changed = true;
  919. }
  920. if (cache[1] !== y) {
  921. cache[1] = y;
  922. changed = true;
  923. }
  924. return changed;
  925. };
  926. /** @ignore */
  927. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  928. var cache = this._valueCache[uniformName];
  929. if (!cache) {
  930. cache = [x, y, z];
  931. this._valueCache[uniformName] = cache;
  932. return true;
  933. }
  934. var changed = false;
  935. if (cache[0] !== x) {
  936. cache[0] = x;
  937. changed = true;
  938. }
  939. if (cache[1] !== y) {
  940. cache[1] = y;
  941. changed = true;
  942. }
  943. if (cache[2] !== z) {
  944. cache[2] = z;
  945. changed = true;
  946. }
  947. return changed;
  948. };
  949. /** @ignore */
  950. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  951. var cache = this._valueCache[uniformName];
  952. if (!cache) {
  953. cache = [x, y, z, w];
  954. this._valueCache[uniformName] = cache;
  955. return true;
  956. }
  957. var changed = false;
  958. if (cache[0] !== x) {
  959. cache[0] = x;
  960. changed = true;
  961. }
  962. if (cache[1] !== y) {
  963. cache[1] = y;
  964. changed = true;
  965. }
  966. if (cache[2] !== z) {
  967. cache[2] = z;
  968. changed = true;
  969. }
  970. if (cache[3] !== w) {
  971. cache[3] = w;
  972. changed = true;
  973. }
  974. return changed;
  975. };
  976. /**
  977. * Binds a buffer to a uniform.
  978. * @param buffer Buffer to bind.
  979. * @param name Name of the uniform variable to bind to.
  980. */
  981. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  982. var bufferName = this._uniformBuffersNames[name];
  983. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  984. return;
  985. }
  986. Effect._baseCache[bufferName] = buffer;
  987. this._engine.bindUniformBufferBase(buffer, bufferName);
  988. };
  989. /**
  990. * Binds block to a uniform.
  991. * @param blockName Name of the block to bind.
  992. * @param index Index to bind.
  993. */
  994. Effect.prototype.bindUniformBlock = function (blockName, index) {
  995. this._engine.bindUniformBlock(this._program, blockName, index);
  996. };
  997. /**
  998. * Sets an interger value on a uniform variable.
  999. * @param uniformName Name of the variable.
  1000. * @param value Value to be set.
  1001. * @returns this effect.
  1002. */
  1003. Effect.prototype.setInt = function (uniformName, value) {
  1004. var cache = this._valueCache[uniformName];
  1005. if (cache !== undefined && cache === value)
  1006. return this;
  1007. this._valueCache[uniformName] = value;
  1008. this._engine.setInt(this.getUniform(uniformName), value);
  1009. return this;
  1010. };
  1011. /**
  1012. * Sets an int array on a uniform variable.
  1013. * @param uniformName Name of the variable.
  1014. * @param array array to be set.
  1015. * @returns this effect.
  1016. */
  1017. Effect.prototype.setIntArray = function (uniformName, array) {
  1018. this._valueCache[uniformName] = null;
  1019. this._engine.setIntArray(this.getUniform(uniformName), array);
  1020. return this;
  1021. };
  1022. /**
  1023. * 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)
  1024. * @param uniformName Name of the variable.
  1025. * @param array array to be set.
  1026. * @returns this effect.
  1027. */
  1028. Effect.prototype.setIntArray2 = function (uniformName, array) {
  1029. this._valueCache[uniformName] = null;
  1030. this._engine.setIntArray2(this.getUniform(uniformName), array);
  1031. return this;
  1032. };
  1033. /**
  1034. * 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)
  1035. * @param uniformName Name of the variable.
  1036. * @param array array to be set.
  1037. * @returns this effect.
  1038. */
  1039. Effect.prototype.setIntArray3 = function (uniformName, array) {
  1040. this._valueCache[uniformName] = null;
  1041. this._engine.setIntArray3(this.getUniform(uniformName), array);
  1042. return this;
  1043. };
  1044. /**
  1045. * 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)
  1046. * @param uniformName Name of the variable.
  1047. * @param array array to be set.
  1048. * @returns this effect.
  1049. */
  1050. Effect.prototype.setIntArray4 = function (uniformName, array) {
  1051. this._valueCache[uniformName] = null;
  1052. this._engine.setIntArray4(this.getUniform(uniformName), array);
  1053. return this;
  1054. };
  1055. /**
  1056. * Sets an float array on a uniform variable.
  1057. * @param uniformName Name of the variable.
  1058. * @param array array to be set.
  1059. * @returns this effect.
  1060. */
  1061. Effect.prototype.setFloatArray = function (uniformName, array) {
  1062. this._valueCache[uniformName] = null;
  1063. this._engine.setFloatArray(this.getUniform(uniformName), array);
  1064. return this;
  1065. };
  1066. /**
  1067. * 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)
  1068. * @param uniformName Name of the variable.
  1069. * @param array array to be set.
  1070. * @returns this effect.
  1071. */
  1072. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  1073. this._valueCache[uniformName] = null;
  1074. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  1075. return this;
  1076. };
  1077. /**
  1078. * 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)
  1079. * @param uniformName Name of the variable.
  1080. * @param array array to be set.
  1081. * @returns this effect.
  1082. */
  1083. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  1084. this._valueCache[uniformName] = null;
  1085. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  1086. return this;
  1087. };
  1088. /**
  1089. * 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)
  1090. * @param uniformName Name of the variable.
  1091. * @param array array to be set.
  1092. * @returns this effect.
  1093. */
  1094. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  1095. this._valueCache[uniformName] = null;
  1096. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  1097. return this;
  1098. };
  1099. /**
  1100. * Sets an array on a uniform variable.
  1101. * @param uniformName Name of the variable.
  1102. * @param array array to be set.
  1103. * @returns this effect.
  1104. */
  1105. Effect.prototype.setArray = function (uniformName, array) {
  1106. this._valueCache[uniformName] = null;
  1107. this._engine.setArray(this.getUniform(uniformName), array);
  1108. return this;
  1109. };
  1110. /**
  1111. * 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)
  1112. * @param uniformName Name of the variable.
  1113. * @param array array to be set.
  1114. * @returns this effect.
  1115. */
  1116. Effect.prototype.setArray2 = function (uniformName, array) {
  1117. this._valueCache[uniformName] = null;
  1118. this._engine.setArray2(this.getUniform(uniformName), array);
  1119. return this;
  1120. };
  1121. /**
  1122. * 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)
  1123. * @param uniformName Name of the variable.
  1124. * @param array array to be set.
  1125. * @returns this effect.
  1126. */
  1127. Effect.prototype.setArray3 = function (uniformName, array) {
  1128. this._valueCache[uniformName] = null;
  1129. this._engine.setArray3(this.getUniform(uniformName), array);
  1130. return this;
  1131. };
  1132. /**
  1133. * 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)
  1134. * @param uniformName Name of the variable.
  1135. * @param array array to be set.
  1136. * @returns this effect.
  1137. */
  1138. Effect.prototype.setArray4 = function (uniformName, array) {
  1139. this._valueCache[uniformName] = null;
  1140. this._engine.setArray4(this.getUniform(uniformName), array);
  1141. return this;
  1142. };
  1143. /**
  1144. * Sets matrices on a uniform variable.
  1145. * @param uniformName Name of the variable.
  1146. * @param matrices matrices to be set.
  1147. * @returns this effect.
  1148. */
  1149. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1150. if (!matrices) {
  1151. return this;
  1152. }
  1153. this._valueCache[uniformName] = null;
  1154. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1155. return this;
  1156. };
  1157. /**
  1158. * Sets matrix on a uniform variable.
  1159. * @param uniformName Name of the variable.
  1160. * @param matrix matrix to be set.
  1161. * @returns this effect.
  1162. */
  1163. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1164. if (this._cacheMatrix(uniformName, matrix)) {
  1165. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1166. }
  1167. return this;
  1168. };
  1169. /**
  1170. * 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)
  1171. * @param uniformName Name of the variable.
  1172. * @param matrix matrix to be set.
  1173. * @returns this effect.
  1174. */
  1175. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1176. this._valueCache[uniformName] = null;
  1177. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1178. return this;
  1179. };
  1180. /**
  1181. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1182. * @param uniformName Name of the variable.
  1183. * @param matrix matrix to be set.
  1184. * @returns this effect.
  1185. */
  1186. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1187. this._valueCache[uniformName] = null;
  1188. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1189. return this;
  1190. };
  1191. /**
  1192. * Sets a float on a uniform variable.
  1193. * @param uniformName Name of the variable.
  1194. * @param value value to be set.
  1195. * @returns this effect.
  1196. */
  1197. Effect.prototype.setFloat = function (uniformName, value) {
  1198. var cache = this._valueCache[uniformName];
  1199. if (cache !== undefined && cache === value)
  1200. return this;
  1201. this._valueCache[uniformName] = value;
  1202. this._engine.setFloat(this.getUniform(uniformName), value);
  1203. return this;
  1204. };
  1205. /**
  1206. * Sets a boolean on a uniform variable.
  1207. * @param uniformName Name of the variable.
  1208. * @param bool value to be set.
  1209. * @returns this effect.
  1210. */
  1211. Effect.prototype.setBool = function (uniformName, bool) {
  1212. var cache = this._valueCache[uniformName];
  1213. if (cache !== undefined && cache === bool)
  1214. return this;
  1215. this._valueCache[uniformName] = bool;
  1216. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1217. return this;
  1218. };
  1219. /**
  1220. * Sets a Vector2 on a uniform variable.
  1221. * @param uniformName Name of the variable.
  1222. * @param vector2 vector2 to be set.
  1223. * @returns this effect.
  1224. */
  1225. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1226. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1227. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1228. }
  1229. return this;
  1230. };
  1231. /**
  1232. * Sets a float2 on a uniform variable.
  1233. * @param uniformName Name of the variable.
  1234. * @param x First float in float2.
  1235. * @param y Second float in float2.
  1236. * @returns this effect.
  1237. */
  1238. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1239. if (this._cacheFloat2(uniformName, x, y)) {
  1240. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1241. }
  1242. return this;
  1243. };
  1244. /**
  1245. * Sets a Vector3 on a uniform variable.
  1246. * @param uniformName Name of the variable.
  1247. * @param vector3 Value to be set.
  1248. * @returns this effect.
  1249. */
  1250. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1251. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1252. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1253. }
  1254. return this;
  1255. };
  1256. /**
  1257. * Sets a float3 on a uniform variable.
  1258. * @param uniformName Name of the variable.
  1259. * @param x First float in float3.
  1260. * @param y Second float in float3.
  1261. * @param z Third float in float3.
  1262. * @returns this effect.
  1263. */
  1264. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1265. if (this._cacheFloat3(uniformName, x, y, z)) {
  1266. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1267. }
  1268. return this;
  1269. };
  1270. /**
  1271. * Sets a Vector4 on a uniform variable.
  1272. * @param uniformName Name of the variable.
  1273. * @param vector4 Value to be set.
  1274. * @returns this effect.
  1275. */
  1276. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1277. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1278. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1279. }
  1280. return this;
  1281. };
  1282. /**
  1283. * Sets a float4 on a uniform variable.
  1284. * @param uniformName Name of the variable.
  1285. * @param x First float in float4.
  1286. * @param y Second float in float4.
  1287. * @param z Third float in float4.
  1288. * @param w Fourth float in float4.
  1289. * @returns this effect.
  1290. */
  1291. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1292. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1293. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1294. }
  1295. return this;
  1296. };
  1297. /**
  1298. * Sets a Color3 on a uniform variable.
  1299. * @param uniformName Name of the variable.
  1300. * @param color3 Value to be set.
  1301. * @returns this effect.
  1302. */
  1303. Effect.prototype.setColor3 = function (uniformName, color3) {
  1304. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1305. this._engine.setColor3(this.getUniform(uniformName), color3);
  1306. }
  1307. return this;
  1308. };
  1309. /**
  1310. * Sets a Color4 on a uniform variable.
  1311. * @param uniformName Name of the variable.
  1312. * @param color3 Value to be set.
  1313. * @param alpha Alpha value to be set.
  1314. * @returns this effect.
  1315. */
  1316. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1317. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1318. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1319. }
  1320. return this;
  1321. };
  1322. /**
  1323. * Sets a Color4 on a uniform variable
  1324. * @param uniformName defines the name of the variable
  1325. * @param color4 defines the value to be set
  1326. * @returns this effect.
  1327. */
  1328. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1329. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1330. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1331. }
  1332. return this;
  1333. };
  1334. /**
  1335. * Resets the cache of effects.
  1336. */
  1337. Effect.ResetCache = function () {
  1338. Effect._baseCache = {};
  1339. };
  1340. Effect._uniqueIdSeed = 0;
  1341. Effect._baseCache = {};
  1342. Effect._sourceCache = {};
  1343. // Statics
  1344. /**
  1345. * Store of each shader (The can be looked up using effect.key)
  1346. */
  1347. Effect.ShadersStore = {};
  1348. /**
  1349. * Store of each included file for a shader (The can be looked up using effect.key)
  1350. */
  1351. Effect.IncludesShadersStore = {};
  1352. return Effect;
  1353. }());
  1354. BABYLON.Effect = Effect;
  1355. })(BABYLON || (BABYLON = {}));
  1356. //# sourceMappingURL=babylon.effect.js.map
  1357. "use strict";
  1358. //# sourceMappingURL=babylon.types.js.map
  1359. "use strict";
  1360. var BABYLON;
  1361. (function (BABYLON) {
  1362. var KeyboardEventTypes = /** @class */ (function () {
  1363. function KeyboardEventTypes() {
  1364. }
  1365. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1366. get: function () {
  1367. return KeyboardEventTypes._KEYDOWN;
  1368. },
  1369. enumerable: true,
  1370. configurable: true
  1371. });
  1372. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1373. get: function () {
  1374. return KeyboardEventTypes._KEYUP;
  1375. },
  1376. enumerable: true,
  1377. configurable: true
  1378. });
  1379. KeyboardEventTypes._KEYDOWN = 0x01;
  1380. KeyboardEventTypes._KEYUP = 0x02;
  1381. return KeyboardEventTypes;
  1382. }());
  1383. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1384. var KeyboardInfo = /** @class */ (function () {
  1385. function KeyboardInfo(type, event) {
  1386. this.type = type;
  1387. this.event = event;
  1388. }
  1389. return KeyboardInfo;
  1390. }());
  1391. BABYLON.KeyboardInfo = KeyboardInfo;
  1392. /**
  1393. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1394. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1395. */
  1396. var KeyboardInfoPre = /** @class */ (function (_super) {
  1397. __extends(KeyboardInfoPre, _super);
  1398. function KeyboardInfoPre(type, event) {
  1399. var _this = _super.call(this, type, event) || this;
  1400. _this.skipOnPointerObservable = false;
  1401. return _this;
  1402. }
  1403. return KeyboardInfoPre;
  1404. }(KeyboardInfo));
  1405. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1406. })(BABYLON || (BABYLON = {}));
  1407. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1408. "use strict";
  1409. var BABYLON;
  1410. (function (BABYLON) {
  1411. var PointerEventTypes = /** @class */ (function () {
  1412. function PointerEventTypes() {
  1413. }
  1414. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1415. get: function () {
  1416. return PointerEventTypes._POINTERDOWN;
  1417. },
  1418. enumerable: true,
  1419. configurable: true
  1420. });
  1421. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1422. get: function () {
  1423. return PointerEventTypes._POINTERUP;
  1424. },
  1425. enumerable: true,
  1426. configurable: true
  1427. });
  1428. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1429. get: function () {
  1430. return PointerEventTypes._POINTERMOVE;
  1431. },
  1432. enumerable: true,
  1433. configurable: true
  1434. });
  1435. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1436. get: function () {
  1437. return PointerEventTypes._POINTERWHEEL;
  1438. },
  1439. enumerable: true,
  1440. configurable: true
  1441. });
  1442. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1443. get: function () {
  1444. return PointerEventTypes._POINTERPICK;
  1445. },
  1446. enumerable: true,
  1447. configurable: true
  1448. });
  1449. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1450. get: function () {
  1451. return PointerEventTypes._POINTERTAP;
  1452. },
  1453. enumerable: true,
  1454. configurable: true
  1455. });
  1456. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1457. get: function () {
  1458. return PointerEventTypes._POINTERDOUBLETAP;
  1459. },
  1460. enumerable: true,
  1461. configurable: true
  1462. });
  1463. PointerEventTypes._POINTERDOWN = 0x01;
  1464. PointerEventTypes._POINTERUP = 0x02;
  1465. PointerEventTypes._POINTERMOVE = 0x04;
  1466. PointerEventTypes._POINTERWHEEL = 0x08;
  1467. PointerEventTypes._POINTERPICK = 0x10;
  1468. PointerEventTypes._POINTERTAP = 0x20;
  1469. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1470. return PointerEventTypes;
  1471. }());
  1472. BABYLON.PointerEventTypes = PointerEventTypes;
  1473. var PointerInfoBase = /** @class */ (function () {
  1474. function PointerInfoBase(type, event) {
  1475. this.type = type;
  1476. this.event = event;
  1477. }
  1478. return PointerInfoBase;
  1479. }());
  1480. BABYLON.PointerInfoBase = PointerInfoBase;
  1481. /**
  1482. * This class is used to store pointer related info for the onPrePointerObservable event.
  1483. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1484. */
  1485. var PointerInfoPre = /** @class */ (function (_super) {
  1486. __extends(PointerInfoPre, _super);
  1487. function PointerInfoPre(type, event, localX, localY) {
  1488. var _this = _super.call(this, type, event) || this;
  1489. _this.skipOnPointerObservable = false;
  1490. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1491. return _this;
  1492. }
  1493. return PointerInfoPre;
  1494. }(PointerInfoBase));
  1495. BABYLON.PointerInfoPre = PointerInfoPre;
  1496. /**
  1497. * This type contains all the data related to a pointer event in Babylon.js.
  1498. * 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.
  1499. */
  1500. var PointerInfo = /** @class */ (function (_super) {
  1501. __extends(PointerInfo, _super);
  1502. function PointerInfo(type, event, pickInfo) {
  1503. var _this = _super.call(this, type, event) || this;
  1504. _this.pickInfo = pickInfo;
  1505. return _this;
  1506. }
  1507. return PointerInfo;
  1508. }(PointerInfoBase));
  1509. BABYLON.PointerInfo = PointerInfo;
  1510. })(BABYLON || (BABYLON = {}));
  1511. //# sourceMappingURL=babylon.pointerEvents.js.map
  1512. "use strict";
  1513. var BABYLON;
  1514. (function (BABYLON) {
  1515. BABYLON.ToGammaSpace = 1 / 2.2;
  1516. BABYLON.ToLinearSpace = 2.2;
  1517. BABYLON.Epsilon = 0.001;
  1518. /**
  1519. * Class used to hold a RBG color
  1520. */
  1521. var Color3 = /** @class */ (function () {
  1522. /**
  1523. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1524. * @param r defines the red component (between 0 and 1, default is 0)
  1525. * @param g defines the green component (between 0 and 1, default is 0)
  1526. * @param b defines the blue component (between 0 and 1, default is 0)
  1527. */
  1528. function Color3(
  1529. /**
  1530. * Defines the red component (between 0 and 1, default is 0)
  1531. */
  1532. r,
  1533. /**
  1534. * Defines the green component (between 0 and 1, default is 0)
  1535. */
  1536. g,
  1537. /**
  1538. * Defines the blue component (between 0 and 1, default is 0)
  1539. */
  1540. b) {
  1541. if (r === void 0) { r = 0; }
  1542. if (g === void 0) { g = 0; }
  1543. if (b === void 0) { b = 0; }
  1544. this.r = r;
  1545. this.g = g;
  1546. this.b = b;
  1547. }
  1548. /**
  1549. * Creates a string with the Color3 current values
  1550. * @returns the string representation of the Color3 object
  1551. */
  1552. Color3.prototype.toString = function () {
  1553. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1554. };
  1555. /**
  1556. * Returns the string "Color3"
  1557. * @returns "Color3"
  1558. */
  1559. Color3.prototype.getClassName = function () {
  1560. return "Color3";
  1561. };
  1562. /**
  1563. * Compute the Color3 hash code
  1564. * @returns an unique number that can be used to hash Color3 objects
  1565. */
  1566. Color3.prototype.getHashCode = function () {
  1567. var hash = this.r || 0;
  1568. hash = (hash * 397) ^ (this.g || 0);
  1569. hash = (hash * 397) ^ (this.b || 0);
  1570. return hash;
  1571. };
  1572. // Operators
  1573. /**
  1574. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements
  1575. * @param array defines the array where to store the r,g,b components
  1576. * @param index defines an optional index in the target array to define where to start storing values
  1577. * @returns the current Color3 object
  1578. */
  1579. Color3.prototype.toArray = function (array, index) {
  1580. if (index === undefined) {
  1581. index = 0;
  1582. }
  1583. array[index] = this.r;
  1584. array[index + 1] = this.g;
  1585. array[index + 2] = this.b;
  1586. return this;
  1587. };
  1588. /**
  1589. * Returns a new {BABYLON.Color4} object from the current Color3 and the passed alpha
  1590. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1591. * @returns a new {BABYLON.Color4} object
  1592. */
  1593. Color3.prototype.toColor4 = function (alpha) {
  1594. if (alpha === void 0) { alpha = 1; }
  1595. return new Color4(this.r, this.g, this.b, alpha);
  1596. };
  1597. /**
  1598. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1599. * @returns the new array
  1600. */
  1601. Color3.prototype.asArray = function () {
  1602. var result = new Array();
  1603. this.toArray(result, 0);
  1604. return result;
  1605. };
  1606. /**
  1607. * Returns the luminance value
  1608. * @returns a float value
  1609. */
  1610. Color3.prototype.toLuminance = function () {
  1611. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1612. };
  1613. /**
  1614. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object
  1615. * @param otherColor defines the second operand
  1616. * @returns the new Color3 object
  1617. */
  1618. Color3.prototype.multiply = function (otherColor) {
  1619. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1620. };
  1621. /**
  1622. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result"
  1623. * @param otherColor defines the second operand
  1624. * @param result defines the Color3 object where to store the result
  1625. * @returns the current Color3
  1626. */
  1627. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1628. result.r = this.r * otherColor.r;
  1629. result.g = this.g * otherColor.g;
  1630. result.b = this.b * otherColor.b;
  1631. return this;
  1632. };
  1633. /**
  1634. * Determines equality between Color3 objects
  1635. * @param otherColor defines the second operand
  1636. * @returns true if the rgb values are equal to the passed ones
  1637. */
  1638. Color3.prototype.equals = function (otherColor) {
  1639. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1640. };
  1641. /**
  1642. * Determines equality between the current Color3 object and a set of r,b,g values
  1643. * @param r defines the red component to check
  1644. * @param g defines the green component to check
  1645. * @param b defines the blue component to check
  1646. * @returns true if the rgb values are equal to the passed ones
  1647. */
  1648. Color3.prototype.equalsFloats = function (r, g, b) {
  1649. return this.r === r && this.g === g && this.b === b;
  1650. };
  1651. /**
  1652. * Multiplies in place each rgb value by scale
  1653. * @param scale defines the scaling factor
  1654. * @returns the updated Color3
  1655. */
  1656. Color3.prototype.scale = function (scale) {
  1657. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1658. };
  1659. /**
  1660. * Multiplies the rgb values by scale and stores the result into "result"
  1661. * @param scale defines the scaling factor
  1662. * @param result defines the Color3 object where to store the result
  1663. * @returns the unmodified current Color3
  1664. */
  1665. Color3.prototype.scaleToRef = function (scale, result) {
  1666. result.r = this.r * scale;
  1667. result.g = this.g * scale;
  1668. result.b = this.b * scale;
  1669. return this;
  1670. };
  1671. /**
  1672. * Scale the current Color3 values by a factor and add the result to a given Color3
  1673. * @param scale defines the scale factor
  1674. * @param result defines color to store the result into
  1675. * @returns the unmodified current Color3
  1676. */
  1677. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1678. result.r += this.r * scale;
  1679. result.g += this.g * scale;
  1680. result.b += this.b * scale;
  1681. return this;
  1682. };
  1683. /**
  1684. * Clamps the rgb values by the min and max values and stores the result into "result"
  1685. * @param min defines minimum clamping value (default is 0)
  1686. * @param max defines maximum clamping value (default is 1)
  1687. * @param result defines color to store the result into
  1688. * @returns the original Color3
  1689. */
  1690. Color3.prototype.clampToRef = function (min, max, result) {
  1691. if (min === void 0) { min = 0; }
  1692. if (max === void 0) { max = 1; }
  1693. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1694. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1695. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1696. return this;
  1697. };
  1698. /**
  1699. * Creates a new Color3 set with the added values of the current Color3 and of the passed one
  1700. * @param otherColor defines the second operand
  1701. * @returns the new Color3
  1702. */
  1703. Color3.prototype.add = function (otherColor) {
  1704. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1705. };
  1706. /**
  1707. * Stores the result of the addition of the current Color3 and passed one rgb values into "result"
  1708. * @param otherColor defines the second operand
  1709. * @param result defines Color3 object to store the result into
  1710. * @returns the unmodified current Color3
  1711. */
  1712. Color3.prototype.addToRef = function (otherColor, result) {
  1713. result.r = this.r + otherColor.r;
  1714. result.g = this.g + otherColor.g;
  1715. result.b = this.b + otherColor.b;
  1716. return this;
  1717. };
  1718. /**
  1719. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3
  1720. * @param otherColor defines the second operand
  1721. * @returns the new Color3
  1722. */
  1723. Color3.prototype.subtract = function (otherColor) {
  1724. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1725. };
  1726. /**
  1727. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result"
  1728. * @param otherColor defines the second operand
  1729. * @param result defines Color3 object to store the result into
  1730. * @returns the unmodified current Color3
  1731. */
  1732. Color3.prototype.subtractToRef = function (otherColor, result) {
  1733. result.r = this.r - otherColor.r;
  1734. result.g = this.g - otherColor.g;
  1735. result.b = this.b - otherColor.b;
  1736. return this;
  1737. };
  1738. /**
  1739. * Copy the current object
  1740. * @returns a new Color3 copied the current one
  1741. */
  1742. Color3.prototype.clone = function () {
  1743. return new Color3(this.r, this.g, this.b);
  1744. };
  1745. /**
  1746. * Copies the rgb values from the source in the current Color3
  1747. * @param source defines the source Color3 object
  1748. * @returns the updated Color3 object
  1749. */
  1750. Color3.prototype.copyFrom = function (source) {
  1751. this.r = source.r;
  1752. this.g = source.g;
  1753. this.b = source.b;
  1754. return this;
  1755. };
  1756. /**
  1757. * Updates the Color3 rgb values from the passed floats
  1758. * @param r defines the red component to read from
  1759. * @param g defines the green component to read from
  1760. * @param b defines the blue component to read from
  1761. * @returns the current Color3 object
  1762. */
  1763. Color3.prototype.copyFromFloats = function (r, g, b) {
  1764. this.r = r;
  1765. this.g = g;
  1766. this.b = b;
  1767. return this;
  1768. };
  1769. /**
  1770. * Updates the Color3 rgb values from the passed floats
  1771. * @param r defines the red component to read from
  1772. * @param g defines the green component to read from
  1773. * @param b defines the blue component to read from
  1774. * @returns the current Color3 object
  1775. */
  1776. Color3.prototype.set = function (r, g, b) {
  1777. return this.copyFromFloats(r, g, b);
  1778. };
  1779. /**
  1780. * Compute the Color3 hexadecimal code as a string
  1781. * @returns a string containing the hexadecimal representation of the Color3 object
  1782. */
  1783. Color3.prototype.toHexString = function () {
  1784. var intR = (this.r * 255) | 0;
  1785. var intG = (this.g * 255) | 0;
  1786. var intB = (this.b * 255) | 0;
  1787. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1788. };
  1789. /**
  1790. * Computes a new Color3 converted from the current one to linear space
  1791. * @returns a new Color3 object
  1792. */
  1793. Color3.prototype.toLinearSpace = function () {
  1794. var convertedColor = new Color3();
  1795. this.toLinearSpaceToRef(convertedColor);
  1796. return convertedColor;
  1797. };
  1798. /**
  1799. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1800. * @param convertedColor defines the Color3 object where to store the linear space version
  1801. * @returns the unmodified Color3
  1802. */
  1803. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1804. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1805. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1806. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1807. return this;
  1808. };
  1809. /**
  1810. * Computes a new Color3 converted from the current one to gamma space
  1811. * @returns a new Color3 object
  1812. */
  1813. Color3.prototype.toGammaSpace = function () {
  1814. var convertedColor = new Color3();
  1815. this.toGammaSpaceToRef(convertedColor);
  1816. return convertedColor;
  1817. };
  1818. /**
  1819. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1820. * @param convertedColor defines the Color3 object where to store the gamma space version
  1821. * @returns the unmodified Color3
  1822. */
  1823. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1824. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1825. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1826. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1827. return this;
  1828. };
  1829. // Statics
  1830. /**
  1831. * Creates a new Color3 from the string containing valid hexadecimal values
  1832. * @param hex defines a string containing valid hexadecimal values
  1833. * @returns a new Color3 object
  1834. */
  1835. Color3.FromHexString = function (hex) {
  1836. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1837. return new Color3(0, 0, 0);
  1838. }
  1839. var r = parseInt(hex.substring(1, 3), 16);
  1840. var g = parseInt(hex.substring(3, 5), 16);
  1841. var b = parseInt(hex.substring(5, 7), 16);
  1842. return Color3.FromInts(r, g, b);
  1843. };
  1844. /**
  1845. * Creates a new Vector3 from the starting index of the passed array
  1846. * @param array defines the source array
  1847. * @param offset defines an offset in the source array
  1848. * @returns a new Color3 object
  1849. */
  1850. Color3.FromArray = function (array, offset) {
  1851. if (offset === void 0) { offset = 0; }
  1852. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1853. };
  1854. /**
  1855. * Creates a new Color3 from integer values (< 256)
  1856. * @param r defines the red component to read from (value between 0 and 255)
  1857. * @param g defines the green component to read from (value between 0 and 255)
  1858. * @param b defines the blue component to read from (value between 0 and 255)
  1859. * @returns a new Color3 object
  1860. */
  1861. Color3.FromInts = function (r, g, b) {
  1862. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1863. };
  1864. /**
  1865. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1866. * @param start defines the start Color3 value
  1867. * @param end defines the end Color3 value
  1868. * @param amount defines the gradient value between start and end
  1869. * @returns a new Color3 object
  1870. */
  1871. Color3.Lerp = function (start, end, amount) {
  1872. var r = start.r + ((end.r - start.r) * amount);
  1873. var g = start.g + ((end.g - start.g) * amount);
  1874. var b = start.b + ((end.b - start.b) * amount);
  1875. return new Color3(r, g, b);
  1876. };
  1877. /**
  1878. * Returns a Color3 value containing a red color
  1879. * @returns a new Color3 object
  1880. */
  1881. Color3.Red = function () { return new Color3(1, 0, 0); };
  1882. /**
  1883. * Returns a Color3 value containing a green color
  1884. * @returns a new Color3 object
  1885. */
  1886. Color3.Green = function () { return new Color3(0, 1, 0); };
  1887. /**
  1888. * Returns a Color3 value containing a blue color
  1889. * @returns a new Color3 object
  1890. */
  1891. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1892. /**
  1893. * Returns a Color3 value containing a black color
  1894. * @returns a new Color3 object
  1895. */
  1896. Color3.Black = function () { return new Color3(0, 0, 0); };
  1897. /**
  1898. * Returns a Color3 value containing a white color
  1899. * @returns a new Color3 object
  1900. */
  1901. Color3.White = function () { return new Color3(1, 1, 1); };
  1902. /**
  1903. * Returns a Color3 value containing a purple color
  1904. * @returns a new Color3 object
  1905. */
  1906. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1907. /**
  1908. * Returns a Color3 value containing a magenta color
  1909. * @returns a new Color3 object
  1910. */
  1911. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1912. /**
  1913. * Returns a Color3 value containing a yellow color
  1914. * @returns a new Color3 object
  1915. */
  1916. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1917. /**
  1918. * Returns a Color3 value containing a gray color
  1919. * @returns a new Color3 object
  1920. */
  1921. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1922. /**
  1923. * Returns a Color3 value containing a teal color
  1924. * @returns a new Color3 object
  1925. */
  1926. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1927. /**
  1928. * Returns a Color3 value containing a random color
  1929. * @returns a new Color3 object
  1930. */
  1931. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1932. return Color3;
  1933. }());
  1934. BABYLON.Color3 = Color3;
  1935. /**
  1936. * Class used to hold a RBGA color
  1937. */
  1938. var Color4 = /** @class */ (function () {
  1939. /**
  1940. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1941. * @param r defines the red component (between 0 and 1, default is 0)
  1942. * @param g defines the green component (between 0 and 1, default is 0)
  1943. * @param b defines the blue component (between 0 and 1, default is 0)
  1944. * @param a defines the alpha component (between 0 and 1, default is 1)
  1945. */
  1946. function Color4(
  1947. /**
  1948. * Defines the red component (between 0 and 1, default is 0)
  1949. */
  1950. r,
  1951. /**
  1952. * Defines the green component (between 0 and 1, default is 0)
  1953. */
  1954. g,
  1955. /**
  1956. * Defines the blue component (between 0 and 1, default is 0)
  1957. */
  1958. b,
  1959. /**
  1960. * Defines the alpha component (between 0 and 1, default is 1)
  1961. */
  1962. a) {
  1963. if (r === void 0) { r = 0; }
  1964. if (g === void 0) { g = 0; }
  1965. if (b === void 0) { b = 0; }
  1966. if (a === void 0) { a = 1; }
  1967. this.r = r;
  1968. this.g = g;
  1969. this.b = b;
  1970. this.a = a;
  1971. }
  1972. // Operators
  1973. /**
  1974. * Adds in place the passed Color4 values to the current Color4 object
  1975. * @param right defines the second operand
  1976. * @returns the current updated Color4 object
  1977. */
  1978. Color4.prototype.addInPlace = function (right) {
  1979. this.r += right.r;
  1980. this.g += right.g;
  1981. this.b += right.b;
  1982. this.a += right.a;
  1983. return this;
  1984. };
  1985. /**
  1986. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1987. * @returns the new array
  1988. */
  1989. Color4.prototype.asArray = function () {
  1990. var result = new Array();
  1991. this.toArray(result, 0);
  1992. return result;
  1993. };
  1994. /**
  1995. * Stores from the starting index in the passed array the Color4 successive values
  1996. * @param array defines the array where to store the r,g,b components
  1997. * @param index defines an optional index in the target array to define where to start storing values
  1998. * @returns the current Color4 object
  1999. */
  2000. Color4.prototype.toArray = function (array, index) {
  2001. if (index === undefined) {
  2002. index = 0;
  2003. }
  2004. array[index] = this.r;
  2005. array[index + 1] = this.g;
  2006. array[index + 2] = this.b;
  2007. array[index + 3] = this.a;
  2008. return this;
  2009. };
  2010. /**
  2011. * Creates a new Color4 set with the added values of the current Color4 and of the passed one
  2012. * @param right defines the second operand
  2013. * @returns a new Color4 object
  2014. */
  2015. Color4.prototype.add = function (right) {
  2016. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  2017. };
  2018. /**
  2019. * Creates a new Color4 set with the subtracted values of the passed one from the current Color4
  2020. * @param right defines the second operand
  2021. * @returns a new Color4 object
  2022. */
  2023. Color4.prototype.subtract = function (right) {
  2024. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  2025. };
  2026. /**
  2027. * Subtracts the passed ones from the current Color4 values and stores the results in "result"
  2028. * @param right defines the second operand
  2029. * @param result defines the Color4 object where to store the result
  2030. * @returns the current Color4 object
  2031. */
  2032. Color4.prototype.subtractToRef = function (right, result) {
  2033. result.r = this.r - right.r;
  2034. result.g = this.g - right.g;
  2035. result.b = this.b - right.b;
  2036. result.a = this.a - right.a;
  2037. return this;
  2038. };
  2039. /**
  2040. * Creates a new Color4 with the current Color4 values multiplied by scale
  2041. * @param scale defines the scaling factor to apply
  2042. * @returns a new Color4 object
  2043. */
  2044. Color4.prototype.scale = function (scale) {
  2045. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  2046. };
  2047. /**
  2048. * Multiplies the current Color4 values by scale and stores the result in "result"
  2049. * @param scale defines the scaling factor to apply
  2050. * @param result defines the Color4 object where to store the result
  2051. * @returns the current unmodified Color4
  2052. */
  2053. Color4.prototype.scaleToRef = function (scale, result) {
  2054. result.r = this.r * scale;
  2055. result.g = this.g * scale;
  2056. result.b = this.b * scale;
  2057. result.a = this.a * scale;
  2058. return this;
  2059. };
  2060. /**
  2061. * Scale the current Color4 values by a factor and add the result to a given Color4
  2062. * @param scale defines the scale factor
  2063. * @param result defines the Color4 object where to store the result
  2064. * @returns the unmodified current Color4
  2065. */
  2066. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  2067. result.r += this.r * scale;
  2068. result.g += this.g * scale;
  2069. result.b += this.b * scale;
  2070. result.a += this.a * scale;
  2071. return this;
  2072. };
  2073. /**
  2074. * Clamps the rgb values by the min and max values and stores the result into "result"
  2075. * @param min defines minimum clamping value (default is 0)
  2076. * @param max defines maximum clamping value (default is 1)
  2077. * @param result defines color to store the result into.
  2078. * @returns the cuurent Color4
  2079. */
  2080. Color4.prototype.clampToRef = function (min, max, result) {
  2081. if (min === void 0) { min = 0; }
  2082. if (max === void 0) { max = 1; }
  2083. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  2084. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  2085. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  2086. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  2087. return this;
  2088. };
  2089. /**
  2090. * Multipy an Color4 value by another and return a new Color4 object
  2091. * @param color defines the Color4 value to multiply by
  2092. * @returns a new Color4 object
  2093. */
  2094. Color4.prototype.multiply = function (color) {
  2095. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  2096. };
  2097. /**
  2098. * Multipy a Color4 value by another and push the result in a reference value
  2099. * @param color defines the Color4 value to multiply by
  2100. * @param result defines the Color4 to fill the result in
  2101. * @returns the result Color4
  2102. */
  2103. Color4.prototype.multiplyToRef = function (color, result) {
  2104. result.r = this.r * color.r;
  2105. result.g = this.g * color.g;
  2106. result.b = this.b * color.b;
  2107. result.a = this.a * color.a;
  2108. return result;
  2109. };
  2110. /**
  2111. * Creates a string with the Color4 current values
  2112. * @returns the string representation of the Color4 object
  2113. */
  2114. Color4.prototype.toString = function () {
  2115. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  2116. };
  2117. /**
  2118. * Returns the string "Color4"
  2119. * @returns "Color4"
  2120. */
  2121. Color4.prototype.getClassName = function () {
  2122. return "Color4";
  2123. };
  2124. /**
  2125. * Compute the Color4 hash code
  2126. * @returns an unique number that can be used to hash Color4 objects
  2127. */
  2128. Color4.prototype.getHashCode = function () {
  2129. var hash = this.r || 0;
  2130. hash = (hash * 397) ^ (this.g || 0);
  2131. hash = (hash * 397) ^ (this.b || 0);
  2132. hash = (hash * 397) ^ (this.a || 0);
  2133. return hash;
  2134. };
  2135. /**
  2136. * Creates a new Color4 copied from the current one
  2137. * @returns a new Color4 object
  2138. */
  2139. Color4.prototype.clone = function () {
  2140. return new Color4(this.r, this.g, this.b, this.a);
  2141. };
  2142. /**
  2143. * Copies the passed Color4 values into the current one
  2144. * @param source defines the source Color4 object
  2145. * @returns the current updated Color4 object
  2146. */
  2147. Color4.prototype.copyFrom = function (source) {
  2148. this.r = source.r;
  2149. this.g = source.g;
  2150. this.b = source.b;
  2151. this.a = source.a;
  2152. return this;
  2153. };
  2154. /**
  2155. * Copies the passed float values into the current one
  2156. * @param r defines the red component to read from
  2157. * @param g defines the green component to read from
  2158. * @param b defines the blue component to read from
  2159. * @param a defines the alpha component to read from
  2160. * @returns the current updated Color4 object
  2161. */
  2162. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2163. this.r = r;
  2164. this.g = g;
  2165. this.b = b;
  2166. this.a = a;
  2167. return this;
  2168. };
  2169. /**
  2170. * Copies the passed float values into the current one
  2171. * @param r defines the red component to read from
  2172. * @param g defines the green component to read from
  2173. * @param b defines the blue component to read from
  2174. * @param a defines the alpha component to read from
  2175. * @returns the current updated Color4 object
  2176. */
  2177. Color4.prototype.set = function (r, g, b, a) {
  2178. return this.copyFromFloats(r, g, b, a);
  2179. };
  2180. /**
  2181. * Compute the Color4 hexadecimal code as a string
  2182. * @returns a string containing the hexadecimal representation of the Color4 object
  2183. */
  2184. Color4.prototype.toHexString = function () {
  2185. var intR = (this.r * 255) | 0;
  2186. var intG = (this.g * 255) | 0;
  2187. var intB = (this.b * 255) | 0;
  2188. var intA = (this.a * 255) | 0;
  2189. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2190. };
  2191. /**
  2192. * Computes a new Color4 converted from the current one to linear space
  2193. * @returns a new Color4 object
  2194. */
  2195. Color4.prototype.toLinearSpace = function () {
  2196. var convertedColor = new Color4();
  2197. this.toLinearSpaceToRef(convertedColor);
  2198. return convertedColor;
  2199. };
  2200. /**
  2201. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2202. * @param convertedColor defines the Color4 object where to store the linear space version
  2203. * @returns the unmodified Color4
  2204. */
  2205. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2206. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2207. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2208. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2209. convertedColor.a = this.a;
  2210. return this;
  2211. };
  2212. /**
  2213. * Computes a new Color4 converted from the current one to gamma space
  2214. * @returns a new Color4 object
  2215. */
  2216. Color4.prototype.toGammaSpace = function () {
  2217. var convertedColor = new Color4();
  2218. this.toGammaSpaceToRef(convertedColor);
  2219. return convertedColor;
  2220. };
  2221. /**
  2222. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2223. * @param convertedColor defines the Color4 object where to store the gamma space version
  2224. * @returns the unmodified Color4
  2225. */
  2226. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2227. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2228. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2229. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2230. convertedColor.a = this.a;
  2231. return this;
  2232. };
  2233. // Statics
  2234. /**
  2235. * Creates a new Color4 from the string containing valid hexadecimal values
  2236. * @param hex defines a string containing valid hexadecimal values
  2237. * @returns a new Color4 object
  2238. */
  2239. Color4.FromHexString = function (hex) {
  2240. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2241. return new Color4(0.0, 0.0, 0.0, 0.0);
  2242. }
  2243. var r = parseInt(hex.substring(1, 3), 16);
  2244. var g = parseInt(hex.substring(3, 5), 16);
  2245. var b = parseInt(hex.substring(5, 7), 16);
  2246. var a = parseInt(hex.substring(7, 9), 16);
  2247. return Color4.FromInts(r, g, b, a);
  2248. };
  2249. /**
  2250. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2251. * @param left defines the start value
  2252. * @param right defines the end value
  2253. * @param amount defines the gradient factor
  2254. * @returns a new Color4 object
  2255. */
  2256. Color4.Lerp = function (left, right, amount) {
  2257. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2258. Color4.LerpToRef(left, right, amount, result);
  2259. return result;
  2260. };
  2261. /**
  2262. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2263. * @param left defines the start value
  2264. * @param right defines the end value
  2265. * @param amount defines the gradient factor
  2266. * @param result defines the Color4 object where to store data
  2267. */
  2268. Color4.LerpToRef = function (left, right, amount, result) {
  2269. result.r = left.r + (right.r - left.r) * amount;
  2270. result.g = left.g + (right.g - left.g) * amount;
  2271. result.b = left.b + (right.b - left.b) * amount;
  2272. result.a = left.a + (right.a - left.a) * amount;
  2273. };
  2274. /**
  2275. * Creates a new Color4 from the starting index element of the passed array
  2276. * @param array defines the source array to read from
  2277. * @param offset defines the offset in the source array
  2278. * @returns a new Color4 object
  2279. */
  2280. Color4.FromArray = function (array, offset) {
  2281. if (offset === void 0) { offset = 0; }
  2282. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2283. };
  2284. /**
  2285. * Creates a new Color3 from integer values (< 256)
  2286. * @param r defines the red component to read from (value between 0 and 255)
  2287. * @param g defines the green component to read from (value between 0 and 255)
  2288. * @param b defines the blue component to read from (value between 0 and 255)
  2289. * @param a defines the alpha component to read from (value between 0 and 255)
  2290. * @returns a new Color3 object
  2291. */
  2292. Color4.FromInts = function (r, g, b, a) {
  2293. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2294. };
  2295. /**
  2296. * Check the content of a given array and convert it to an array containing RGBA data
  2297. * If the original array was already containing count * 4 values then it is returned directly
  2298. * @param colors defines the array to check
  2299. * @param count defines the number of RGBA data to expect
  2300. * @returns an array containing count * 4 values (RGBA)
  2301. */
  2302. Color4.CheckColors4 = function (colors, count) {
  2303. // Check if color3 was used
  2304. if (colors.length === count * 3) {
  2305. var colors4 = [];
  2306. for (var index = 0; index < colors.length; index += 3) {
  2307. var newIndex = (index / 3) * 4;
  2308. colors4[newIndex] = colors[index];
  2309. colors4[newIndex + 1] = colors[index + 1];
  2310. colors4[newIndex + 2] = colors[index + 2];
  2311. colors4[newIndex + 3] = 1.0;
  2312. }
  2313. return colors4;
  2314. }
  2315. return colors;
  2316. };
  2317. return Color4;
  2318. }());
  2319. BABYLON.Color4 = Color4;
  2320. var Vector2 = /** @class */ (function () {
  2321. /**
  2322. * Creates a new Vector2 from the passed x and y coordinates.
  2323. */
  2324. function Vector2(x, y) {
  2325. this.x = x;
  2326. this.y = y;
  2327. }
  2328. /**
  2329. * Returns a string with the Vector2 coordinates.
  2330. */
  2331. Vector2.prototype.toString = function () {
  2332. return "{X: " + this.x + " Y:" + this.y + "}";
  2333. };
  2334. /**
  2335. * Returns the string "Vector2"
  2336. */
  2337. Vector2.prototype.getClassName = function () {
  2338. return "Vector2";
  2339. };
  2340. /**
  2341. * Returns the Vector2 hash code as a number.
  2342. */
  2343. Vector2.prototype.getHashCode = function () {
  2344. var hash = this.x || 0;
  2345. hash = (hash * 397) ^ (this.y || 0);
  2346. return hash;
  2347. };
  2348. // Operators
  2349. /**
  2350. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  2351. * Returns the Vector2.
  2352. */
  2353. Vector2.prototype.toArray = function (array, index) {
  2354. if (index === void 0) { index = 0; }
  2355. array[index] = this.x;
  2356. array[index + 1] = this.y;
  2357. return this;
  2358. };
  2359. /**
  2360. * Returns a new array with 2 elements : the Vector2 coordinates.
  2361. */
  2362. Vector2.prototype.asArray = function () {
  2363. var result = new Array();
  2364. this.toArray(result, 0);
  2365. return result;
  2366. };
  2367. /**
  2368. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  2369. * Returns the updated Vector2.
  2370. */
  2371. Vector2.prototype.copyFrom = function (source) {
  2372. this.x = source.x;
  2373. this.y = source.y;
  2374. return this;
  2375. };
  2376. /**
  2377. * Sets the Vector2 coordinates with the passed floats.
  2378. * Returns the updated Vector2.
  2379. */
  2380. Vector2.prototype.copyFromFloats = function (x, y) {
  2381. this.x = x;
  2382. this.y = y;
  2383. return this;
  2384. };
  2385. /**
  2386. * Sets the Vector2 coordinates with the passed floats.
  2387. * Returns the updated Vector2.
  2388. */
  2389. Vector2.prototype.set = function (x, y) {
  2390. return this.copyFromFloats(x, y);
  2391. };
  2392. /**
  2393. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  2394. */
  2395. Vector2.prototype.add = function (otherVector) {
  2396. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2397. };
  2398. /**
  2399. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  2400. * Returns the Vector2.
  2401. */
  2402. Vector2.prototype.addToRef = function (otherVector, result) {
  2403. result.x = this.x + otherVector.x;
  2404. result.y = this.y + otherVector.y;
  2405. return this;
  2406. };
  2407. /**
  2408. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  2409. * Returns the updated Vector2.
  2410. */
  2411. Vector2.prototype.addInPlace = function (otherVector) {
  2412. this.x += otherVector.x;
  2413. this.y += otherVector.y;
  2414. return this;
  2415. };
  2416. /**
  2417. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  2418. */
  2419. Vector2.prototype.addVector3 = function (otherVector) {
  2420. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2421. };
  2422. /**
  2423. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  2424. */
  2425. Vector2.prototype.subtract = function (otherVector) {
  2426. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2427. };
  2428. /**
  2429. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  2430. * Returns the Vector2.
  2431. */
  2432. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2433. result.x = this.x - otherVector.x;
  2434. result.y = this.y - otherVector.y;
  2435. return this;
  2436. };
  2437. /**
  2438. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  2439. * Returns the updated Vector2.
  2440. */
  2441. Vector2.prototype.subtractInPlace = function (otherVector) {
  2442. this.x -= otherVector.x;
  2443. this.y -= otherVector.y;
  2444. return this;
  2445. };
  2446. /**
  2447. * Multiplies in place the current Vector2 coordinates by the passed ones.
  2448. * Returns the updated Vector2.
  2449. */
  2450. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2451. this.x *= otherVector.x;
  2452. this.y *= otherVector.y;
  2453. return this;
  2454. };
  2455. /**
  2456. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  2457. */
  2458. Vector2.prototype.multiply = function (otherVector) {
  2459. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2460. };
  2461. /**
  2462. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  2463. * Returns the Vector2.
  2464. */
  2465. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2466. result.x = this.x * otherVector.x;
  2467. result.y = this.y * otherVector.y;
  2468. return this;
  2469. };
  2470. /**
  2471. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  2472. */
  2473. Vector2.prototype.multiplyByFloats = function (x, y) {
  2474. return new Vector2(this.x * x, this.y * y);
  2475. };
  2476. /**
  2477. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  2478. */
  2479. Vector2.prototype.divide = function (otherVector) {
  2480. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2481. };
  2482. /**
  2483. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  2484. * Returns the Vector2.
  2485. */
  2486. Vector2.prototype.divideToRef = function (otherVector, result) {
  2487. result.x = this.x / otherVector.x;
  2488. result.y = this.y / otherVector.y;
  2489. return this;
  2490. };
  2491. /**
  2492. * Divides the current Vector3 coordinates by the passed ones.
  2493. * Returns the updated Vector3.
  2494. */
  2495. Vector2.prototype.divideInPlace = function (otherVector) {
  2496. return this.divideToRef(otherVector, this);
  2497. };
  2498. /**
  2499. * Returns a new Vector2 with current Vector2 negated coordinates.
  2500. */
  2501. Vector2.prototype.negate = function () {
  2502. return new Vector2(-this.x, -this.y);
  2503. };
  2504. /**
  2505. * Multiply the Vector2 coordinates by scale.
  2506. * Returns the updated Vector2.
  2507. */
  2508. Vector2.prototype.scaleInPlace = function (scale) {
  2509. this.x *= scale;
  2510. this.y *= scale;
  2511. return this;
  2512. };
  2513. /**
  2514. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  2515. */
  2516. Vector2.prototype.scale = function (scale) {
  2517. var result = new Vector2(0, 0);
  2518. this.scaleToRef(scale, result);
  2519. return result;
  2520. };
  2521. /**
  2522. * Scale the current Vector2 values by a factor to a given Vector2
  2523. * @param scale defines the scale factor
  2524. * @param result defines the Vector2 object where to store the result
  2525. * @returns the unmodified current Vector2
  2526. */
  2527. Vector2.prototype.scaleToRef = function (scale, result) {
  2528. result.x = this.x * scale;
  2529. result.y = this.y * scale;
  2530. return this;
  2531. };
  2532. /**
  2533. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2534. * @param scale defines the scale factor
  2535. * @param result defines the Vector2 object where to store the result
  2536. * @returns the unmodified current Vector2
  2537. */
  2538. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2539. result.x += this.x * scale;
  2540. result.y += this.y * scale;
  2541. return this;
  2542. };
  2543. /**
  2544. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  2545. */
  2546. Vector2.prototype.equals = function (otherVector) {
  2547. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2548. };
  2549. /**
  2550. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  2551. */
  2552. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2553. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2554. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2555. };
  2556. // Properties
  2557. /**
  2558. * Returns the vector length (float).
  2559. */
  2560. Vector2.prototype.length = function () {
  2561. return Math.sqrt(this.x * this.x + this.y * this.y);
  2562. };
  2563. /**
  2564. * Returns the vector squared length (float);
  2565. */
  2566. Vector2.prototype.lengthSquared = function () {
  2567. return (this.x * this.x + this.y * this.y);
  2568. };
  2569. // Methods
  2570. /**
  2571. * Normalize the vector.
  2572. * Returns the updated Vector2.
  2573. */
  2574. Vector2.prototype.normalize = function () {
  2575. var len = this.length();
  2576. if (len === 0)
  2577. return this;
  2578. var num = 1.0 / len;
  2579. this.x *= num;
  2580. this.y *= num;
  2581. return this;
  2582. };
  2583. /**
  2584. * Returns a new Vector2 copied from the Vector2.
  2585. */
  2586. Vector2.prototype.clone = function () {
  2587. return new Vector2(this.x, this.y);
  2588. };
  2589. // Statics
  2590. /**
  2591. * Returns a new Vector2(0, 0)
  2592. */
  2593. Vector2.Zero = function () {
  2594. return new Vector2(0, 0);
  2595. };
  2596. /**
  2597. * Returns a new Vector2(1, 1)
  2598. */
  2599. Vector2.One = function () {
  2600. return new Vector2(1, 1);
  2601. };
  2602. /**
  2603. * Returns a new Vector2 set from the passed index element of the passed array.
  2604. */
  2605. Vector2.FromArray = function (array, offset) {
  2606. if (offset === void 0) { offset = 0; }
  2607. return new Vector2(array[offset], array[offset + 1]);
  2608. };
  2609. /**
  2610. * Sets "result" from the passed index element of the passed array.
  2611. */
  2612. Vector2.FromArrayToRef = function (array, offset, result) {
  2613. result.x = array[offset];
  2614. result.y = array[offset + 1];
  2615. };
  2616. /**
  2617. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  2618. */
  2619. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2620. var squared = amount * amount;
  2621. var cubed = amount * squared;
  2622. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2623. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2624. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2625. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2626. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2627. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2628. return new Vector2(x, y);
  2629. };
  2630. /**
  2631. * 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".
  2632. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2633. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  2634. */
  2635. Vector2.Clamp = function (value, min, max) {
  2636. var x = value.x;
  2637. x = (x > max.x) ? max.x : x;
  2638. x = (x < min.x) ? min.x : x;
  2639. var y = value.y;
  2640. y = (y > max.y) ? max.y : y;
  2641. y = (y < min.y) ? min.y : y;
  2642. return new Vector2(x, y);
  2643. };
  2644. /**
  2645. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  2646. */
  2647. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2648. var squared = amount * amount;
  2649. var cubed = amount * squared;
  2650. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2651. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2652. var part3 = (cubed - (2.0 * squared)) + amount;
  2653. var part4 = cubed - squared;
  2654. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2655. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2656. return new Vector2(x, y);
  2657. };
  2658. /**
  2659. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2660. */
  2661. Vector2.Lerp = function (start, end, amount) {
  2662. var x = start.x + ((end.x - start.x) * amount);
  2663. var y = start.y + ((end.y - start.y) * amount);
  2664. return new Vector2(x, y);
  2665. };
  2666. /**
  2667. * Returns the dot product (float) of the vector "left" and the vector "right".
  2668. */
  2669. Vector2.Dot = function (left, right) {
  2670. return left.x * right.x + left.y * right.y;
  2671. };
  2672. /**
  2673. * Returns a new Vector2 equal to the normalized passed vector.
  2674. */
  2675. Vector2.Normalize = function (vector) {
  2676. var newVector = vector.clone();
  2677. newVector.normalize();
  2678. return newVector;
  2679. };
  2680. /**
  2681. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  2682. */
  2683. Vector2.Minimize = function (left, right) {
  2684. var x = (left.x < right.x) ? left.x : right.x;
  2685. var y = (left.y < right.y) ? left.y : right.y;
  2686. return new Vector2(x, y);
  2687. };
  2688. /**
  2689. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  2690. */
  2691. Vector2.Maximize = function (left, right) {
  2692. var x = (left.x > right.x) ? left.x : right.x;
  2693. var y = (left.y > right.y) ? left.y : right.y;
  2694. return new Vector2(x, y);
  2695. };
  2696. /**
  2697. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  2698. */
  2699. Vector2.Transform = function (vector, transformation) {
  2700. var r = Vector2.Zero();
  2701. Vector2.TransformToRef(vector, transformation, r);
  2702. return r;
  2703. };
  2704. /**
  2705. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  2706. */
  2707. Vector2.TransformToRef = function (vector, transformation, result) {
  2708. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2709. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2710. result.x = x;
  2711. result.y = y;
  2712. };
  2713. /**
  2714. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2715. */
  2716. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2717. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2718. var sign = a < 0 ? -1 : 1;
  2719. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2720. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2721. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2722. };
  2723. /**
  2724. * Returns the distance (float) between the vectors "value1" and "value2".
  2725. */
  2726. Vector2.Distance = function (value1, value2) {
  2727. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2728. };
  2729. /**
  2730. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2731. */
  2732. Vector2.DistanceSquared = function (value1, value2) {
  2733. var x = value1.x - value2.x;
  2734. var y = value1.y - value2.y;
  2735. return (x * x) + (y * y);
  2736. };
  2737. /**
  2738. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  2739. */
  2740. Vector2.Center = function (value1, value2) {
  2741. var center = value1.add(value2);
  2742. center.scaleInPlace(0.5);
  2743. return center;
  2744. };
  2745. /**
  2746. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2747. */
  2748. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2749. var l2 = Vector2.DistanceSquared(segA, segB);
  2750. if (l2 === 0.0) {
  2751. return Vector2.Distance(p, segA);
  2752. }
  2753. var v = segB.subtract(segA);
  2754. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2755. var proj = segA.add(v.multiplyByFloats(t, t));
  2756. return Vector2.Distance(p, proj);
  2757. };
  2758. return Vector2;
  2759. }());
  2760. BABYLON.Vector2 = Vector2;
  2761. /**
  2762. * Classed used to store (x,y,z) vector representation
  2763. * A Vector3 is the main object used in 3D geometry
  2764. * It can represent etiher the coordinates of a point the space, either a direction
  2765. * Reminder: Babylon.js uses a left handed forward facing system
  2766. */
  2767. var Vector3 = /** @class */ (function () {
  2768. /**
  2769. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  2770. * @param x defines the first coordinates (on X axis)
  2771. * @param y defines the second coordinates (on Y axis)
  2772. * @param z defines the third coordinates (on Z axis)
  2773. */
  2774. function Vector3(
  2775. /**
  2776. * Defines the first coordinates (on X axis)
  2777. */
  2778. x,
  2779. /**
  2780. * Defines the second coordinates (on Y axis)
  2781. */
  2782. y,
  2783. /**
  2784. * Defines the third coordinates (on Z axis)
  2785. */
  2786. z) {
  2787. this.x = x;
  2788. this.y = y;
  2789. this.z = z;
  2790. }
  2791. /**
  2792. * Creates a string representation of the Vector3
  2793. * @returns a string with the Vector3 coordinates.
  2794. */
  2795. Vector3.prototype.toString = function () {
  2796. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2797. };
  2798. /**
  2799. * Gets the class name
  2800. * @returns the string "Vector3"
  2801. */
  2802. Vector3.prototype.getClassName = function () {
  2803. return "Vector3";
  2804. };
  2805. /**
  2806. * Creates the Vector3 hash code
  2807. * @returns a number which tends to be unique between Vector3 instances
  2808. */
  2809. Vector3.prototype.getHashCode = function () {
  2810. var hash = this.x || 0;
  2811. hash = (hash * 397) ^ (this.y || 0);
  2812. hash = (hash * 397) ^ (this.z || 0);
  2813. return hash;
  2814. };
  2815. // Operators
  2816. /**
  2817. * Creates an array containing three elements : the coordinates of the Vector3
  2818. * @returns a new array of numbers
  2819. */
  2820. Vector3.prototype.asArray = function () {
  2821. var result = [];
  2822. this.toArray(result, 0);
  2823. return result;
  2824. };
  2825. /**
  2826. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3
  2827. * @param array defines the destination array
  2828. * @param index defines the offset in the destination array
  2829. * @returns the current Vector3
  2830. */
  2831. Vector3.prototype.toArray = function (array, index) {
  2832. if (index === void 0) { index = 0; }
  2833. array[index] = this.x;
  2834. array[index + 1] = this.y;
  2835. array[index + 2] = this.z;
  2836. return this;
  2837. };
  2838. /**
  2839. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2840. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2841. */
  2842. Vector3.prototype.toQuaternion = function () {
  2843. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  2844. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  2845. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  2846. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  2847. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  2848. var cosy = Math.cos(this.y * 0.5);
  2849. var siny = Math.sin(this.y * 0.5);
  2850. result.x = coszMinusx * siny;
  2851. result.y = -sinzMinusx * siny;
  2852. result.z = sinxPlusz * cosy;
  2853. result.w = cosxPlusz * cosy;
  2854. return result;
  2855. };
  2856. /**
  2857. * Adds the passed vector to the current Vector3
  2858. * @param otherVector defines the second operand
  2859. * @returns the current updated Vector3
  2860. */
  2861. Vector3.prototype.addInPlace = function (otherVector) {
  2862. this.x += otherVector.x;
  2863. this.y += otherVector.y;
  2864. this.z += otherVector.z;
  2865. return this;
  2866. };
  2867. /**
  2868. * Gets a new Vector3, result of the addition the current Vector3 and the passed vector
  2869. * @param otherVector defines the second operand
  2870. * @returns the resulting Vector3
  2871. */
  2872. Vector3.prototype.add = function (otherVector) {
  2873. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2874. };
  2875. /**
  2876. * Adds the current Vector3 to the passed one and stores the result in the vector "result"
  2877. * @param otherVector defines the second operand
  2878. * @param result defines the Vector3 object where to store the result
  2879. * @returns the current Vector3
  2880. */
  2881. Vector3.prototype.addToRef = function (otherVector, result) {
  2882. result.x = this.x + otherVector.x;
  2883. result.y = this.y + otherVector.y;
  2884. result.z = this.z + otherVector.z;
  2885. return this;
  2886. };
  2887. /**
  2888. * Subtract the passed vector from the current Vector3
  2889. * @param otherVector defines the second operand
  2890. * @returns the current updated Vector3
  2891. */
  2892. Vector3.prototype.subtractInPlace = function (otherVector) {
  2893. this.x -= otherVector.x;
  2894. this.y -= otherVector.y;
  2895. this.z -= otherVector.z;
  2896. return this;
  2897. };
  2898. /**
  2899. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3
  2900. * @param otherVector defines the second operand
  2901. * @returns the resulting Vector3
  2902. */
  2903. Vector3.prototype.subtract = function (otherVector) {
  2904. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2905. };
  2906. /**
  2907. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  2908. * @param otherVector defines the second operand
  2909. * @param result defines the Vector3 object where to store the result
  2910. * @returns the current Vector3
  2911. */
  2912. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2913. result.x = this.x - otherVector.x;
  2914. result.y = this.y - otherVector.y;
  2915. result.z = this.z - otherVector.z;
  2916. return this;
  2917. };
  2918. /**
  2919. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates
  2920. * @param x defines the x coordinate of the operand
  2921. * @param y defines the y coordinate of the operand
  2922. * @param z defines the z coordinate of the operand
  2923. * @returns the resulting Vector3
  2924. */
  2925. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2926. return new Vector3(this.x - x, this.y - y, this.z - z);
  2927. };
  2928. /**
  2929. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result
  2930. * @param x defines the x coordinate of the operand
  2931. * @param y defines the y coordinate of the operand
  2932. * @param z defines the z coordinate of the operand
  2933. * @param result defines the Vector3 object where to store the result
  2934. * @returns the current Vector3
  2935. */
  2936. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2937. result.x = this.x - x;
  2938. result.y = this.y - y;
  2939. result.z = this.z - z;
  2940. return this;
  2941. };
  2942. /**
  2943. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2944. * @returns a new Vector3
  2945. */
  2946. Vector3.prototype.negate = function () {
  2947. return new Vector3(-this.x, -this.y, -this.z);
  2948. };
  2949. /**
  2950. * Multiplies the Vector3 coordinates by the float "scale"
  2951. * @param scale defines the multiplier factor
  2952. * @returns the current updated Vector3
  2953. */
  2954. Vector3.prototype.scaleInPlace = function (scale) {
  2955. this.x *= scale;
  2956. this.y *= scale;
  2957. this.z *= scale;
  2958. return this;
  2959. };
  2960. /**
  2961. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2962. * @param scale defines the multiplier factor
  2963. * @returns a new Vector3
  2964. */
  2965. Vector3.prototype.scale = function (scale) {
  2966. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2967. };
  2968. /**
  2969. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates
  2970. * @param scale defines the multiplier factor
  2971. * @param result defines the Vector3 object where to store the result
  2972. * @returns the current Vector3
  2973. */
  2974. Vector3.prototype.scaleToRef = function (scale, result) {
  2975. result.x = this.x * scale;
  2976. result.y = this.y * scale;
  2977. result.z = this.z * scale;
  2978. return this;
  2979. };
  2980. /**
  2981. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  2982. * @param scale defines the scale factor
  2983. * @param result defines the Vector3 object where to store the result
  2984. * @returns the unmodified current Vector3
  2985. */
  2986. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  2987. result.x += this.x * scale;
  2988. result.y += this.y * scale;
  2989. result.z += this.z * scale;
  2990. return this;
  2991. };
  2992. /**
  2993. * Returns true if the current Vector3 and the passed vector coordinates are strictly equal
  2994. * @param otherVector defines the second operand
  2995. * @returns true if both vectors are equals
  2996. */
  2997. Vector3.prototype.equals = function (otherVector) {
  2998. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2999. };
  3000. /**
  3001. * Returns true if the current Vector3 and the passed vector coordinates are distant less than epsilon
  3002. * @param otherVector defines the second operand
  3003. * @param epsilon defines the minimal distance to define values as equals
  3004. * @returns true if both vectors are distant less than epsilon
  3005. */
  3006. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3007. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3008. 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);
  3009. };
  3010. /**
  3011. * Returns true if the current Vector3 coordinates equals the passed floats
  3012. * @param x defines the x coordinate of the operand
  3013. * @param y defines the y coordinate of the operand
  3014. * @param z defines the z coordinate of the operand
  3015. * @returns true if both vectors are equals
  3016. */
  3017. Vector3.prototype.equalsToFloats = function (x, y, z) {
  3018. return this.x === x && this.y === y && this.z === z;
  3019. };
  3020. /**
  3021. * Multiplies the current Vector3 coordinates by the passed ones
  3022. * @param otherVector defines the second operand
  3023. * @returns the current updated Vector3
  3024. */
  3025. Vector3.prototype.multiplyInPlace = function (otherVector) {
  3026. this.x *= otherVector.x;
  3027. this.y *= otherVector.y;
  3028. this.z *= otherVector.z;
  3029. return this;
  3030. };
  3031. /**
  3032. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector
  3033. * @param otherVector defines the second operand
  3034. * @returns the new Vector3
  3035. */
  3036. Vector3.prototype.multiply = function (otherVector) {
  3037. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  3038. };
  3039. /**
  3040. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result"
  3041. * @param otherVector defines the second operand
  3042. * @param result defines the Vector3 object where to store the result
  3043. * @returns the current Vector3
  3044. */
  3045. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  3046. result.x = this.x * otherVector.x;
  3047. result.y = this.y * otherVector.y;
  3048. result.z = this.z * otherVector.z;
  3049. return this;
  3050. };
  3051. /**
  3052. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the passed floats
  3053. * @param x defines the x coordinate of the operand
  3054. * @param y defines the y coordinate of the operand
  3055. * @param z defines the z coordinate of the operand
  3056. * @returns the new Vector3
  3057. */
  3058. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  3059. return new Vector3(this.x * x, this.y * y, this.z * z);
  3060. };
  3061. /**
  3062. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the passed ones
  3063. * @param otherVector defines the second operand
  3064. * @returns the new Vector3
  3065. */
  3066. Vector3.prototype.divide = function (otherVector) {
  3067. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3068. };
  3069. /**
  3070. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result"
  3071. * @param otherVector defines the second operand
  3072. * @param result defines the Vector3 object where to store the result
  3073. * @returns the current Vector3
  3074. */
  3075. Vector3.prototype.divideToRef = function (otherVector, result) {
  3076. result.x = this.x / otherVector.x;
  3077. result.y = this.y / otherVector.y;
  3078. result.z = this.z / otherVector.z;
  3079. return this;
  3080. };
  3081. /**
  3082. * Divides the current Vector3 coordinates by the passed ones.
  3083. * @param otherVector defines the second operand
  3084. * @returns the current updated Vector3
  3085. */
  3086. Vector3.prototype.divideInPlace = function (otherVector) {
  3087. return this.divideToRef(otherVector, this);
  3088. };
  3089. /**
  3090. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones
  3091. * @param other defines the second operand
  3092. * @returns the current updated Vector3
  3093. */
  3094. Vector3.prototype.minimizeInPlace = function (other) {
  3095. if (other.x < this.x)
  3096. this.x = other.x;
  3097. if (other.y < this.y)
  3098. this.y = other.y;
  3099. if (other.z < this.z)
  3100. this.z = other.z;
  3101. return this;
  3102. };
  3103. /**
  3104. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  3105. * @param other defines the second operand
  3106. * @returns the current updated Vector3
  3107. */
  3108. Vector3.prototype.maximizeInPlace = function (other) {
  3109. if (other.x > this.x)
  3110. this.x = other.x;
  3111. if (other.y > this.y)
  3112. this.y = other.y;
  3113. if (other.z > this.z)
  3114. this.z = other.z;
  3115. return this;
  3116. };
  3117. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3118. /**
  3119. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3120. */
  3121. get: function () {
  3122. var absX = Math.abs(this.x);
  3123. var absY = Math.abs(this.y);
  3124. if (absX !== absY) {
  3125. return true;
  3126. }
  3127. var absZ = Math.abs(this.z);
  3128. if (absX !== absZ) {
  3129. return true;
  3130. }
  3131. if (absY !== absZ) {
  3132. return true;
  3133. }
  3134. return false;
  3135. },
  3136. enumerable: true,
  3137. configurable: true
  3138. });
  3139. // Properties
  3140. /**
  3141. * Gets the length of the Vector3
  3142. * @returns the length of the Vecto3
  3143. */
  3144. Vector3.prototype.length = function () {
  3145. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3146. };
  3147. /**
  3148. * Gets the squared length of the Vector3
  3149. * @returns squared length of the Vector3
  3150. */
  3151. Vector3.prototype.lengthSquared = function () {
  3152. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3153. };
  3154. /**
  3155. * Normalize the current Vector3.
  3156. * Please note that this is an in place operation.
  3157. * @returns the current updated Vector3
  3158. */
  3159. Vector3.prototype.normalize = function () {
  3160. var len = this.length();
  3161. if (len === 0 || len === 1.0)
  3162. return this;
  3163. var num = 1.0 / len;
  3164. this.x *= num;
  3165. this.y *= num;
  3166. this.z *= num;
  3167. return this;
  3168. };
  3169. /**
  3170. * Normalize the current Vector3 to a new vector
  3171. * @returns the new Vector3
  3172. */
  3173. Vector3.prototype.normalizeToNew = function () {
  3174. var normalized = new Vector3(0, 0, 0);
  3175. this.normalizeToRef(normalized);
  3176. return normalized;
  3177. };
  3178. /**
  3179. * Normalize the current Vector3 to the reference
  3180. * @param reference define the Vector3 to update
  3181. * @returns the updated Vector3
  3182. */
  3183. Vector3.prototype.normalizeToRef = function (reference) {
  3184. var len = this.length();
  3185. if (len === 0 || len === 1.0) {
  3186. reference.set(this.x, this.y, this.z);
  3187. return reference;
  3188. }
  3189. var scale = 1.0 / len;
  3190. this.scaleToRef(scale, reference);
  3191. return reference;
  3192. };
  3193. /**
  3194. * Creates a new Vector3 copied from the current Vector3
  3195. * @returns the new Vector3
  3196. */
  3197. Vector3.prototype.clone = function () {
  3198. return new Vector3(this.x, this.y, this.z);
  3199. };
  3200. /**
  3201. * Copies the passed vector coordinates to the current Vector3 ones
  3202. * @param source defines the source Vector3
  3203. * @returns the current updated Vector3
  3204. */
  3205. Vector3.prototype.copyFrom = function (source) {
  3206. this.x = source.x;
  3207. this.y = source.y;
  3208. this.z = source.z;
  3209. return this;
  3210. };
  3211. /**
  3212. * Copies the passed floats to the current Vector3 coordinates
  3213. * @param x defines the x coordinate of the operand
  3214. * @param y defines the y coordinate of the operand
  3215. * @param z defines the z coordinate of the operand
  3216. * @returns the current updated Vector3
  3217. */
  3218. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3219. this.x = x;
  3220. this.y = y;
  3221. this.z = z;
  3222. return this;
  3223. };
  3224. /**
  3225. * Copies the passed floats to the current Vector3 coordinates
  3226. * @param x defines the x coordinate of the operand
  3227. * @param y defines the y coordinate of the operand
  3228. * @param z defines the z coordinate of the operand
  3229. * @returns the current updated Vector3
  3230. */
  3231. Vector3.prototype.set = function (x, y, z) {
  3232. return this.copyFromFloats(x, y, z);
  3233. };
  3234. // Statics
  3235. /**
  3236. * Get the clip factor between two vectors
  3237. * @param vector0 defines the first operand
  3238. * @param vector1 defines the second operand
  3239. * @param axis defines the axis to use
  3240. * @param size defines the size along the axis
  3241. * @returns the clip factor
  3242. */
  3243. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3244. var d0 = Vector3.Dot(vector0, axis) - size;
  3245. var d1 = Vector3.Dot(vector1, axis) - size;
  3246. var s = d0 / (d0 - d1);
  3247. return s;
  3248. };
  3249. /**
  3250. * Get angle between two vectors
  3251. * @param vector0 angle between vector0 and vector1
  3252. * @param vector1 angle between vector0 and vector1
  3253. * @param normal direction of the normal
  3254. * @return the angle between vector0 and vector1
  3255. */
  3256. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3257. var v0 = vector0.clone().normalize();
  3258. var v1 = vector1.clone().normalize();
  3259. var dot = Vector3.Dot(v0, v1);
  3260. var n = Vector3.Cross(v0, v1);
  3261. if (Vector3.Dot(n, normal) > 0) {
  3262. return Math.acos(dot);
  3263. }
  3264. return -Math.acos(dot);
  3265. };
  3266. /**
  3267. * Returns a new Vector3 set from the index "offset" of the passed array
  3268. * @param array defines the source array
  3269. * @param offset defines the offset in the source array
  3270. * @returns the new Vector3
  3271. */
  3272. Vector3.FromArray = function (array, offset) {
  3273. if (!offset) {
  3274. offset = 0;
  3275. }
  3276. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3277. };
  3278. /**
  3279. * Returns a new Vector3 set from the index "offset" of the passed Float32Array
  3280. * This function is deprecated. Use FromArray instead
  3281. * @param array defines the source array
  3282. * @param offset defines the offset in the source array
  3283. * @returns the new Vector3
  3284. */
  3285. Vector3.FromFloatArray = function (array, offset) {
  3286. return Vector3.FromArray(array, offset);
  3287. };
  3288. /**
  3289. * Sets the passed vector "result" with the element values from the index "offset" of the passed array
  3290. * @param array defines the source array
  3291. * @param offset defines the offset in the source array
  3292. * @param result defines the Vector3 where to store the result
  3293. */
  3294. Vector3.FromArrayToRef = function (array, offset, result) {
  3295. result.x = array[offset];
  3296. result.y = array[offset + 1];
  3297. result.z = array[offset + 2];
  3298. };
  3299. /**
  3300. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array
  3301. * This function is deprecated. Use FromArrayToRef instead.
  3302. * @param array defines the source array
  3303. * @param offset defines the offset in the source array
  3304. * @param result defines the Vector3 where to store the result
  3305. */
  3306. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3307. return Vector3.FromArrayToRef(array, offset, result);
  3308. };
  3309. /**
  3310. * Sets the passed vector "result" with the passed floats.
  3311. * @param x defines the x coordinate of the source
  3312. * @param y defines the y coordinate of the source
  3313. * @param z defines the z coordinate of the source
  3314. * @param result defines the Vector3 where to store the result
  3315. */
  3316. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3317. result.x = x;
  3318. result.y = y;
  3319. result.z = z;
  3320. };
  3321. /**
  3322. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3323. * @returns a new empty Vector3
  3324. */
  3325. Vector3.Zero = function () {
  3326. return new Vector3(0.0, 0.0, 0.0);
  3327. };
  3328. /**
  3329. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3330. * @returns a new unit Vector3
  3331. */
  3332. Vector3.One = function () {
  3333. return new Vector3(1.0, 1.0, 1.0);
  3334. };
  3335. /**
  3336. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3337. * @returns a new up Vector3
  3338. */
  3339. Vector3.Up = function () {
  3340. return new Vector3(0.0, 1.0, 0.0);
  3341. };
  3342. /**
  3343. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3344. * @returns a new forward Vector3
  3345. */
  3346. Vector3.Forward = function () {
  3347. return new Vector3(0.0, 0.0, 1.0);
  3348. };
  3349. /**
  3350. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3351. * @returns a new right Vector3
  3352. */
  3353. Vector3.Right = function () {
  3354. return new Vector3(1.0, 0.0, 0.0);
  3355. };
  3356. /**
  3357. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3358. * @returns a new left Vector3
  3359. */
  3360. Vector3.Left = function () {
  3361. return new Vector3(-1.0, 0.0, 0.0);
  3362. };
  3363. /**
  3364. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  3365. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3366. * @param vector defines the Vector3 to transform
  3367. * @param transformation defines the transformation matrix
  3368. * @returns the transformed Vector3
  3369. */
  3370. Vector3.TransformCoordinates = function (vector, transformation) {
  3371. var result = Vector3.Zero();
  3372. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3373. return result;
  3374. };
  3375. /**
  3376. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector
  3377. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3378. * @param vector defines the Vector3 to transform
  3379. * @param transformation defines the transformation matrix
  3380. * @param result defines the Vector3 where to store the result
  3381. */
  3382. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3383. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3384. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3385. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3386. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3387. result.x = x / w;
  3388. result.y = y / w;
  3389. result.z = z / w;
  3390. };
  3391. /**
  3392. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z)
  3393. * This method computes tranformed coordinates only, not transformed direction vectors
  3394. * @param x define the x coordinate of the source vector
  3395. * @param y define the y coordinate of the source vector
  3396. * @param z define the z coordinate of the source vector
  3397. * @param transformation defines the transformation matrix
  3398. * @param result defines the Vector3 where to store the result
  3399. */
  3400. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3401. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3402. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3403. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3404. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3405. result.x = rx / rw;
  3406. result.y = ry / rw;
  3407. result.z = rz / rw;
  3408. };
  3409. /**
  3410. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector
  3411. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3412. * @param vector defines the Vector3 to transform
  3413. * @param transformation defines the transformation matrix
  3414. * @returns the new Vector3
  3415. */
  3416. Vector3.TransformNormal = function (vector, transformation) {
  3417. var result = Vector3.Zero();
  3418. Vector3.TransformNormalToRef(vector, transformation, result);
  3419. return result;
  3420. };
  3421. /**
  3422. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector
  3423. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3424. * @param vector defines the Vector3 to transform
  3425. * @param transformation defines the transformation matrix
  3426. * @param result defines the Vector3 where to store the result
  3427. */
  3428. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3429. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3430. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3431. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3432. result.x = x;
  3433. result.y = y;
  3434. result.z = z;
  3435. };
  3436. /**
  3437. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z)
  3438. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3439. * @param x define the x coordinate of the source vector
  3440. * @param y define the y coordinate of the source vector
  3441. * @param z define the z coordinate of the source vector
  3442. * @param transformation defines the transformation matrix
  3443. * @param result defines the Vector3 where to store the result
  3444. */
  3445. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3446. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3447. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3448. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3449. };
  3450. /**
  3451. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3452. * @param value1 defines the first control point
  3453. * @param value2 defines the second control point
  3454. * @param value3 defines the third control point
  3455. * @param value4 defines the fourth control point
  3456. * @param amount defines the amount on the spline to use
  3457. * @returns the new Vector3
  3458. */
  3459. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3460. var squared = amount * amount;
  3461. var cubed = amount * squared;
  3462. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3463. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3464. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3465. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3466. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3467. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3468. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3469. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3470. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3471. return new Vector3(x, y, z);
  3472. };
  3473. /**
  3474. * 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"
  3475. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3476. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3477. * @param value defines the current value
  3478. * @param min defines the lower range value
  3479. * @param max defines the upper range value
  3480. * @returns the new Vector3
  3481. */
  3482. Vector3.Clamp = function (value, min, max) {
  3483. var x = value.x;
  3484. x = (x > max.x) ? max.x : x;
  3485. x = (x < min.x) ? min.x : x;
  3486. var y = value.y;
  3487. y = (y > max.y) ? max.y : y;
  3488. y = (y < min.y) ? min.y : y;
  3489. var z = value.z;
  3490. z = (z > max.z) ? max.z : z;
  3491. z = (z < min.z) ? min.z : z;
  3492. return new Vector3(x, y, z);
  3493. };
  3494. /**
  3495. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3496. * @param value1 defines the first control point
  3497. * @param tangent1 defines the first tangent vector
  3498. * @param value2 defines the second control point
  3499. * @param tangent2 defines the second tangent vector
  3500. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3501. * @returns the new Vector3
  3502. */
  3503. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3504. var squared = amount * amount;
  3505. var cubed = amount * squared;
  3506. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3507. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3508. var part3 = (cubed - (2.0 * squared)) + amount;
  3509. var part4 = cubed - squared;
  3510. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3511. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3512. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3513. return new Vector3(x, y, z);
  3514. };
  3515. /**
  3516. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3517. * @param start defines the start value
  3518. * @param end defines the end value
  3519. * @param amount max defines amount between both (between 0 and 1)
  3520. * @returns the new Vector3
  3521. */
  3522. Vector3.Lerp = function (start, end, amount) {
  3523. var result = new Vector3(0, 0, 0);
  3524. Vector3.LerpToRef(start, end, amount, result);
  3525. return result;
  3526. };
  3527. /**
  3528. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3529. * @param start defines the start value
  3530. * @param end defines the end value
  3531. * @param amount max defines amount between both (between 0 and 1)
  3532. * @param result defines the Vector3 where to store the result
  3533. */
  3534. Vector3.LerpToRef = function (start, end, amount, result) {
  3535. result.x = start.x + ((end.x - start.x) * amount);
  3536. result.y = start.y + ((end.y - start.y) * amount);
  3537. result.z = start.z + ((end.z - start.z) * amount);
  3538. };
  3539. /**
  3540. * Returns the dot product (float) between the vectors "left" and "right"
  3541. * @param left defines the left operand
  3542. * @param right defines the right operand
  3543. * @returns the dot product
  3544. */
  3545. Vector3.Dot = function (left, right) {
  3546. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3547. };
  3548. /**
  3549. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3550. * The cross product is then orthogonal to both "left" and "right"
  3551. * @param left defines the left operand
  3552. * @param right defines the right operand
  3553. * @returns the cross product
  3554. */
  3555. Vector3.Cross = function (left, right) {
  3556. var result = Vector3.Zero();
  3557. Vector3.CrossToRef(left, right, result);
  3558. return result;
  3559. };
  3560. /**
  3561. * Sets the passed vector "result" with the cross product of "left" and "right"
  3562. * The cross product is then orthogonal to both "left" and "right"
  3563. * @param left defines the left operand
  3564. * @param right defines the right operand
  3565. * @param result defines the Vector3 where to store the result
  3566. */
  3567. Vector3.CrossToRef = function (left, right, result) {
  3568. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3569. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3570. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3571. result.copyFrom(MathTmp.Vector3[0]);
  3572. };
  3573. /**
  3574. * Returns a new Vector3 as the normalization of the passed vector
  3575. * @param vector defines the Vector3 to normalize
  3576. * @returns the new Vector3
  3577. */
  3578. Vector3.Normalize = function (vector) {
  3579. var result = Vector3.Zero();
  3580. Vector3.NormalizeToRef(vector, result);
  3581. return result;
  3582. };
  3583. /**
  3584. * Sets the passed vector "result" with the normalization of the passed first vector
  3585. * @param vector defines the Vector3 to normalize
  3586. * @param result defines the Vector3 where to store the result
  3587. */
  3588. Vector3.NormalizeToRef = function (vector, result) {
  3589. result.copyFrom(vector);
  3590. result.normalize();
  3591. };
  3592. /**
  3593. * Project a Vector3 onto screen space
  3594. * @param vector defines the Vector3 to project
  3595. * @param world defines the world matrix to use
  3596. * @param transform defines the transform (view x projection) matrix to use
  3597. * @param viewport defines the screen viewport to use
  3598. * @returns the new Vector3
  3599. */
  3600. Vector3.Project = function (vector, world, transform, viewport) {
  3601. var cw = viewport.width;
  3602. var ch = viewport.height;
  3603. var cx = viewport.x;
  3604. var cy = viewport.y;
  3605. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3606. 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);
  3607. var matrix = MathTmp.Matrix[0];
  3608. world.multiplyToRef(transform, matrix);
  3609. matrix.multiplyToRef(viewportMatrix, matrix);
  3610. return Vector3.TransformCoordinates(vector, matrix);
  3611. };
  3612. /**
  3613. * Unproject from screen space to object space
  3614. * @param source defines the screen space Vector3 to use
  3615. * @param viewportWidth defines the current width of the viewport
  3616. * @param viewportHeight defines the current height of the viewport
  3617. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3618. * @param transform defines the transform (view x projection) matrix to use
  3619. * @returns the new Vector3
  3620. */
  3621. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3622. var matrix = MathTmp.Matrix[0];
  3623. world.multiplyToRef(transform, matrix);
  3624. matrix.invert();
  3625. source.x = source.x / viewportWidth * 2 - 1;
  3626. source.y = -(source.y / viewportHeight * 2 - 1);
  3627. var vector = Vector3.TransformCoordinates(source, matrix);
  3628. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3629. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3630. vector = vector.scale(1.0 / num);
  3631. }
  3632. return vector;
  3633. };
  3634. /**
  3635. * Unproject from screen space to object space
  3636. * @param source defines the screen space Vector3 to use
  3637. * @param viewportWidth defines the current width of the viewport
  3638. * @param viewportHeight defines the current height of the viewport
  3639. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3640. * @param view defines the view matrix to use
  3641. * @param projection defines the projection matrix to use
  3642. * @returns the new Vector3
  3643. */
  3644. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3645. var result = Vector3.Zero();
  3646. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3647. return result;
  3648. };
  3649. /**
  3650. * Unproject from screen space to object space
  3651. * @param source defines the screen space Vector3 to use
  3652. * @param viewportWidth defines the current width of the viewport
  3653. * @param viewportHeight defines the current height of the viewport
  3654. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3655. * @param view defines the view matrix to use
  3656. * @param projection defines the projection matrix to use
  3657. * @param result defines the Vector3 where to store the result
  3658. */
  3659. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3660. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3661. };
  3662. /**
  3663. * Unproject from screen space to object space
  3664. * @param sourceX defines the screen space x coordinate to use
  3665. * @param sourceY defines the screen space y coordinate to use
  3666. * @param sourceZ defines the screen space z coordinate to use
  3667. * @param viewportWidth defines the current width of the viewport
  3668. * @param viewportHeight defines the current height of the viewport
  3669. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3670. * @param view defines the view matrix to use
  3671. * @param projection defines the projection matrix to use
  3672. * @param result defines the Vector3 where to store the result
  3673. */
  3674. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3675. var matrix = MathTmp.Matrix[0];
  3676. world.multiplyToRef(view, matrix);
  3677. matrix.multiplyToRef(projection, matrix);
  3678. matrix.invert();
  3679. var screenSource = MathTmp.Vector3[0];
  3680. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3681. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3682. screenSource.z = 2 * sourceZ - 1.0;
  3683. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3684. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3685. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3686. result.scaleInPlace(1.0 / num);
  3687. }
  3688. };
  3689. /**
  3690. * Gets the minimal coordinate values between two Vector3
  3691. * @param left defines the first operand
  3692. * @param right defines the second operand
  3693. * @returns the new Vector3
  3694. */
  3695. Vector3.Minimize = function (left, right) {
  3696. var min = left.clone();
  3697. min.minimizeInPlace(right);
  3698. return min;
  3699. };
  3700. /**
  3701. * Gets the maximal coordinate values between two Vector3
  3702. * @param left defines the first operand
  3703. * @param right defines the second operand
  3704. * @returns the new Vector3
  3705. */
  3706. Vector3.Maximize = function (left, right) {
  3707. var max = left.clone();
  3708. max.maximizeInPlace(right);
  3709. return max;
  3710. };
  3711. /**
  3712. * Returns the distance between the vectors "value1" and "value2"
  3713. * @param value1 defines the first operand
  3714. * @param value2 defines the second operand
  3715. * @returns the distance
  3716. */
  3717. Vector3.Distance = function (value1, value2) {
  3718. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3719. };
  3720. /**
  3721. * Returns the squared distance between the vectors "value1" and "value2"
  3722. * @param value1 defines the first operand
  3723. * @param value2 defines the second operand
  3724. * @returns the squared distance
  3725. */
  3726. Vector3.DistanceSquared = function (value1, value2) {
  3727. var x = value1.x - value2.x;
  3728. var y = value1.y - value2.y;
  3729. var z = value1.z - value2.z;
  3730. return (x * x) + (y * y) + (z * z);
  3731. };
  3732. /**
  3733. * Returns a new Vector3 located at the center between "value1" and "value2"
  3734. * @param value1 defines the first operand
  3735. * @param value2 defines the second operand
  3736. * @returns the new Vector3
  3737. */
  3738. Vector3.Center = function (value1, value2) {
  3739. var center = value1.add(value2);
  3740. center.scaleInPlace(0.5);
  3741. return center;
  3742. };
  3743. /**
  3744. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3745. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3746. * to something in order to rotate it from its local system to the given target system
  3747. * Note: axis1, axis2 and axis3 are normalized during this operation
  3748. * @param axis1 defines the first axis
  3749. * @param axis2 defines the second axis
  3750. * @param axis3 defines the third axis
  3751. * @returns a new Vector3
  3752. */
  3753. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3754. var rotation = Vector3.Zero();
  3755. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3756. return rotation;
  3757. };
  3758. /**
  3759. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3
  3760. * @param axis1 defines the first axis
  3761. * @param axis2 defines the second axis
  3762. * @param axis3 defines the third axis
  3763. * @param ref defines the Vector3 where to store the result
  3764. */
  3765. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3766. var quat = MathTmp.Quaternion[0];
  3767. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3768. quat.toEulerAnglesToRef(ref);
  3769. };
  3770. return Vector3;
  3771. }());
  3772. BABYLON.Vector3 = Vector3;
  3773. //Vector4 class created for EulerAngle class conversion to Quaternion
  3774. var Vector4 = /** @class */ (function () {
  3775. /**
  3776. * Creates a Vector4 object from the passed floats.
  3777. */
  3778. function Vector4(x, y, z, w) {
  3779. this.x = x;
  3780. this.y = y;
  3781. this.z = z;
  3782. this.w = w;
  3783. }
  3784. /**
  3785. * Returns the string with the Vector4 coordinates.
  3786. */
  3787. Vector4.prototype.toString = function () {
  3788. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3789. };
  3790. /**
  3791. * Returns the string "Vector4".
  3792. */
  3793. Vector4.prototype.getClassName = function () {
  3794. return "Vector4";
  3795. };
  3796. /**
  3797. * Returns the Vector4 hash code.
  3798. */
  3799. Vector4.prototype.getHashCode = function () {
  3800. var hash = this.x || 0;
  3801. hash = (hash * 397) ^ (this.y || 0);
  3802. hash = (hash * 397) ^ (this.z || 0);
  3803. hash = (hash * 397) ^ (this.w || 0);
  3804. return hash;
  3805. };
  3806. // Operators
  3807. /**
  3808. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3809. */
  3810. Vector4.prototype.asArray = function () {
  3811. var result = new Array();
  3812. this.toArray(result, 0);
  3813. return result;
  3814. };
  3815. /**
  3816. * Populates the passed array from the passed index with the Vector4 coordinates.
  3817. * Returns the Vector4.
  3818. */
  3819. Vector4.prototype.toArray = function (array, index) {
  3820. if (index === undefined) {
  3821. index = 0;
  3822. }
  3823. array[index] = this.x;
  3824. array[index + 1] = this.y;
  3825. array[index + 2] = this.z;
  3826. array[index + 3] = this.w;
  3827. return this;
  3828. };
  3829. /**
  3830. * Adds the passed vector to the current Vector4.
  3831. * Returns the updated Vector4.
  3832. */
  3833. Vector4.prototype.addInPlace = function (otherVector) {
  3834. this.x += otherVector.x;
  3835. this.y += otherVector.y;
  3836. this.z += otherVector.z;
  3837. this.w += otherVector.w;
  3838. return this;
  3839. };
  3840. /**
  3841. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  3842. */
  3843. Vector4.prototype.add = function (otherVector) {
  3844. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3845. };
  3846. /**
  3847. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  3848. * Returns the current Vector4.
  3849. */
  3850. Vector4.prototype.addToRef = function (otherVector, result) {
  3851. result.x = this.x + otherVector.x;
  3852. result.y = this.y + otherVector.y;
  3853. result.z = this.z + otherVector.z;
  3854. result.w = this.w + otherVector.w;
  3855. return this;
  3856. };
  3857. /**
  3858. * Subtract in place the passed vector from the current Vector4.
  3859. * Returns the updated Vector4.
  3860. */
  3861. Vector4.prototype.subtractInPlace = function (otherVector) {
  3862. this.x -= otherVector.x;
  3863. this.y -= otherVector.y;
  3864. this.z -= otherVector.z;
  3865. this.w -= otherVector.w;
  3866. return this;
  3867. };
  3868. /**
  3869. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  3870. */
  3871. Vector4.prototype.subtract = function (otherVector) {
  3872. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3873. };
  3874. /**
  3875. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  3876. * Returns the current Vector4.
  3877. */
  3878. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3879. result.x = this.x - otherVector.x;
  3880. result.y = this.y - otherVector.y;
  3881. result.z = this.z - otherVector.z;
  3882. result.w = this.w - otherVector.w;
  3883. return this;
  3884. };
  3885. /**
  3886. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3887. */
  3888. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3889. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3890. };
  3891. /**
  3892. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3893. * Returns the current Vector4.
  3894. */
  3895. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3896. result.x = this.x - x;
  3897. result.y = this.y - y;
  3898. result.z = this.z - z;
  3899. result.w = this.w - w;
  3900. return this;
  3901. };
  3902. /**
  3903. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3904. */
  3905. Vector4.prototype.negate = function () {
  3906. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3907. };
  3908. /**
  3909. * Multiplies the current Vector4 coordinates by scale (float).
  3910. * Returns the updated Vector4.
  3911. */
  3912. Vector4.prototype.scaleInPlace = function (scale) {
  3913. this.x *= scale;
  3914. this.y *= scale;
  3915. this.z *= scale;
  3916. this.w *= scale;
  3917. return this;
  3918. };
  3919. /**
  3920. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3921. */
  3922. Vector4.prototype.scale = function (scale) {
  3923. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3924. };
  3925. /**
  3926. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3927. * Returns the current Vector4.
  3928. */
  3929. Vector4.prototype.scaleToRef = function (scale, result) {
  3930. result.x = this.x * scale;
  3931. result.y = this.y * scale;
  3932. result.z = this.z * scale;
  3933. result.w = this.w * scale;
  3934. return this;
  3935. };
  3936. /**
  3937. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  3938. * @param scale defines the scale factor
  3939. * @param result defines the Vector4 object where to store the result
  3940. * @returns the unmodified current Vector4
  3941. */
  3942. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  3943. result.x += this.x * scale;
  3944. result.y += this.y * scale;
  3945. result.z += this.z * scale;
  3946. result.w += this.w * scale;
  3947. return this;
  3948. };
  3949. /**
  3950. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  3951. */
  3952. Vector4.prototype.equals = function (otherVector) {
  3953. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3954. };
  3955. /**
  3956. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  3957. */
  3958. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3959. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3960. return otherVector
  3961. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3962. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3963. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3964. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3965. };
  3966. /**
  3967. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  3968. */
  3969. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3970. return this.x === x && this.y === y && this.z === z && this.w === w;
  3971. };
  3972. /**
  3973. * Multiplies in place the current Vector4 by the passed one.
  3974. * Returns the updated Vector4.
  3975. */
  3976. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3977. this.x *= otherVector.x;
  3978. this.y *= otherVector.y;
  3979. this.z *= otherVector.z;
  3980. this.w *= otherVector.w;
  3981. return this;
  3982. };
  3983. /**
  3984. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  3985. */
  3986. Vector4.prototype.multiply = function (otherVector) {
  3987. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3988. };
  3989. /**
  3990. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  3991. * Returns the current Vector4.
  3992. */
  3993. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3994. result.x = this.x * otherVector.x;
  3995. result.y = this.y * otherVector.y;
  3996. result.z = this.z * otherVector.z;
  3997. result.w = this.w * otherVector.w;
  3998. return this;
  3999. };
  4000. /**
  4001. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  4002. */
  4003. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  4004. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  4005. };
  4006. /**
  4007. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  4008. */
  4009. Vector4.prototype.divide = function (otherVector) {
  4010. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  4011. };
  4012. /**
  4013. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  4014. * Returns the current Vector4.
  4015. */
  4016. Vector4.prototype.divideToRef = function (otherVector, result) {
  4017. result.x = this.x / otherVector.x;
  4018. result.y = this.y / otherVector.y;
  4019. result.z = this.z / otherVector.z;
  4020. result.w = this.w / otherVector.w;
  4021. return this;
  4022. };
  4023. /**
  4024. * Divides the current Vector3 coordinates by the passed ones.
  4025. * @returns the updated Vector3.
  4026. */
  4027. Vector4.prototype.divideInPlace = function (otherVector) {
  4028. return this.divideToRef(otherVector, this);
  4029. };
  4030. /**
  4031. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones
  4032. * @param other defines the second operand
  4033. * @returns the current updated Vector4
  4034. */
  4035. Vector4.prototype.minimizeInPlace = function (other) {
  4036. if (other.x < this.x)
  4037. this.x = other.x;
  4038. if (other.y < this.y)
  4039. this.y = other.y;
  4040. if (other.z < this.z)
  4041. this.z = other.z;
  4042. if (other.w < this.w)
  4043. this.w = other.w;
  4044. return this;
  4045. };
  4046. /**
  4047. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones
  4048. * @param other defines the second operand
  4049. * @returns the current updated Vector4
  4050. */
  4051. Vector4.prototype.maximizeInPlace = function (other) {
  4052. if (other.x > this.x)
  4053. this.x = other.x;
  4054. if (other.y > this.y)
  4055. this.y = other.y;
  4056. if (other.z > this.z)
  4057. this.z = other.z;
  4058. if (other.w > this.w)
  4059. this.w = other.w;
  4060. return this;
  4061. };
  4062. // Properties
  4063. /**
  4064. * Returns the Vector4 length (float).
  4065. */
  4066. Vector4.prototype.length = function () {
  4067. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4068. };
  4069. /**
  4070. * Returns the Vector4 squared length (float).
  4071. */
  4072. Vector4.prototype.lengthSquared = function () {
  4073. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4074. };
  4075. // Methods
  4076. /**
  4077. * Normalizes in place the Vector4.
  4078. * Returns the updated Vector4.
  4079. */
  4080. Vector4.prototype.normalize = function () {
  4081. var len = this.length();
  4082. if (len === 0)
  4083. return this;
  4084. var num = 1.0 / len;
  4085. this.x *= num;
  4086. this.y *= num;
  4087. this.z *= num;
  4088. this.w *= num;
  4089. return this;
  4090. };
  4091. /**
  4092. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4093. */
  4094. Vector4.prototype.toVector3 = function () {
  4095. return new Vector3(this.x, this.y, this.z);
  4096. };
  4097. /**
  4098. * Returns a new Vector4 copied from the current one.
  4099. */
  4100. Vector4.prototype.clone = function () {
  4101. return new Vector4(this.x, this.y, this.z, this.w);
  4102. };
  4103. /**
  4104. * Updates the current Vector4 with the passed one coordinates.
  4105. * Returns the updated Vector4.
  4106. */
  4107. Vector4.prototype.copyFrom = function (source) {
  4108. this.x = source.x;
  4109. this.y = source.y;
  4110. this.z = source.z;
  4111. this.w = source.w;
  4112. return this;
  4113. };
  4114. /**
  4115. * Updates the current Vector4 coordinates with the passed floats.
  4116. * Returns the updated Vector4.
  4117. */
  4118. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4119. this.x = x;
  4120. this.y = y;
  4121. this.z = z;
  4122. this.w = w;
  4123. return this;
  4124. };
  4125. /**
  4126. * Updates the current Vector4 coordinates with the passed floats.
  4127. * Returns the updated Vector4.
  4128. */
  4129. Vector4.prototype.set = function (x, y, z, w) {
  4130. return this.copyFromFloats(x, y, z, w);
  4131. };
  4132. // Statics
  4133. /**
  4134. * Returns a new Vector4 set from the starting index of the passed array.
  4135. */
  4136. Vector4.FromArray = function (array, offset) {
  4137. if (!offset) {
  4138. offset = 0;
  4139. }
  4140. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4141. };
  4142. /**
  4143. * Updates the passed vector "result" from the starting index of the passed array.
  4144. */
  4145. Vector4.FromArrayToRef = function (array, offset, result) {
  4146. result.x = array[offset];
  4147. result.y = array[offset + 1];
  4148. result.z = array[offset + 2];
  4149. result.w = array[offset + 3];
  4150. };
  4151. /**
  4152. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  4153. */
  4154. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4155. Vector4.FromArrayToRef(array, offset, result);
  4156. };
  4157. /**
  4158. * Updates the passed vector "result" coordinates from the passed floats.
  4159. */
  4160. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4161. result.x = x;
  4162. result.y = y;
  4163. result.z = z;
  4164. result.w = w;
  4165. };
  4166. /**
  4167. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4168. */
  4169. Vector4.Zero = function () {
  4170. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4171. };
  4172. /**
  4173. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4174. */
  4175. Vector4.One = function () {
  4176. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4177. };
  4178. /**
  4179. * Returns a new normalized Vector4 from the passed one.
  4180. */
  4181. Vector4.Normalize = function (vector) {
  4182. var result = Vector4.Zero();
  4183. Vector4.NormalizeToRef(vector, result);
  4184. return result;
  4185. };
  4186. /**
  4187. * Updates the passed vector "result" from the normalization of the passed one.
  4188. */
  4189. Vector4.NormalizeToRef = function (vector, result) {
  4190. result.copyFrom(vector);
  4191. result.normalize();
  4192. };
  4193. Vector4.Minimize = function (left, right) {
  4194. var min = left.clone();
  4195. min.minimizeInPlace(right);
  4196. return min;
  4197. };
  4198. Vector4.Maximize = function (left, right) {
  4199. var max = left.clone();
  4200. max.maximizeInPlace(right);
  4201. return max;
  4202. };
  4203. /**
  4204. * Returns the distance (float) between the vectors "value1" and "value2".
  4205. */
  4206. Vector4.Distance = function (value1, value2) {
  4207. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4208. };
  4209. /**
  4210. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4211. */
  4212. Vector4.DistanceSquared = function (value1, value2) {
  4213. var x = value1.x - value2.x;
  4214. var y = value1.y - value2.y;
  4215. var z = value1.z - value2.z;
  4216. var w = value1.w - value2.w;
  4217. return (x * x) + (y * y) + (z * z) + (w * w);
  4218. };
  4219. /**
  4220. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4221. */
  4222. Vector4.Center = function (value1, value2) {
  4223. var center = value1.add(value2);
  4224. center.scaleInPlace(0.5);
  4225. return center;
  4226. };
  4227. /**
  4228. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  4229. * This methods computes transformed normalized direction vectors only.
  4230. */
  4231. Vector4.TransformNormal = function (vector, transformation) {
  4232. var result = Vector4.Zero();
  4233. Vector4.TransformNormalToRef(vector, transformation, result);
  4234. return result;
  4235. };
  4236. /**
  4237. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  4238. * This methods computes transformed normalized direction vectors only.
  4239. */
  4240. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4241. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4242. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4243. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4244. result.x = x;
  4245. result.y = y;
  4246. result.z = z;
  4247. result.w = vector.w;
  4248. };
  4249. /**
  4250. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  4251. * This methods computes transformed normalized direction vectors only.
  4252. */
  4253. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4254. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4255. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4256. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4257. result.w = w;
  4258. };
  4259. return Vector4;
  4260. }());
  4261. BABYLON.Vector4 = Vector4;
  4262. var Size = /** @class */ (function () {
  4263. /**
  4264. * Creates a Size object from the passed width and height (floats).
  4265. */
  4266. function Size(width, height) {
  4267. this.width = width;
  4268. this.height = height;
  4269. }
  4270. // Returns a string with the Size width and height.
  4271. Size.prototype.toString = function () {
  4272. return "{W: " + this.width + ", H: " + this.height + "}";
  4273. };
  4274. /**
  4275. * Returns the string "Size"
  4276. */
  4277. Size.prototype.getClassName = function () {
  4278. return "Size";
  4279. };
  4280. /**
  4281. * Returns the Size hash code.
  4282. */
  4283. Size.prototype.getHashCode = function () {
  4284. var hash = this.width || 0;
  4285. hash = (hash * 397) ^ (this.height || 0);
  4286. return hash;
  4287. };
  4288. /**
  4289. * Updates the current size from the passed one.
  4290. * Returns the updated Size.
  4291. */
  4292. Size.prototype.copyFrom = function (src) {
  4293. this.width = src.width;
  4294. this.height = src.height;
  4295. };
  4296. /**
  4297. * Updates in place the current Size from the passed floats.
  4298. * Returns the updated Size.
  4299. */
  4300. Size.prototype.copyFromFloats = function (width, height) {
  4301. this.width = width;
  4302. this.height = height;
  4303. return this;
  4304. };
  4305. /**
  4306. * Updates in place the current Size from the passed floats.
  4307. * Returns the updated Size.
  4308. */
  4309. Size.prototype.set = function (width, height) {
  4310. return this.copyFromFloats(width, height);
  4311. };
  4312. /**
  4313. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  4314. */
  4315. Size.prototype.multiplyByFloats = function (w, h) {
  4316. return new Size(this.width * w, this.height * h);
  4317. };
  4318. /**
  4319. * Returns a new Size copied from the passed one.
  4320. */
  4321. Size.prototype.clone = function () {
  4322. return new Size(this.width, this.height);
  4323. };
  4324. /**
  4325. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  4326. */
  4327. Size.prototype.equals = function (other) {
  4328. if (!other) {
  4329. return false;
  4330. }
  4331. return (this.width === other.width) && (this.height === other.height);
  4332. };
  4333. Object.defineProperty(Size.prototype, "surface", {
  4334. /**
  4335. * Returns the surface of the Size : width * height (float).
  4336. */
  4337. get: function () {
  4338. return this.width * this.height;
  4339. },
  4340. enumerable: true,
  4341. configurable: true
  4342. });
  4343. /**
  4344. * Returns a new Size set to (0.0, 0.0)
  4345. */
  4346. Size.Zero = function () {
  4347. return new Size(0.0, 0.0);
  4348. };
  4349. /**
  4350. * Returns a new Size set as the addition result of the current Size and the passed one.
  4351. */
  4352. Size.prototype.add = function (otherSize) {
  4353. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4354. return r;
  4355. };
  4356. /**
  4357. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  4358. */
  4359. Size.prototype.subtract = function (otherSize) {
  4360. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4361. return r;
  4362. };
  4363. /**
  4364. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4365. */
  4366. Size.Lerp = function (start, end, amount) {
  4367. var w = start.width + ((end.width - start.width) * amount);
  4368. var h = start.height + ((end.height - start.height) * amount);
  4369. return new Size(w, h);
  4370. };
  4371. return Size;
  4372. }());
  4373. BABYLON.Size = Size;
  4374. var Quaternion = /** @class */ (function () {
  4375. /**
  4376. * Creates a new Quaternion from the passed floats.
  4377. */
  4378. function Quaternion(x, y, z, w) {
  4379. if (x === void 0) { x = 0.0; }
  4380. if (y === void 0) { y = 0.0; }
  4381. if (z === void 0) { z = 0.0; }
  4382. if (w === void 0) { w = 1.0; }
  4383. this.x = x;
  4384. this.y = y;
  4385. this.z = z;
  4386. this.w = w;
  4387. }
  4388. /**
  4389. * Returns a string with the Quaternion coordinates.
  4390. */
  4391. Quaternion.prototype.toString = function () {
  4392. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4393. };
  4394. /**
  4395. * Returns the string "Quaternion".
  4396. */
  4397. Quaternion.prototype.getClassName = function () {
  4398. return "Quaternion";
  4399. };
  4400. /**
  4401. * Returns the Quaternion hash code.
  4402. */
  4403. Quaternion.prototype.getHashCode = function () {
  4404. var hash = this.x || 0;
  4405. hash = (hash * 397) ^ (this.y || 0);
  4406. hash = (hash * 397) ^ (this.z || 0);
  4407. hash = (hash * 397) ^ (this.w || 0);
  4408. return hash;
  4409. };
  4410. /**
  4411. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  4412. */
  4413. Quaternion.prototype.asArray = function () {
  4414. return [this.x, this.y, this.z, this.w];
  4415. };
  4416. /**
  4417. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  4418. */
  4419. Quaternion.prototype.equals = function (otherQuaternion) {
  4420. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4421. };
  4422. /**
  4423. * Returns a new Quaternion copied from the current one.
  4424. */
  4425. Quaternion.prototype.clone = function () {
  4426. return new Quaternion(this.x, this.y, this.z, this.w);
  4427. };
  4428. /**
  4429. * Updates the current Quaternion from the passed one coordinates.
  4430. * Returns the updated Quaterion.
  4431. */
  4432. Quaternion.prototype.copyFrom = function (other) {
  4433. this.x = other.x;
  4434. this.y = other.y;
  4435. this.z = other.z;
  4436. this.w = other.w;
  4437. return this;
  4438. };
  4439. /**
  4440. * Updates the current Quaternion from the passed float coordinates.
  4441. * Returns the updated Quaterion.
  4442. */
  4443. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4444. this.x = x;
  4445. this.y = y;
  4446. this.z = z;
  4447. this.w = w;
  4448. return this;
  4449. };
  4450. /**
  4451. * Updates the current Quaternion from the passed float coordinates.
  4452. * Returns the updated Quaterion.
  4453. */
  4454. Quaternion.prototype.set = function (x, y, z, w) {
  4455. return this.copyFromFloats(x, y, z, w);
  4456. };
  4457. /**
  4458. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  4459. */
  4460. Quaternion.prototype.add = function (other) {
  4461. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4462. };
  4463. /**
  4464. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  4465. */
  4466. Quaternion.prototype.subtract = function (other) {
  4467. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4468. };
  4469. /**
  4470. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  4471. */
  4472. Quaternion.prototype.scale = function (value) {
  4473. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4474. };
  4475. /**
  4476. * Scale the current Quaternion values by a factor to a given Quaternion
  4477. * @param scale defines the scale factor
  4478. * @param result defines the Quaternion object where to store the result
  4479. * @returns the unmodified current Quaternion
  4480. */
  4481. Quaternion.prototype.scaleToRef = function (scale, result) {
  4482. result.x = this.x * scale;
  4483. result.y = this.y * scale;
  4484. result.z = this.z * scale;
  4485. result.w = this.w * scale;
  4486. return this;
  4487. };
  4488. /**
  4489. * Scale the current Quaternion values by a factor and add the result to a given Quaternion
  4490. * @param scale defines the scale factor
  4491. * @param result defines the Quaternion object where to store the result
  4492. * @returns the unmodified current Quaternion
  4493. */
  4494. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4495. result.x += this.x * scale;
  4496. result.y += this.y * scale;
  4497. result.z += this.z * scale;
  4498. result.w += this.w * scale;
  4499. return this;
  4500. };
  4501. /**
  4502. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  4503. */
  4504. Quaternion.prototype.multiply = function (q1) {
  4505. var result = new Quaternion(0, 0, 0, 1.0);
  4506. this.multiplyToRef(q1, result);
  4507. return result;
  4508. };
  4509. /**
  4510. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  4511. * Returns the current Quaternion.
  4512. */
  4513. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4514. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4515. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4516. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4517. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4518. result.copyFromFloats(x, y, z, w);
  4519. return this;
  4520. };
  4521. /**
  4522. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  4523. * Returns the updated Quaternion.
  4524. */
  4525. Quaternion.prototype.multiplyInPlace = function (q1) {
  4526. this.multiplyToRef(q1, this);
  4527. return this;
  4528. };
  4529. /**
  4530. * Sets the passed "ref" with the conjugation of the current Quaternion.
  4531. * Returns the current Quaternion.
  4532. */
  4533. Quaternion.prototype.conjugateToRef = function (ref) {
  4534. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4535. return this;
  4536. };
  4537. /**
  4538. * Conjugates in place the current Quaternion.
  4539. * Returns the updated Quaternion.
  4540. */
  4541. Quaternion.prototype.conjugateInPlace = function () {
  4542. this.x *= -1;
  4543. this.y *= -1;
  4544. this.z *= -1;
  4545. return this;
  4546. };
  4547. /**
  4548. * Returns a new Quaternion as the conjugate of the current Quaternion.
  4549. */
  4550. Quaternion.prototype.conjugate = function () {
  4551. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4552. return result;
  4553. };
  4554. /**
  4555. * Returns the Quaternion length (float).
  4556. */
  4557. Quaternion.prototype.length = function () {
  4558. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4559. };
  4560. /**
  4561. * Normalize in place the current Quaternion.
  4562. * Returns the updated Quaternion.
  4563. */
  4564. Quaternion.prototype.normalize = function () {
  4565. var length = 1.0 / this.length();
  4566. this.x *= length;
  4567. this.y *= length;
  4568. this.z *= length;
  4569. this.w *= length;
  4570. return this;
  4571. };
  4572. /**
  4573. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion
  4574. * @param order is a reserved parameter and is ignore for now
  4575. * @returns the new Vector3
  4576. */
  4577. Quaternion.prototype.toEulerAngles = function (order) {
  4578. if (order === void 0) { order = "YZX"; }
  4579. var result = Vector3.Zero();
  4580. this.toEulerAnglesToRef(result, order);
  4581. return result;
  4582. };
  4583. /**
  4584. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion
  4585. * @param result defines the vector which will be filled with the Euler angles
  4586. * @param order is a reserved parameter and is ignore for now
  4587. * @returns the current Quaternion
  4588. */
  4589. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4590. if (order === void 0) { order = "YZX"; }
  4591. var qz = this.z;
  4592. var qx = this.x;
  4593. var qy = this.y;
  4594. var qw = this.w;
  4595. var sqw = qw * qw;
  4596. var sqz = qz * qz;
  4597. var sqx = qx * qx;
  4598. var sqy = qy * qy;
  4599. var zAxisY = qy * qz - qx * qw;
  4600. var limit = .4999999;
  4601. if (zAxisY < -limit) {
  4602. result.y = 2 * Math.atan2(qy, qw);
  4603. result.x = Math.PI / 2;
  4604. result.z = 0;
  4605. }
  4606. else if (zAxisY > limit) {
  4607. result.y = 2 * Math.atan2(qy, qw);
  4608. result.x = -Math.PI / 2;
  4609. result.z = 0;
  4610. }
  4611. else {
  4612. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4613. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4614. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4615. }
  4616. return this;
  4617. };
  4618. /**
  4619. * Updates the passed rotation matrix with the current Quaternion values.
  4620. * Returns the current Quaternion.
  4621. */
  4622. Quaternion.prototype.toRotationMatrix = function (result) {
  4623. var xx = this.x * this.x;
  4624. var yy = this.y * this.y;
  4625. var zz = this.z * this.z;
  4626. var xy = this.x * this.y;
  4627. var zw = this.z * this.w;
  4628. var zx = this.z * this.x;
  4629. var yw = this.y * this.w;
  4630. var yz = this.y * this.z;
  4631. var xw = this.x * this.w;
  4632. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4633. result.m[1] = 2.0 * (xy + zw);
  4634. result.m[2] = 2.0 * (zx - yw);
  4635. result.m[3] = 0;
  4636. result.m[4] = 2.0 * (xy - zw);
  4637. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4638. result.m[6] = 2.0 * (yz + xw);
  4639. result.m[7] = 0;
  4640. result.m[8] = 2.0 * (zx + yw);
  4641. result.m[9] = 2.0 * (yz - xw);
  4642. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4643. result.m[11] = 0;
  4644. result.m[12] = 0;
  4645. result.m[13] = 0;
  4646. result.m[14] = 0;
  4647. result.m[15] = 1.0;
  4648. result._markAsUpdated();
  4649. return this;
  4650. };
  4651. /**
  4652. * Updates the current Quaternion from the passed rotation matrix values.
  4653. * Returns the updated Quaternion.
  4654. */
  4655. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4656. Quaternion.FromRotationMatrixToRef(matrix, this);
  4657. return this;
  4658. };
  4659. // Statics
  4660. /**
  4661. * Returns a new Quaternion set from the passed rotation matrix values.
  4662. */
  4663. Quaternion.FromRotationMatrix = function (matrix) {
  4664. var result = new Quaternion();
  4665. Quaternion.FromRotationMatrixToRef(matrix, result);
  4666. return result;
  4667. };
  4668. /**
  4669. * Updates the passed quaternion "result" with the passed rotation matrix values.
  4670. */
  4671. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4672. var data = matrix.m;
  4673. var m11 = data[0], m12 = data[4], m13 = data[8];
  4674. var m21 = data[1], m22 = data[5], m23 = data[9];
  4675. var m31 = data[2], m32 = data[6], m33 = data[10];
  4676. var trace = m11 + m22 + m33;
  4677. var s;
  4678. if (trace > 0) {
  4679. s = 0.5 / Math.sqrt(trace + 1.0);
  4680. result.w = 0.25 / s;
  4681. result.x = (m32 - m23) * s;
  4682. result.y = (m13 - m31) * s;
  4683. result.z = (m21 - m12) * s;
  4684. }
  4685. else if (m11 > m22 && m11 > m33) {
  4686. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4687. result.w = (m32 - m23) / s;
  4688. result.x = 0.25 * s;
  4689. result.y = (m12 + m21) / s;
  4690. result.z = (m13 + m31) / s;
  4691. }
  4692. else if (m22 > m33) {
  4693. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4694. result.w = (m13 - m31) / s;
  4695. result.x = (m12 + m21) / s;
  4696. result.y = 0.25 * s;
  4697. result.z = (m23 + m32) / s;
  4698. }
  4699. else {
  4700. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4701. result.w = (m21 - m12) / s;
  4702. result.x = (m13 + m31) / s;
  4703. result.y = (m23 + m32) / s;
  4704. result.z = 0.25 * s;
  4705. }
  4706. };
  4707. /**
  4708. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  4709. */
  4710. Quaternion.Zero = function () {
  4711. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4712. };
  4713. /**
  4714. * Returns a new Quaternion as the inverted current Quaternion.
  4715. */
  4716. Quaternion.Inverse = function (q) {
  4717. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4718. };
  4719. /**
  4720. * Returns the identity Quaternion.
  4721. */
  4722. Quaternion.Identity = function () {
  4723. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4724. };
  4725. Quaternion.IsIdentity = function (quaternion) {
  4726. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4727. };
  4728. /**
  4729. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  4730. */
  4731. Quaternion.RotationAxis = function (axis, angle) {
  4732. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4733. };
  4734. /**
  4735. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  4736. */
  4737. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4738. var sin = Math.sin(angle / 2);
  4739. axis.normalize();
  4740. result.w = Math.cos(angle / 2);
  4741. result.x = axis.x * sin;
  4742. result.y = axis.y * sin;
  4743. result.z = axis.z * sin;
  4744. return result;
  4745. };
  4746. /**
  4747. * Retuns a new Quaternion set from the starting index of the passed array.
  4748. */
  4749. Quaternion.FromArray = function (array, offset) {
  4750. if (!offset) {
  4751. offset = 0;
  4752. }
  4753. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4754. };
  4755. /**
  4756. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  4757. */
  4758. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4759. var q = new Quaternion();
  4760. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4761. return q;
  4762. };
  4763. /**
  4764. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  4765. */
  4766. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4767. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4768. var halfRoll = roll * 0.5;
  4769. var halfPitch = pitch * 0.5;
  4770. var halfYaw = yaw * 0.5;
  4771. var sinRoll = Math.sin(halfRoll);
  4772. var cosRoll = Math.cos(halfRoll);
  4773. var sinPitch = Math.sin(halfPitch);
  4774. var cosPitch = Math.cos(halfPitch);
  4775. var sinYaw = Math.sin(halfYaw);
  4776. var cosYaw = Math.cos(halfYaw);
  4777. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4778. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4779. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4780. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4781. };
  4782. /**
  4783. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  4784. */
  4785. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4786. var result = new Quaternion();
  4787. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4788. return result;
  4789. };
  4790. /**
  4791. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  4792. */
  4793. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4794. // Produces a quaternion from Euler angles in the z-x-z orientation
  4795. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4796. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4797. var halfBeta = beta * 0.5;
  4798. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4799. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4800. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4801. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4802. };
  4803. /**
  4804. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4805. * cf to Vector3.RotationFromAxis() documentation.
  4806. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4807. */
  4808. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  4809. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4810. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4811. return quat;
  4812. };
  4813. /**
  4814. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4815. * cf to Vector3.RotationFromAxis() documentation.
  4816. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4817. */
  4818. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4819. var rotMat = MathTmp.Matrix[0];
  4820. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4821. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4822. };
  4823. Quaternion.Slerp = function (left, right, amount) {
  4824. var result = Quaternion.Identity();
  4825. Quaternion.SlerpToRef(left, right, amount, result);
  4826. return result;
  4827. };
  4828. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4829. var num2;
  4830. var num3;
  4831. var num = amount;
  4832. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4833. var flag = false;
  4834. if (num4 < 0) {
  4835. flag = true;
  4836. num4 = -num4;
  4837. }
  4838. if (num4 > 0.999999) {
  4839. num3 = 1 - num;
  4840. num2 = flag ? -num : num;
  4841. }
  4842. else {
  4843. var num5 = Math.acos(num4);
  4844. var num6 = (1.0 / Math.sin(num5));
  4845. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  4846. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  4847. }
  4848. result.x = (num3 * left.x) + (num2 * right.x);
  4849. result.y = (num3 * left.y) + (num2 * right.y);
  4850. result.z = (num3 * left.z) + (num2 * right.z);
  4851. result.w = (num3 * left.w) + (num2 * right.w);
  4852. };
  4853. /**
  4854. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  4855. */
  4856. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4857. var squared = amount * amount;
  4858. var cubed = amount * squared;
  4859. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4860. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4861. var part3 = (cubed - (2.0 * squared)) + amount;
  4862. var part4 = cubed - squared;
  4863. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  4864. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  4865. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  4866. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  4867. return new Quaternion(x, y, z, w);
  4868. };
  4869. return Quaternion;
  4870. }());
  4871. BABYLON.Quaternion = Quaternion;
  4872. var Matrix = /** @class */ (function () {
  4873. function Matrix() {
  4874. this._isIdentity = false;
  4875. this._isIdentityDirty = true;
  4876. this.m = new Float32Array(16);
  4877. this._markAsUpdated();
  4878. }
  4879. Matrix.prototype._markAsUpdated = function () {
  4880. this.updateFlag = Matrix._updateFlagSeed++;
  4881. this._isIdentityDirty = true;
  4882. };
  4883. // Properties
  4884. /**
  4885. * Boolean : True is the matrix is the identity matrix
  4886. */
  4887. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  4888. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  4889. if (this._isIdentityDirty) {
  4890. this._isIdentityDirty = false;
  4891. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  4892. this._isIdentity = false;
  4893. }
  4894. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  4895. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  4896. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  4897. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  4898. this._isIdentity = false;
  4899. }
  4900. else {
  4901. this._isIdentity = true;
  4902. }
  4903. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  4904. this._isIdentity = false;
  4905. }
  4906. }
  4907. return this._isIdentity;
  4908. };
  4909. /**
  4910. * Returns the matrix determinant (float).
  4911. */
  4912. Matrix.prototype.determinant = function () {
  4913. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  4914. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  4915. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  4916. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  4917. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  4918. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  4919. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  4920. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  4921. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  4922. };
  4923. // Methods
  4924. /**
  4925. * Returns the matrix underlying array.
  4926. */
  4927. Matrix.prototype.toArray = function () {
  4928. return this.m;
  4929. };
  4930. /**
  4931. * Returns the matrix underlying array.
  4932. */
  4933. Matrix.prototype.asArray = function () {
  4934. return this.toArray();
  4935. };
  4936. /**
  4937. * Inverts in place the Matrix.
  4938. * Returns the Matrix inverted.
  4939. */
  4940. Matrix.prototype.invert = function () {
  4941. this.invertToRef(this);
  4942. return this;
  4943. };
  4944. /**
  4945. * Sets all the matrix elements to zero.
  4946. * Returns the Matrix.
  4947. */
  4948. Matrix.prototype.reset = function () {
  4949. for (var index = 0; index < 16; index++) {
  4950. this.m[index] = 0.0;
  4951. }
  4952. this._markAsUpdated();
  4953. return this;
  4954. };
  4955. /**
  4956. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  4957. */
  4958. Matrix.prototype.add = function (other) {
  4959. var result = new Matrix();
  4960. this.addToRef(other, result);
  4961. return result;
  4962. };
  4963. /**
  4964. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  4965. * Returns the Matrix.
  4966. */
  4967. Matrix.prototype.addToRef = function (other, result) {
  4968. for (var index = 0; index < 16; index++) {
  4969. result.m[index] = this.m[index] + other.m[index];
  4970. }
  4971. result._markAsUpdated();
  4972. return this;
  4973. };
  4974. /**
  4975. * Adds in place the passed matrix to the current Matrix.
  4976. * Returns the updated Matrix.
  4977. */
  4978. Matrix.prototype.addToSelf = function (other) {
  4979. for (var index = 0; index < 16; index++) {
  4980. this.m[index] += other.m[index];
  4981. }
  4982. this._markAsUpdated();
  4983. return this;
  4984. };
  4985. /**
  4986. * Sets the passed matrix with the current inverted Matrix.
  4987. * Returns the unmodified current Matrix.
  4988. */
  4989. Matrix.prototype.invertToRef = function (other) {
  4990. var l1 = this.m[0];
  4991. var l2 = this.m[1];
  4992. var l3 = this.m[2];
  4993. var l4 = this.m[3];
  4994. var l5 = this.m[4];
  4995. var l6 = this.m[5];
  4996. var l7 = this.m[6];
  4997. var l8 = this.m[7];
  4998. var l9 = this.m[8];
  4999. var l10 = this.m[9];
  5000. var l11 = this.m[10];
  5001. var l12 = this.m[11];
  5002. var l13 = this.m[12];
  5003. var l14 = this.m[13];
  5004. var l15 = this.m[14];
  5005. var l16 = this.m[15];
  5006. var l17 = (l11 * l16) - (l12 * l15);
  5007. var l18 = (l10 * l16) - (l12 * l14);
  5008. var l19 = (l10 * l15) - (l11 * l14);
  5009. var l20 = (l9 * l16) - (l12 * l13);
  5010. var l21 = (l9 * l15) - (l11 * l13);
  5011. var l22 = (l9 * l14) - (l10 * l13);
  5012. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5013. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5014. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5015. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5016. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5017. var l28 = (l7 * l16) - (l8 * l15);
  5018. var l29 = (l6 * l16) - (l8 * l14);
  5019. var l30 = (l6 * l15) - (l7 * l14);
  5020. var l31 = (l5 * l16) - (l8 * l13);
  5021. var l32 = (l5 * l15) - (l7 * l13);
  5022. var l33 = (l5 * l14) - (l6 * l13);
  5023. var l34 = (l7 * l12) - (l8 * l11);
  5024. var l35 = (l6 * l12) - (l8 * l10);
  5025. var l36 = (l6 * l11) - (l7 * l10);
  5026. var l37 = (l5 * l12) - (l8 * l9);
  5027. var l38 = (l5 * l11) - (l7 * l9);
  5028. var l39 = (l5 * l10) - (l6 * l9);
  5029. other.m[0] = l23 * l27;
  5030. other.m[4] = l24 * l27;
  5031. other.m[8] = l25 * l27;
  5032. other.m[12] = l26 * l27;
  5033. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5034. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5035. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5036. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5037. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5038. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5039. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5040. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5041. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5042. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5043. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5044. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5045. other._markAsUpdated();
  5046. return this;
  5047. };
  5048. /**
  5049. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  5050. * Returns the updated Matrix.
  5051. */
  5052. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5053. this.m[12] = x;
  5054. this.m[13] = y;
  5055. this.m[14] = z;
  5056. this._markAsUpdated();
  5057. return this;
  5058. };
  5059. /**
  5060. * Inserts the translation vector in the current Matrix.
  5061. * Returns the updated Matrix.
  5062. */
  5063. Matrix.prototype.setTranslation = function (vector3) {
  5064. this.m[12] = vector3.x;
  5065. this.m[13] = vector3.y;
  5066. this.m[14] = vector3.z;
  5067. this._markAsUpdated();
  5068. return this;
  5069. };
  5070. /**
  5071. * Returns a new Vector3 as the extracted translation from the Matrix.
  5072. */
  5073. Matrix.prototype.getTranslation = function () {
  5074. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5075. };
  5076. /**
  5077. * Fill a Vector3 with the extracted translation from the Matrix.
  5078. */
  5079. Matrix.prototype.getTranslationToRef = function (result) {
  5080. result.x = this.m[12];
  5081. result.y = this.m[13];
  5082. result.z = this.m[14];
  5083. return this;
  5084. };
  5085. /**
  5086. * Remove rotation and scaling part from the Matrix.
  5087. * Returns the updated Matrix.
  5088. */
  5089. Matrix.prototype.removeRotationAndScaling = function () {
  5090. this.setRowFromFloats(0, 1, 0, 0, 0);
  5091. this.setRowFromFloats(1, 0, 1, 0, 0);
  5092. this.setRowFromFloats(2, 0, 0, 1, 0);
  5093. return this;
  5094. };
  5095. /**
  5096. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  5097. */
  5098. Matrix.prototype.multiply = function (other) {
  5099. var result = new Matrix();
  5100. this.multiplyToRef(other, result);
  5101. return result;
  5102. };
  5103. /**
  5104. * Updates the current Matrix from the passed one values.
  5105. * Returns the updated Matrix.
  5106. */
  5107. Matrix.prototype.copyFrom = function (other) {
  5108. for (var index = 0; index < 16; index++) {
  5109. this.m[index] = other.m[index];
  5110. }
  5111. this._markAsUpdated();
  5112. return this;
  5113. };
  5114. /**
  5115. * Populates the passed array from the starting index with the Matrix values.
  5116. * Returns the Matrix.
  5117. */
  5118. Matrix.prototype.copyToArray = function (array, offset) {
  5119. if (offset === void 0) { offset = 0; }
  5120. for (var index = 0; index < 16; index++) {
  5121. array[offset + index] = this.m[index];
  5122. }
  5123. return this;
  5124. };
  5125. /**
  5126. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  5127. */
  5128. Matrix.prototype.multiplyToRef = function (other, result) {
  5129. this.multiplyToArray(other, result.m, 0);
  5130. result._markAsUpdated();
  5131. return this;
  5132. };
  5133. /**
  5134. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  5135. */
  5136. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5137. var tm0 = this.m[0];
  5138. var tm1 = this.m[1];
  5139. var tm2 = this.m[2];
  5140. var tm3 = this.m[3];
  5141. var tm4 = this.m[4];
  5142. var tm5 = this.m[5];
  5143. var tm6 = this.m[6];
  5144. var tm7 = this.m[7];
  5145. var tm8 = this.m[8];
  5146. var tm9 = this.m[9];
  5147. var tm10 = this.m[10];
  5148. var tm11 = this.m[11];
  5149. var tm12 = this.m[12];
  5150. var tm13 = this.m[13];
  5151. var tm14 = this.m[14];
  5152. var tm15 = this.m[15];
  5153. var om0 = other.m[0];
  5154. var om1 = other.m[1];
  5155. var om2 = other.m[2];
  5156. var om3 = other.m[3];
  5157. var om4 = other.m[4];
  5158. var om5 = other.m[5];
  5159. var om6 = other.m[6];
  5160. var om7 = other.m[7];
  5161. var om8 = other.m[8];
  5162. var om9 = other.m[9];
  5163. var om10 = other.m[10];
  5164. var om11 = other.m[11];
  5165. var om12 = other.m[12];
  5166. var om13 = other.m[13];
  5167. var om14 = other.m[14];
  5168. var om15 = other.m[15];
  5169. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5170. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5171. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5172. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5173. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5174. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5175. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5176. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5177. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5178. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5179. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5180. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5181. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5182. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5183. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5184. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5185. return this;
  5186. };
  5187. /**
  5188. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  5189. */
  5190. Matrix.prototype.equals = function (value) {
  5191. return value &&
  5192. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5193. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5194. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5195. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5196. };
  5197. /**
  5198. * Returns a new Matrix from the current Matrix.
  5199. */
  5200. Matrix.prototype.clone = function () {
  5201. 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]);
  5202. };
  5203. /**
  5204. * Returns the string "Matrix"
  5205. */
  5206. Matrix.prototype.getClassName = function () {
  5207. return "Matrix";
  5208. };
  5209. /**
  5210. * Returns the Matrix hash code.
  5211. */
  5212. Matrix.prototype.getHashCode = function () {
  5213. var hash = this.m[0] || 0;
  5214. for (var i = 1; i < 16; i++) {
  5215. hash = (hash * 397) ^ (this.m[i] || 0);
  5216. }
  5217. return hash;
  5218. };
  5219. /**
  5220. * Decomposes the current Matrix into :
  5221. * - a scale vector3 passed as a reference to update,
  5222. * - a rotation quaternion passed as a reference to update,
  5223. * - a translation vector3 passed as a reference to update.
  5224. * Returns the true if operation was successful.
  5225. */
  5226. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5227. translation.x = this.m[12];
  5228. translation.y = this.m[13];
  5229. translation.z = this.m[14];
  5230. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5231. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5232. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5233. if (this.determinant() <= 0) {
  5234. scale.y *= -1;
  5235. }
  5236. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5237. rotation.x = 0;
  5238. rotation.y = 0;
  5239. rotation.z = 0;
  5240. rotation.w = 1;
  5241. return false;
  5242. }
  5243. 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]);
  5244. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5245. return true;
  5246. };
  5247. /**
  5248. * Returns the index-th row of the current matrix as a new Vector4.
  5249. */
  5250. Matrix.prototype.getRow = function (index) {
  5251. if (index < 0 || index > 3) {
  5252. return null;
  5253. }
  5254. var i = index * 4;
  5255. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5256. };
  5257. /**
  5258. * Sets the index-th row of the current matrix with the passed Vector4 values.
  5259. * Returns the updated Matrix.
  5260. */
  5261. Matrix.prototype.setRow = function (index, row) {
  5262. if (index < 0 || index > 3) {
  5263. return this;
  5264. }
  5265. var i = index * 4;
  5266. this.m[i + 0] = row.x;
  5267. this.m[i + 1] = row.y;
  5268. this.m[i + 2] = row.z;
  5269. this.m[i + 3] = row.w;
  5270. this._markAsUpdated();
  5271. return this;
  5272. };
  5273. /**
  5274. * Compute the transpose of the matrix.
  5275. * Returns a new Matrix.
  5276. */
  5277. Matrix.prototype.transpose = function () {
  5278. return Matrix.Transpose(this);
  5279. };
  5280. /**
  5281. * Compute the transpose of the matrix.
  5282. * Returns the current matrix.
  5283. */
  5284. Matrix.prototype.transposeToRef = function (result) {
  5285. Matrix.TransposeToRef(this, result);
  5286. return this;
  5287. };
  5288. /**
  5289. * Sets the index-th row of the current matrix with the passed 4 x float values.
  5290. * Returns the updated Matrix.
  5291. */
  5292. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5293. if (index < 0 || index > 3) {
  5294. return this;
  5295. }
  5296. var i = index * 4;
  5297. this.m[i + 0] = x;
  5298. this.m[i + 1] = y;
  5299. this.m[i + 2] = z;
  5300. this.m[i + 3] = w;
  5301. this._markAsUpdated();
  5302. return this;
  5303. };
  5304. /**
  5305. * Compute a new Matrix set with the current Matrix values multiplied by scale (float)
  5306. * @param scale defines the scale factor
  5307. * @returns a new Matrix
  5308. */
  5309. Matrix.prototype.scale = function (scale) {
  5310. var result = new Matrix();
  5311. this.scaleToRef(scale, result);
  5312. return result;
  5313. };
  5314. /**
  5315. * Scale the current Matrix values by a factor to a given result Matrix
  5316. * @param scale defines the scale factor
  5317. * @param result defines the Matrix to store the result
  5318. * @returns the current Matrix
  5319. */
  5320. Matrix.prototype.scaleToRef = function (scale, result) {
  5321. for (var index = 0; index < 16; index++) {
  5322. result.m[index] = this.m[index] * scale;
  5323. }
  5324. result._markAsUpdated();
  5325. return this;
  5326. };
  5327. /**
  5328. * Scale the current Matrix values by a factor and add the result to a given Matrix
  5329. * @param scale defines the scale factor
  5330. * @param result defines the Matrix to store the result
  5331. * @returns the current Matrix
  5332. */
  5333. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5334. for (var index = 0; index < 16; index++) {
  5335. result.m[index] += this.m[index] * scale;
  5336. }
  5337. result._markAsUpdated();
  5338. return this;
  5339. };
  5340. /**
  5341. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5342. * @param ref matrix to store the result
  5343. */
  5344. Matrix.prototype.toNormalMatrix = function (ref) {
  5345. this.invertToRef(ref);
  5346. ref.transpose();
  5347. var m = ref.m;
  5348. 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);
  5349. };
  5350. /**
  5351. * Returns a new Matrix as the extracted rotation matrix from the current one.
  5352. */
  5353. Matrix.prototype.getRotationMatrix = function () {
  5354. var result = Matrix.Identity();
  5355. this.getRotationMatrixToRef(result);
  5356. return result;
  5357. };
  5358. /**
  5359. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  5360. * Returns the current Matrix.
  5361. */
  5362. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5363. var m = this.m;
  5364. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  5365. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  5366. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  5367. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5368. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5369. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5370. 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);
  5371. return this;
  5372. };
  5373. // Statics
  5374. /**
  5375. * Returns a new Matrix set from the starting index of the passed array.
  5376. */
  5377. Matrix.FromArray = function (array, offset) {
  5378. var result = new Matrix();
  5379. if (!offset) {
  5380. offset = 0;
  5381. }
  5382. Matrix.FromArrayToRef(array, offset, result);
  5383. return result;
  5384. };
  5385. /**
  5386. * Sets the passed "result" matrix from the starting index of the passed array.
  5387. */
  5388. Matrix.FromArrayToRef = function (array, offset, result) {
  5389. for (var index = 0; index < 16; index++) {
  5390. result.m[index] = array[index + offset];
  5391. }
  5392. result._markAsUpdated();
  5393. };
  5394. /**
  5395. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  5396. */
  5397. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5398. for (var index = 0; index < 16; index++) {
  5399. result.m[index] = array[index + offset] * scale;
  5400. }
  5401. result._markAsUpdated();
  5402. };
  5403. /**
  5404. * Sets the passed matrix "result" with the 16 passed floats.
  5405. */
  5406. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5407. result.m[0] = initialM11;
  5408. result.m[1] = initialM12;
  5409. result.m[2] = initialM13;
  5410. result.m[3] = initialM14;
  5411. result.m[4] = initialM21;
  5412. result.m[5] = initialM22;
  5413. result.m[6] = initialM23;
  5414. result.m[7] = initialM24;
  5415. result.m[8] = initialM31;
  5416. result.m[9] = initialM32;
  5417. result.m[10] = initialM33;
  5418. result.m[11] = initialM34;
  5419. result.m[12] = initialM41;
  5420. result.m[13] = initialM42;
  5421. result.m[14] = initialM43;
  5422. result.m[15] = initialM44;
  5423. result._markAsUpdated();
  5424. };
  5425. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5426. /**
  5427. * Static identity matrix to be used as readonly matrix
  5428. * Must not be updated.
  5429. */
  5430. get: function () {
  5431. return Matrix._identityReadOnly;
  5432. },
  5433. enumerable: true,
  5434. configurable: true
  5435. });
  5436. /**
  5437. * Returns a new Matrix set from the 16 passed floats.
  5438. */
  5439. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5440. var result = new Matrix();
  5441. result.m[0] = initialM11;
  5442. result.m[1] = initialM12;
  5443. result.m[2] = initialM13;
  5444. result.m[3] = initialM14;
  5445. result.m[4] = initialM21;
  5446. result.m[5] = initialM22;
  5447. result.m[6] = initialM23;
  5448. result.m[7] = initialM24;
  5449. result.m[8] = initialM31;
  5450. result.m[9] = initialM32;
  5451. result.m[10] = initialM33;
  5452. result.m[11] = initialM34;
  5453. result.m[12] = initialM41;
  5454. result.m[13] = initialM42;
  5455. result.m[14] = initialM43;
  5456. result.m[15] = initialM44;
  5457. return result;
  5458. };
  5459. /**
  5460. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5461. */
  5462. Matrix.Compose = function (scale, rotation, translation) {
  5463. var result = Matrix.Identity();
  5464. Matrix.ComposeToRef(scale, rotation, translation, result);
  5465. return result;
  5466. };
  5467. /**
  5468. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5469. */
  5470. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5471. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5472. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5473. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5474. result.setTranslation(translation);
  5475. };
  5476. /**
  5477. * Returns a new indentity Matrix.
  5478. */
  5479. Matrix.Identity = function () {
  5480. 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);
  5481. };
  5482. /**
  5483. * Sets the passed "result" as an identity matrix.
  5484. */
  5485. Matrix.IdentityToRef = function (result) {
  5486. 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);
  5487. };
  5488. /**
  5489. * Returns a new zero Matrix.
  5490. */
  5491. Matrix.Zero = function () {
  5492. 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);
  5493. };
  5494. /**
  5495. * Returns a new rotation matrix for "angle" radians around the X axis.
  5496. */
  5497. Matrix.RotationX = function (angle) {
  5498. var result = new Matrix();
  5499. Matrix.RotationXToRef(angle, result);
  5500. return result;
  5501. };
  5502. /**
  5503. * Returns a new Matrix as the passed inverted one.
  5504. */
  5505. Matrix.Invert = function (source) {
  5506. var result = new Matrix();
  5507. source.invertToRef(result);
  5508. return result;
  5509. };
  5510. /**
  5511. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  5512. */
  5513. Matrix.RotationXToRef = function (angle, result) {
  5514. var s = Math.sin(angle);
  5515. var c = Math.cos(angle);
  5516. result.m[0] = 1.0;
  5517. result.m[15] = 1.0;
  5518. result.m[5] = c;
  5519. result.m[10] = c;
  5520. result.m[9] = -s;
  5521. result.m[6] = s;
  5522. result.m[1] = 0.0;
  5523. result.m[2] = 0.0;
  5524. result.m[3] = 0.0;
  5525. result.m[4] = 0.0;
  5526. result.m[7] = 0.0;
  5527. result.m[8] = 0.0;
  5528. result.m[11] = 0.0;
  5529. result.m[12] = 0.0;
  5530. result.m[13] = 0.0;
  5531. result.m[14] = 0.0;
  5532. result._markAsUpdated();
  5533. };
  5534. /**
  5535. * Returns a new rotation matrix for "angle" radians around the Y axis.
  5536. */
  5537. Matrix.RotationY = function (angle) {
  5538. var result = new Matrix();
  5539. Matrix.RotationYToRef(angle, result);
  5540. return result;
  5541. };
  5542. /**
  5543. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  5544. */
  5545. Matrix.RotationYToRef = function (angle, result) {
  5546. var s = Math.sin(angle);
  5547. var c = Math.cos(angle);
  5548. result.m[5] = 1.0;
  5549. result.m[15] = 1.0;
  5550. result.m[0] = c;
  5551. result.m[2] = -s;
  5552. result.m[8] = s;
  5553. result.m[10] = c;
  5554. result.m[1] = 0.0;
  5555. result.m[3] = 0.0;
  5556. result.m[4] = 0.0;
  5557. result.m[6] = 0.0;
  5558. result.m[7] = 0.0;
  5559. result.m[9] = 0.0;
  5560. result.m[11] = 0.0;
  5561. result.m[12] = 0.0;
  5562. result.m[13] = 0.0;
  5563. result.m[14] = 0.0;
  5564. result._markAsUpdated();
  5565. };
  5566. /**
  5567. * Returns a new rotation matrix for "angle" radians around the Z axis.
  5568. */
  5569. Matrix.RotationZ = function (angle) {
  5570. var result = new Matrix();
  5571. Matrix.RotationZToRef(angle, result);
  5572. return result;
  5573. };
  5574. /**
  5575. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  5576. */
  5577. Matrix.RotationZToRef = function (angle, result) {
  5578. var s = Math.sin(angle);
  5579. var c = Math.cos(angle);
  5580. result.m[10] = 1.0;
  5581. result.m[15] = 1.0;
  5582. result.m[0] = c;
  5583. result.m[1] = s;
  5584. result.m[4] = -s;
  5585. result.m[5] = c;
  5586. result.m[2] = 0.0;
  5587. result.m[3] = 0.0;
  5588. result.m[6] = 0.0;
  5589. result.m[7] = 0.0;
  5590. result.m[8] = 0.0;
  5591. result.m[9] = 0.0;
  5592. result.m[11] = 0.0;
  5593. result.m[12] = 0.0;
  5594. result.m[13] = 0.0;
  5595. result.m[14] = 0.0;
  5596. result._markAsUpdated();
  5597. };
  5598. /**
  5599. * Returns a new rotation matrix for "angle" radians around the passed axis.
  5600. */
  5601. Matrix.RotationAxis = function (axis, angle) {
  5602. var result = Matrix.Zero();
  5603. Matrix.RotationAxisToRef(axis, angle, result);
  5604. return result;
  5605. };
  5606. /**
  5607. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  5608. */
  5609. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5610. var s = Math.sin(-angle);
  5611. var c = Math.cos(-angle);
  5612. var c1 = 1 - c;
  5613. axis.normalize();
  5614. result.m[0] = (axis.x * axis.x) * c1 + c;
  5615. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5616. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5617. result.m[3] = 0.0;
  5618. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5619. result.m[5] = (axis.y * axis.y) * c1 + c;
  5620. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5621. result.m[7] = 0.0;
  5622. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5623. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5624. result.m[10] = (axis.z * axis.z) * c1 + c;
  5625. result.m[11] = 0.0;
  5626. result.m[15] = 1.0;
  5627. result._markAsUpdated();
  5628. };
  5629. /**
  5630. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  5631. */
  5632. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5633. var result = new Matrix();
  5634. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5635. return result;
  5636. };
  5637. /**
  5638. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  5639. */
  5640. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5641. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5642. this._tempQuaternion.toRotationMatrix(result);
  5643. };
  5644. /**
  5645. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  5646. */
  5647. Matrix.Scaling = function (x, y, z) {
  5648. var result = Matrix.Zero();
  5649. Matrix.ScalingToRef(x, y, z, result);
  5650. return result;
  5651. };
  5652. /**
  5653. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  5654. */
  5655. Matrix.ScalingToRef = function (x, y, z, result) {
  5656. result.m[0] = x;
  5657. result.m[1] = 0.0;
  5658. result.m[2] = 0.0;
  5659. result.m[3] = 0.0;
  5660. result.m[4] = 0.0;
  5661. result.m[5] = y;
  5662. result.m[6] = 0.0;
  5663. result.m[7] = 0.0;
  5664. result.m[8] = 0.0;
  5665. result.m[9] = 0.0;
  5666. result.m[10] = z;
  5667. result.m[11] = 0.0;
  5668. result.m[12] = 0.0;
  5669. result.m[13] = 0.0;
  5670. result.m[14] = 0.0;
  5671. result.m[15] = 1.0;
  5672. result._markAsUpdated();
  5673. };
  5674. /**
  5675. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  5676. */
  5677. Matrix.Translation = function (x, y, z) {
  5678. var result = Matrix.Identity();
  5679. Matrix.TranslationToRef(x, y, z, result);
  5680. return result;
  5681. };
  5682. /**
  5683. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  5684. */
  5685. Matrix.TranslationToRef = function (x, y, z, result) {
  5686. 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);
  5687. };
  5688. /**
  5689. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5690. * @param startValue defines the start value
  5691. * @param endValue defines the end value
  5692. * @param gradient defines the gradient factor
  5693. * @returns the new matrix
  5694. */
  5695. Matrix.Lerp = function (startValue, endValue, gradient) {
  5696. var result = Matrix.Zero();
  5697. Matrix.LerpToRef(startValue, endValue, gradient, result);
  5698. return result;
  5699. };
  5700. /**
  5701. * Set the passed matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5702. * @param startValue defines the start value
  5703. * @param endValue defines the end value
  5704. * @param gradient defines the gradient factor
  5705. * @param result defines the Matrix object where to store data
  5706. */
  5707. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  5708. for (var index = 0; index < 16; index++) {
  5709. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  5710. }
  5711. result._markAsUpdated();
  5712. };
  5713. /**
  5714. * Returns a new Matrix whose values are computed by :
  5715. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  5716. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  5717. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  5718. */
  5719. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  5720. var startScale = new Vector3(0, 0, 0);
  5721. var startRotation = new Quaternion();
  5722. var startTranslation = new Vector3(0, 0, 0);
  5723. startValue.decompose(startScale, startRotation, startTranslation);
  5724. var endScale = new Vector3(0, 0, 0);
  5725. var endRotation = new Quaternion();
  5726. var endTranslation = new Vector3(0, 0, 0);
  5727. endValue.decompose(endScale, endRotation, endTranslation);
  5728. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  5729. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  5730. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  5731. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  5732. };
  5733. /**
  5734. * 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".
  5735. * This methods works for a Left-Handed system.
  5736. */
  5737. Matrix.LookAtLH = function (eye, target, up) {
  5738. var result = Matrix.Zero();
  5739. Matrix.LookAtLHToRef(eye, target, up, result);
  5740. return result;
  5741. };
  5742. /**
  5743. * 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".
  5744. * This methods works for a Left-Handed system.
  5745. */
  5746. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  5747. // Z axis
  5748. target.subtractToRef(eye, this._zAxis);
  5749. this._zAxis.normalize();
  5750. // X axis
  5751. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5752. if (this._xAxis.lengthSquared() === 0) {
  5753. this._xAxis.x = 1.0;
  5754. }
  5755. else {
  5756. this._xAxis.normalize();
  5757. }
  5758. // Y axis
  5759. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5760. this._yAxis.normalize();
  5761. // Eye angles
  5762. var ex = -Vector3.Dot(this._xAxis, eye);
  5763. var ey = -Vector3.Dot(this._yAxis, eye);
  5764. var ez = -Vector3.Dot(this._zAxis, eye);
  5765. 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);
  5766. };
  5767. /**
  5768. * 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".
  5769. * This methods works for a Right-Handed system.
  5770. */
  5771. Matrix.LookAtRH = function (eye, target, up) {
  5772. var result = Matrix.Zero();
  5773. Matrix.LookAtRHToRef(eye, target, up, result);
  5774. return result;
  5775. };
  5776. /**
  5777. * 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".
  5778. * This methods works for a Left-Handed system.
  5779. */
  5780. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  5781. // Z axis
  5782. eye.subtractToRef(target, this._zAxis);
  5783. this._zAxis.normalize();
  5784. // X axis
  5785. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5786. if (this._xAxis.lengthSquared() === 0) {
  5787. this._xAxis.x = 1.0;
  5788. }
  5789. else {
  5790. this._xAxis.normalize();
  5791. }
  5792. // Y axis
  5793. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5794. this._yAxis.normalize();
  5795. // Eye angles
  5796. var ex = -Vector3.Dot(this._xAxis, eye);
  5797. var ey = -Vector3.Dot(this._yAxis, eye);
  5798. var ez = -Vector3.Dot(this._zAxis, eye);
  5799. 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);
  5800. };
  5801. /**
  5802. * 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.
  5803. */
  5804. Matrix.OrthoLH = function (width, height, znear, zfar) {
  5805. var matrix = Matrix.Zero();
  5806. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  5807. return matrix;
  5808. };
  5809. /**
  5810. * 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.
  5811. */
  5812. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  5813. var n = znear;
  5814. var f = zfar;
  5815. var a = 2.0 / width;
  5816. var b = 2.0 / height;
  5817. var c = 2.0 / (f - n);
  5818. var d = -(f + n) / (f - n);
  5819. 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);
  5820. };
  5821. /**
  5822. * 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.
  5823. */
  5824. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  5825. var matrix = Matrix.Zero();
  5826. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  5827. return matrix;
  5828. };
  5829. /**
  5830. * 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.
  5831. */
  5832. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5833. var n = znear;
  5834. var f = zfar;
  5835. var a = 2.0 / (right - left);
  5836. var b = 2.0 / (top - bottom);
  5837. var c = 2.0 / (f - n);
  5838. var d = -(f + n) / (f - n);
  5839. var i0 = (left + right) / (left - right);
  5840. var i1 = (top + bottom) / (bottom - top);
  5841. 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);
  5842. };
  5843. /**
  5844. * 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.
  5845. */
  5846. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  5847. var matrix = Matrix.Zero();
  5848. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  5849. return matrix;
  5850. };
  5851. /**
  5852. * 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.
  5853. */
  5854. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5855. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  5856. result.m[10] *= -1.0;
  5857. };
  5858. /**
  5859. * 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.
  5860. */
  5861. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  5862. var matrix = Matrix.Zero();
  5863. var n = znear;
  5864. var f = zfar;
  5865. var a = 2.0 * n / width;
  5866. var b = 2.0 * n / height;
  5867. var c = (f + n) / (f - n);
  5868. var d = -2.0 * f * n / (f - n);
  5869. 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);
  5870. return matrix;
  5871. };
  5872. /**
  5873. * 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.
  5874. */
  5875. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  5876. var matrix = Matrix.Zero();
  5877. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  5878. return matrix;
  5879. };
  5880. /**
  5881. * 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.
  5882. */
  5883. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5884. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5885. var n = znear;
  5886. var f = zfar;
  5887. var t = 1.0 / (Math.tan(fov * 0.5));
  5888. var a = isVerticalFovFixed ? (t / aspect) : t;
  5889. var b = isVerticalFovFixed ? t : (t * aspect);
  5890. var c = (f + n) / (f - n);
  5891. var d = -2.0 * f * n / (f - n);
  5892. 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);
  5893. };
  5894. /**
  5895. * 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.
  5896. */
  5897. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  5898. var matrix = Matrix.Zero();
  5899. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  5900. return matrix;
  5901. };
  5902. /**
  5903. * 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.
  5904. */
  5905. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5906. //alternatively this could be expressed as:
  5907. // m = PerspectiveFovLHToRef
  5908. // m[10] *= -1.0;
  5909. // m[11] *= -1.0;
  5910. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5911. var n = znear;
  5912. var f = zfar;
  5913. var t = 1.0 / (Math.tan(fov * 0.5));
  5914. var a = isVerticalFovFixed ? (t / aspect) : t;
  5915. var b = isVerticalFovFixed ? t : (t * aspect);
  5916. var c = -(f + n) / (f - n);
  5917. var d = -2 * f * n / (f - n);
  5918. 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);
  5919. };
  5920. /**
  5921. * 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.
  5922. */
  5923. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  5924. if (rightHanded === void 0) { rightHanded = false; }
  5925. var rightHandedFactor = rightHanded ? -1 : 1;
  5926. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  5927. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  5928. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  5929. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  5930. var xScale = 2.0 / (leftTan + rightTan);
  5931. var yScale = 2.0 / (upTan + downTan);
  5932. result.m[0] = xScale;
  5933. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  5934. result.m[5] = yScale;
  5935. result.m[6] = result.m[7] = 0.0;
  5936. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  5937. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  5938. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  5939. result.m[10] = -zfar / (znear - zfar);
  5940. result.m[11] = 1.0 * rightHandedFactor;
  5941. result.m[12] = result.m[13] = result.m[15] = 0.0;
  5942. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  5943. // result.m[14] = (znear * zfar) / (znear - zfar);
  5944. result._markAsUpdated();
  5945. };
  5946. /**
  5947. * Returns the final transformation matrix : world * view * projection * viewport
  5948. */
  5949. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  5950. var cw = viewport.width;
  5951. var ch = viewport.height;
  5952. var cx = viewport.x;
  5953. var cy = viewport.y;
  5954. 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);
  5955. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  5956. };
  5957. /**
  5958. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  5959. */
  5960. Matrix.GetAsMatrix2x2 = function (matrix) {
  5961. return new Float32Array([
  5962. matrix.m[0], matrix.m[1],
  5963. matrix.m[4], matrix.m[5]
  5964. ]);
  5965. };
  5966. /**
  5967. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  5968. */
  5969. Matrix.GetAsMatrix3x3 = function (matrix) {
  5970. return new Float32Array([
  5971. matrix.m[0], matrix.m[1], matrix.m[2],
  5972. matrix.m[4], matrix.m[5], matrix.m[6],
  5973. matrix.m[8], matrix.m[9], matrix.m[10]
  5974. ]);
  5975. };
  5976. /**
  5977. * Compute the transpose of the passed Matrix.
  5978. * Returns a new Matrix.
  5979. */
  5980. Matrix.Transpose = function (matrix) {
  5981. var result = new Matrix();
  5982. Matrix.TransposeToRef(matrix, result);
  5983. return result;
  5984. };
  5985. /**
  5986. * Compute the transpose of the passed Matrix and store it in the result matrix.
  5987. */
  5988. Matrix.TransposeToRef = function (matrix, result) {
  5989. result.m[0] = matrix.m[0];
  5990. result.m[1] = matrix.m[4];
  5991. result.m[2] = matrix.m[8];
  5992. result.m[3] = matrix.m[12];
  5993. result.m[4] = matrix.m[1];
  5994. result.m[5] = matrix.m[5];
  5995. result.m[6] = matrix.m[9];
  5996. result.m[7] = matrix.m[13];
  5997. result.m[8] = matrix.m[2];
  5998. result.m[9] = matrix.m[6];
  5999. result.m[10] = matrix.m[10];
  6000. result.m[11] = matrix.m[14];
  6001. result.m[12] = matrix.m[3];
  6002. result.m[13] = matrix.m[7];
  6003. result.m[14] = matrix.m[11];
  6004. result.m[15] = matrix.m[15];
  6005. };
  6006. /**
  6007. * Returns a new Matrix as the reflection matrix across the passed plane.
  6008. */
  6009. Matrix.Reflection = function (plane) {
  6010. var matrix = new Matrix();
  6011. Matrix.ReflectionToRef(plane, matrix);
  6012. return matrix;
  6013. };
  6014. /**
  6015. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  6016. */
  6017. Matrix.ReflectionToRef = function (plane, result) {
  6018. plane.normalize();
  6019. var x = plane.normal.x;
  6020. var y = plane.normal.y;
  6021. var z = plane.normal.z;
  6022. var temp = -2 * x;
  6023. var temp2 = -2 * y;
  6024. var temp3 = -2 * z;
  6025. result.m[0] = (temp * x) + 1;
  6026. result.m[1] = temp2 * x;
  6027. result.m[2] = temp3 * x;
  6028. result.m[3] = 0.0;
  6029. result.m[4] = temp * y;
  6030. result.m[5] = (temp2 * y) + 1;
  6031. result.m[6] = temp3 * y;
  6032. result.m[7] = 0.0;
  6033. result.m[8] = temp * z;
  6034. result.m[9] = temp2 * z;
  6035. result.m[10] = (temp3 * z) + 1;
  6036. result.m[11] = 0.0;
  6037. result.m[12] = temp * plane.d;
  6038. result.m[13] = temp2 * plane.d;
  6039. result.m[14] = temp3 * plane.d;
  6040. result.m[15] = 1.0;
  6041. result._markAsUpdated();
  6042. };
  6043. /**
  6044. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  6045. */
  6046. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6047. result.m[0] = xaxis.x;
  6048. result.m[1] = xaxis.y;
  6049. result.m[2] = xaxis.z;
  6050. result.m[3] = 0.0;
  6051. result.m[4] = yaxis.x;
  6052. result.m[5] = yaxis.y;
  6053. result.m[6] = yaxis.z;
  6054. result.m[7] = 0.0;
  6055. result.m[8] = zaxis.x;
  6056. result.m[9] = zaxis.y;
  6057. result.m[10] = zaxis.z;
  6058. result.m[11] = 0.0;
  6059. result.m[12] = 0.0;
  6060. result.m[13] = 0.0;
  6061. result.m[14] = 0.0;
  6062. result.m[15] = 1.0;
  6063. result._markAsUpdated();
  6064. };
  6065. /**
  6066. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  6067. */
  6068. Matrix.FromQuaternionToRef = function (quat, result) {
  6069. var xx = quat.x * quat.x;
  6070. var yy = quat.y * quat.y;
  6071. var zz = quat.z * quat.z;
  6072. var xy = quat.x * quat.y;
  6073. var zw = quat.z * quat.w;
  6074. var zx = quat.z * quat.x;
  6075. var yw = quat.y * quat.w;
  6076. var yz = quat.y * quat.z;
  6077. var xw = quat.x * quat.w;
  6078. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6079. result.m[1] = 2.0 * (xy + zw);
  6080. result.m[2] = 2.0 * (zx - yw);
  6081. result.m[3] = 0.0;
  6082. result.m[4] = 2.0 * (xy - zw);
  6083. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6084. result.m[6] = 2.0 * (yz + xw);
  6085. result.m[7] = 0.0;
  6086. result.m[8] = 2.0 * (zx + yw);
  6087. result.m[9] = 2.0 * (yz - xw);
  6088. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6089. result.m[11] = 0.0;
  6090. result.m[12] = 0.0;
  6091. result.m[13] = 0.0;
  6092. result.m[14] = 0.0;
  6093. result.m[15] = 1.0;
  6094. result._markAsUpdated();
  6095. };
  6096. Matrix._tempQuaternion = new Quaternion();
  6097. Matrix._xAxis = Vector3.Zero();
  6098. Matrix._yAxis = Vector3.Zero();
  6099. Matrix._zAxis = Vector3.Zero();
  6100. Matrix._updateFlagSeed = 0;
  6101. Matrix._identityReadOnly = Matrix.Identity();
  6102. return Matrix;
  6103. }());
  6104. BABYLON.Matrix = Matrix;
  6105. var Plane = /** @class */ (function () {
  6106. /**
  6107. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6108. */
  6109. function Plane(a, b, c, d) {
  6110. this.normal = new Vector3(a, b, c);
  6111. this.d = d;
  6112. }
  6113. /**
  6114. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6115. */
  6116. Plane.prototype.asArray = function () {
  6117. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6118. };
  6119. // Methods
  6120. /**
  6121. * Returns a new plane copied from the current Plane.
  6122. */
  6123. Plane.prototype.clone = function () {
  6124. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6125. };
  6126. /**
  6127. * Returns the string "Plane".
  6128. */
  6129. Plane.prototype.getClassName = function () {
  6130. return "Plane";
  6131. };
  6132. /**
  6133. * Returns the Plane hash code.
  6134. */
  6135. Plane.prototype.getHashCode = function () {
  6136. var hash = this.normal.getHashCode();
  6137. hash = (hash * 397) ^ (this.d || 0);
  6138. return hash;
  6139. };
  6140. /**
  6141. * Normalize the current Plane in place.
  6142. * Returns the updated Plane.
  6143. */
  6144. Plane.prototype.normalize = function () {
  6145. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6146. var magnitude = 0.0;
  6147. if (norm !== 0) {
  6148. magnitude = 1.0 / norm;
  6149. }
  6150. this.normal.x *= magnitude;
  6151. this.normal.y *= magnitude;
  6152. this.normal.z *= magnitude;
  6153. this.d *= magnitude;
  6154. return this;
  6155. };
  6156. /**
  6157. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  6158. */
  6159. Plane.prototype.transform = function (transformation) {
  6160. var transposedMatrix = Matrix.Transpose(transformation);
  6161. var x = this.normal.x;
  6162. var y = this.normal.y;
  6163. var z = this.normal.z;
  6164. var d = this.d;
  6165. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6166. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6167. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6168. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6169. return new Plane(normalX, normalY, normalZ, finalD);
  6170. };
  6171. /**
  6172. * Returns the dot product (float) of the point coordinates and the plane normal.
  6173. */
  6174. Plane.prototype.dotCoordinate = function (point) {
  6175. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6176. };
  6177. /**
  6178. * Updates the current Plane from the plane defined by the three passed points.
  6179. * Returns the updated Plane.
  6180. */
  6181. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6182. var x1 = point2.x - point1.x;
  6183. var y1 = point2.y - point1.y;
  6184. var z1 = point2.z - point1.z;
  6185. var x2 = point3.x - point1.x;
  6186. var y2 = point3.y - point1.y;
  6187. var z2 = point3.z - point1.z;
  6188. var yz = (y1 * z2) - (z1 * y2);
  6189. var xz = (z1 * x2) - (x1 * z2);
  6190. var xy = (x1 * y2) - (y1 * x2);
  6191. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6192. var invPyth;
  6193. if (pyth !== 0) {
  6194. invPyth = 1.0 / pyth;
  6195. }
  6196. else {
  6197. invPyth = 0.0;
  6198. }
  6199. this.normal.x = yz * invPyth;
  6200. this.normal.y = xz * invPyth;
  6201. this.normal.z = xy * invPyth;
  6202. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6203. return this;
  6204. };
  6205. /**
  6206. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6207. */
  6208. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6209. var dot = Vector3.Dot(this.normal, direction);
  6210. return (dot <= epsilon);
  6211. };
  6212. /**
  6213. * Returns the signed distance (float) from the passed point to the Plane.
  6214. */
  6215. Plane.prototype.signedDistanceTo = function (point) {
  6216. return Vector3.Dot(point, this.normal) + this.d;
  6217. };
  6218. // Statics
  6219. /**
  6220. * Returns a new Plane from the passed array.
  6221. */
  6222. Plane.FromArray = function (array) {
  6223. return new Plane(array[0], array[1], array[2], array[3]);
  6224. };
  6225. /**
  6226. * Returns a new Plane defined by the three passed points.
  6227. */
  6228. Plane.FromPoints = function (point1, point2, point3) {
  6229. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6230. result.copyFromPoints(point1, point2, point3);
  6231. return result;
  6232. };
  6233. /**
  6234. * Returns a new Plane the normal vector to this plane at the passed origin point.
  6235. * Note : the vector "normal" is updated because normalized.
  6236. */
  6237. Plane.FromPositionAndNormal = function (origin, normal) {
  6238. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6239. normal.normalize();
  6240. result.normal = normal;
  6241. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6242. return result;
  6243. };
  6244. /**
  6245. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  6246. */
  6247. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6248. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6249. return Vector3.Dot(point, normal) + d;
  6250. };
  6251. return Plane;
  6252. }());
  6253. BABYLON.Plane = Plane;
  6254. var Viewport = /** @class */ (function () {
  6255. /**
  6256. * Creates a Viewport object located at (x, y) and sized (width, height).
  6257. */
  6258. function Viewport(x, y, width, height) {
  6259. this.x = x;
  6260. this.y = y;
  6261. this.width = width;
  6262. this.height = height;
  6263. }
  6264. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6265. if (renderWidthOrEngine.getRenderWidth) {
  6266. var engine = renderWidthOrEngine;
  6267. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6268. }
  6269. var renderWidth = renderWidthOrEngine;
  6270. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6271. };
  6272. /**
  6273. * Returns a new Viewport copied from the current one.
  6274. */
  6275. Viewport.prototype.clone = function () {
  6276. return new Viewport(this.x, this.y, this.width, this.height);
  6277. };
  6278. return Viewport;
  6279. }());
  6280. BABYLON.Viewport = Viewport;
  6281. var Frustum = /** @class */ (function () {
  6282. function Frustum() {
  6283. }
  6284. /**
  6285. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  6286. */
  6287. Frustum.GetPlanes = function (transform) {
  6288. var frustumPlanes = [];
  6289. for (var index = 0; index < 6; index++) {
  6290. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6291. }
  6292. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6293. return frustumPlanes;
  6294. };
  6295. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6296. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6297. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6298. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6299. frustumPlane.d = transform.m[15] + transform.m[14];
  6300. frustumPlane.normalize();
  6301. };
  6302. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6303. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6304. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6305. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6306. frustumPlane.d = transform.m[15] - transform.m[14];
  6307. frustumPlane.normalize();
  6308. };
  6309. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6310. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6311. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6312. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6313. frustumPlane.d = transform.m[15] + transform.m[12];
  6314. frustumPlane.normalize();
  6315. };
  6316. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6317. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6318. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6319. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6320. frustumPlane.d = transform.m[15] - transform.m[12];
  6321. frustumPlane.normalize();
  6322. };
  6323. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6324. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6325. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6326. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6327. frustumPlane.d = transform.m[15] - transform.m[13];
  6328. frustumPlane.normalize();
  6329. };
  6330. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6331. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6332. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6333. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6334. frustumPlane.d = transform.m[15] + transform.m[13];
  6335. frustumPlane.normalize();
  6336. };
  6337. /**
  6338. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  6339. */
  6340. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6341. // Near
  6342. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6343. // Far
  6344. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6345. // Left
  6346. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6347. // Right
  6348. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6349. // Top
  6350. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6351. // Bottom
  6352. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6353. };
  6354. return Frustum;
  6355. }());
  6356. BABYLON.Frustum = Frustum;
  6357. var Space;
  6358. (function (Space) {
  6359. Space[Space["LOCAL"] = 0] = "LOCAL";
  6360. Space[Space["WORLD"] = 1] = "WORLD";
  6361. Space[Space["BONE"] = 2] = "BONE";
  6362. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6363. var Axis = /** @class */ (function () {
  6364. function Axis() {
  6365. }
  6366. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6367. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6368. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6369. return Axis;
  6370. }());
  6371. BABYLON.Axis = Axis;
  6372. ;
  6373. var BezierCurve = /** @class */ (function () {
  6374. function BezierCurve() {
  6375. }
  6376. /**
  6377. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  6378. */
  6379. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6380. // Extract X (which is equal to time here)
  6381. var f0 = 1 - 3 * x2 + 3 * x1;
  6382. var f1 = 3 * x2 - 6 * x1;
  6383. var f2 = 3 * x1;
  6384. var refinedT = t;
  6385. for (var i = 0; i < 5; i++) {
  6386. var refinedT2 = refinedT * refinedT;
  6387. var refinedT3 = refinedT2 * refinedT;
  6388. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6389. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6390. refinedT -= (x - t) * slope;
  6391. refinedT = Math.min(1, Math.max(0, refinedT));
  6392. }
  6393. // Resolve cubic bezier for the given x
  6394. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6395. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6396. Math.pow(refinedT, 3);
  6397. };
  6398. return BezierCurve;
  6399. }());
  6400. BABYLON.BezierCurve = BezierCurve;
  6401. var Orientation;
  6402. (function (Orientation) {
  6403. Orientation[Orientation["CW"] = 0] = "CW";
  6404. Orientation[Orientation["CCW"] = 1] = "CCW";
  6405. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6406. var Angle = /** @class */ (function () {
  6407. /**
  6408. * Creates an Angle object of "radians" radians (float).
  6409. */
  6410. function Angle(radians) {
  6411. var _this = this;
  6412. /**
  6413. * Returns the Angle value in degrees (float).
  6414. */
  6415. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  6416. /**
  6417. * Returns the Angle value in radians (float).
  6418. */
  6419. this.radians = function () { return _this._radians; };
  6420. this._radians = radians;
  6421. if (this._radians < 0.0)
  6422. this._radians += (2.0 * Math.PI);
  6423. }
  6424. /**
  6425. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  6426. */
  6427. Angle.BetweenTwoPoints = function (a, b) {
  6428. var delta = b.subtract(a);
  6429. var theta = Math.atan2(delta.y, delta.x);
  6430. return new Angle(theta);
  6431. };
  6432. /**
  6433. * Returns a new Angle object from the passed float in radians.
  6434. */
  6435. Angle.FromRadians = function (radians) {
  6436. return new Angle(radians);
  6437. };
  6438. /**
  6439. * Returns a new Angle object from the passed float in degrees.
  6440. */
  6441. Angle.FromDegrees = function (degrees) {
  6442. return new Angle(degrees * Math.PI / 180.0);
  6443. };
  6444. return Angle;
  6445. }());
  6446. BABYLON.Angle = Angle;
  6447. var Arc2 = /** @class */ (function () {
  6448. /**
  6449. * Creates an Arc object from the three passed points : start, middle and end.
  6450. */
  6451. function Arc2(startPoint, midPoint, endPoint) {
  6452. this.startPoint = startPoint;
  6453. this.midPoint = midPoint;
  6454. this.endPoint = endPoint;
  6455. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6456. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6457. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6458. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6459. 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);
  6460. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6461. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6462. var a1 = this.startAngle.degrees();
  6463. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6464. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6465. // angles correction
  6466. if (a2 - a1 > +180.0)
  6467. a2 -= 360.0;
  6468. if (a2 - a1 < -180.0)
  6469. a2 += 360.0;
  6470. if (a3 - a2 > +180.0)
  6471. a3 -= 360.0;
  6472. if (a3 - a2 < -180.0)
  6473. a3 += 360.0;
  6474. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6475. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6476. }
  6477. return Arc2;
  6478. }());
  6479. BABYLON.Arc2 = Arc2;
  6480. var Path2 = /** @class */ (function () {
  6481. /**
  6482. * Creates a Path2 object from the starting 2D coordinates x and y.
  6483. */
  6484. function Path2(x, y) {
  6485. this._points = new Array();
  6486. this._length = 0.0;
  6487. this.closed = false;
  6488. this._points.push(new Vector2(x, y));
  6489. }
  6490. /**
  6491. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  6492. * Returns the updated Path2.
  6493. */
  6494. Path2.prototype.addLineTo = function (x, y) {
  6495. if (this.closed) {
  6496. return this;
  6497. }
  6498. var newPoint = new Vector2(x, y);
  6499. var previousPoint = this._points[this._points.length - 1];
  6500. this._points.push(newPoint);
  6501. this._length += newPoint.subtract(previousPoint).length();
  6502. return this;
  6503. };
  6504. /**
  6505. * 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.
  6506. * Returns the updated Path2.
  6507. */
  6508. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6509. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6510. if (this.closed) {
  6511. return this;
  6512. }
  6513. var startPoint = this._points[this._points.length - 1];
  6514. var midPoint = new Vector2(midX, midY);
  6515. var endPoint = new Vector2(endX, endY);
  6516. var arc = new Arc2(startPoint, midPoint, endPoint);
  6517. var increment = arc.angle.radians() / numberOfSegments;
  6518. if (arc.orientation === Orientation.CW)
  6519. increment *= -1;
  6520. var currentAngle = arc.startAngle.radians() + increment;
  6521. for (var i = 0; i < numberOfSegments; i++) {
  6522. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6523. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6524. this.addLineTo(x, y);
  6525. currentAngle += increment;
  6526. }
  6527. return this;
  6528. };
  6529. /**
  6530. * Closes the Path2.
  6531. * Returns the Path2.
  6532. */
  6533. Path2.prototype.close = function () {
  6534. this.closed = true;
  6535. return this;
  6536. };
  6537. /**
  6538. * Returns the Path2 total length (float).
  6539. */
  6540. Path2.prototype.length = function () {
  6541. var result = this._length;
  6542. if (!this.closed) {
  6543. var lastPoint = this._points[this._points.length - 1];
  6544. var firstPoint = this._points[0];
  6545. result += (firstPoint.subtract(lastPoint).length());
  6546. }
  6547. return result;
  6548. };
  6549. /**
  6550. * Returns the Path2 internal array of points.
  6551. */
  6552. Path2.prototype.getPoints = function () {
  6553. return this._points;
  6554. };
  6555. /**
  6556. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  6557. */
  6558. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  6559. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  6560. return Vector2.Zero();
  6561. }
  6562. var lengthPosition = normalizedLengthPosition * this.length();
  6563. var previousOffset = 0;
  6564. for (var i = 0; i < this._points.length; i++) {
  6565. var j = (i + 1) % this._points.length;
  6566. var a = this._points[i];
  6567. var b = this._points[j];
  6568. var bToA = b.subtract(a);
  6569. var nextOffset = (bToA.length() + previousOffset);
  6570. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  6571. var dir = bToA.normalize();
  6572. var localOffset = lengthPosition - previousOffset;
  6573. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  6574. }
  6575. previousOffset = nextOffset;
  6576. }
  6577. return Vector2.Zero();
  6578. };
  6579. /**
  6580. * Returns a new Path2 starting at the coordinates (x, y).
  6581. */
  6582. Path2.StartingAt = function (x, y) {
  6583. return new Path2(x, y);
  6584. };
  6585. return Path2;
  6586. }());
  6587. BABYLON.Path2 = Path2;
  6588. var Path3D = /** @class */ (function () {
  6589. /**
  6590. * new Path3D(path, normal, raw)
  6591. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  6592. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  6593. * path : an array of Vector3, the curve axis of the Path3D
  6594. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  6595. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  6596. */
  6597. function Path3D(path, firstNormal, raw) {
  6598. if (firstNormal === void 0) { firstNormal = null; }
  6599. this.path = path;
  6600. this._curve = new Array();
  6601. this._distances = new Array();
  6602. this._tangents = new Array();
  6603. this._normals = new Array();
  6604. this._binormals = new Array();
  6605. for (var p = 0; p < path.length; p++) {
  6606. this._curve[p] = path[p].clone(); // hard copy
  6607. }
  6608. this._raw = raw || false;
  6609. this._compute(firstNormal);
  6610. }
  6611. /**
  6612. * Returns the Path3D array of successive Vector3 designing its curve.
  6613. */
  6614. Path3D.prototype.getCurve = function () {
  6615. return this._curve;
  6616. };
  6617. /**
  6618. * Returns an array populated with tangent vectors on each Path3D curve point.
  6619. */
  6620. Path3D.prototype.getTangents = function () {
  6621. return this._tangents;
  6622. };
  6623. /**
  6624. * Returns an array populated with normal vectors on each Path3D curve point.
  6625. */
  6626. Path3D.prototype.getNormals = function () {
  6627. return this._normals;
  6628. };
  6629. /**
  6630. * Returns an array populated with binormal vectors on each Path3D curve point.
  6631. */
  6632. Path3D.prototype.getBinormals = function () {
  6633. return this._binormals;
  6634. };
  6635. /**
  6636. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  6637. */
  6638. Path3D.prototype.getDistances = function () {
  6639. return this._distances;
  6640. };
  6641. /**
  6642. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  6643. * Returns the same object updated.
  6644. */
  6645. Path3D.prototype.update = function (path, firstNormal) {
  6646. if (firstNormal === void 0) { firstNormal = null; }
  6647. for (var p = 0; p < path.length; p++) {
  6648. this._curve[p].x = path[p].x;
  6649. this._curve[p].y = path[p].y;
  6650. this._curve[p].z = path[p].z;
  6651. }
  6652. this._compute(firstNormal);
  6653. return this;
  6654. };
  6655. // private function compute() : computes tangents, normals and binormals
  6656. Path3D.prototype._compute = function (firstNormal) {
  6657. var l = this._curve.length;
  6658. // first and last tangents
  6659. this._tangents[0] = this._getFirstNonNullVector(0);
  6660. if (!this._raw) {
  6661. this._tangents[0].normalize();
  6662. }
  6663. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  6664. if (!this._raw) {
  6665. this._tangents[l - 1].normalize();
  6666. }
  6667. // normals and binormals at first point : arbitrary vector with _normalVector()
  6668. var tg0 = this._tangents[0];
  6669. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  6670. this._normals[0] = pp0;
  6671. if (!this._raw) {
  6672. this._normals[0].normalize();
  6673. }
  6674. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  6675. if (!this._raw) {
  6676. this._binormals[0].normalize();
  6677. }
  6678. this._distances[0] = 0.0;
  6679. // normals and binormals : next points
  6680. var prev; // previous vector (segment)
  6681. var cur; // current vector (segment)
  6682. var curTang; // current tangent
  6683. // previous normal
  6684. var prevBinor; // previous binormal
  6685. for (var i = 1; i < l; i++) {
  6686. // tangents
  6687. prev = this._getLastNonNullVector(i);
  6688. if (i < l - 1) {
  6689. cur = this._getFirstNonNullVector(i);
  6690. this._tangents[i] = prev.add(cur);
  6691. this._tangents[i].normalize();
  6692. }
  6693. this._distances[i] = this._distances[i - 1] + prev.length();
  6694. // normals and binormals
  6695. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  6696. curTang = this._tangents[i];
  6697. prevBinor = this._binormals[i - 1];
  6698. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  6699. if (!this._raw) {
  6700. this._normals[i].normalize();
  6701. }
  6702. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  6703. if (!this._raw) {
  6704. this._binormals[i].normalize();
  6705. }
  6706. }
  6707. };
  6708. // private function getFirstNonNullVector(index)
  6709. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  6710. Path3D.prototype._getFirstNonNullVector = function (index) {
  6711. var i = 1;
  6712. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  6713. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  6714. i++;
  6715. nNVector = this._curve[index + i].subtract(this._curve[index]);
  6716. }
  6717. return nNVector;
  6718. };
  6719. // private function getLastNonNullVector(index)
  6720. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  6721. Path3D.prototype._getLastNonNullVector = function (index) {
  6722. var i = 1;
  6723. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  6724. while (nLVector.length() === 0 && index > i + 1) {
  6725. i++;
  6726. nLVector = this._curve[index].subtract(this._curve[index - i]);
  6727. }
  6728. return nLVector;
  6729. };
  6730. // private function normalVector(v0, vt, va) :
  6731. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  6732. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  6733. Path3D.prototype._normalVector = function (v0, vt, va) {
  6734. var normal0;
  6735. var tgl = vt.length();
  6736. if (tgl === 0.0) {
  6737. tgl = 1.0;
  6738. }
  6739. if (va === undefined || va === null) {
  6740. var point;
  6741. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  6742. point = new Vector3(0.0, -1.0, 0.0);
  6743. }
  6744. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  6745. point = new Vector3(1.0, 0.0, 0.0);
  6746. }
  6747. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  6748. point = new Vector3(0.0, 0.0, 1.0);
  6749. }
  6750. else {
  6751. point = Vector3.Zero();
  6752. }
  6753. normal0 = Vector3.Cross(vt, point);
  6754. }
  6755. else {
  6756. normal0 = Vector3.Cross(vt, va);
  6757. Vector3.CrossToRef(normal0, vt, normal0);
  6758. }
  6759. normal0.normalize();
  6760. return normal0;
  6761. };
  6762. return Path3D;
  6763. }());
  6764. BABYLON.Path3D = Path3D;
  6765. var Curve3 = /** @class */ (function () {
  6766. /**
  6767. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  6768. * A Curve3 is designed from a series of successive Vector3.
  6769. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  6770. */
  6771. function Curve3(points) {
  6772. this._length = 0.0;
  6773. this._points = points;
  6774. this._length = this._computeLength(points);
  6775. }
  6776. /**
  6777. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  6778. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  6779. * @param v1 (Vector3) the control point
  6780. * @param v2 (Vector3) the end point of the Quadratic Bezier
  6781. * @param nbPoints (integer) the wanted number of points in the curve
  6782. */
  6783. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  6784. nbPoints = nbPoints > 2 ? nbPoints : 3;
  6785. var bez = new Array();
  6786. var equation = function (t, val0, val1, val2) {
  6787. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  6788. return res;
  6789. };
  6790. for (var i = 0; i <= nbPoints; i++) {
  6791. 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)));
  6792. }
  6793. return new Curve3(bez);
  6794. };
  6795. /**
  6796. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  6797. * @param v0 (Vector3) the origin point of the Cubic Bezier
  6798. * @param v1 (Vector3) the first control point
  6799. * @param v2 (Vector3) the second control point
  6800. * @param v3 (Vector3) the end point of the Cubic Bezier
  6801. * @param nbPoints (integer) the wanted number of points in the curve
  6802. */
  6803. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  6804. nbPoints = nbPoints > 3 ? nbPoints : 4;
  6805. var bez = new Array();
  6806. var equation = function (t, val0, val1, val2, val3) {
  6807. 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;
  6808. return res;
  6809. };
  6810. for (var i = 0; i <= nbPoints; i++) {
  6811. 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)));
  6812. }
  6813. return new Curve3(bez);
  6814. };
  6815. /**
  6816. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  6817. * @param p1 (Vector3) the origin point of the Hermite Spline
  6818. * @param t1 (Vector3) the tangent vector at the origin point
  6819. * @param p2 (Vector3) the end point of the Hermite Spline
  6820. * @param t2 (Vector3) the tangent vector at the end point
  6821. * @param nbPoints (integer) the wanted number of points in the curve
  6822. */
  6823. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  6824. var hermite = new Array();
  6825. var step = 1.0 / nbPoints;
  6826. for (var i = 0; i <= nbPoints; i++) {
  6827. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  6828. }
  6829. return new Curve3(hermite);
  6830. };
  6831. /**
  6832. * Returns a Curve3 object along a CatmullRom Spline curve :
  6833. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  6834. * @param nbPoints (integer) the wanted number of points between each curve control points.
  6835. */
  6836. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  6837. var totalPoints = new Array();
  6838. totalPoints.push(points[0].clone());
  6839. Array.prototype.push.apply(totalPoints, points);
  6840. totalPoints.push(points[points.length - 1].clone());
  6841. var catmullRom = new Array();
  6842. var step = 1.0 / nbPoints;
  6843. var amount = 0.0;
  6844. for (var i = 0; i < totalPoints.length - 3; i++) {
  6845. amount = 0;
  6846. for (var c = 0; c < nbPoints; c++) {
  6847. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6848. amount += step;
  6849. }
  6850. }
  6851. i--;
  6852. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6853. return new Curve3(catmullRom);
  6854. };
  6855. /**
  6856. * Returns the Curve3 stored array of successive Vector3
  6857. */
  6858. Curve3.prototype.getPoints = function () {
  6859. return this._points;
  6860. };
  6861. /**
  6862. * Returns the computed length (float) of the curve.
  6863. */
  6864. Curve3.prototype.length = function () {
  6865. return this._length;
  6866. };
  6867. /**
  6868. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  6869. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  6870. * curveA and curveB keep unchanged.
  6871. */
  6872. Curve3.prototype.continue = function (curve) {
  6873. var lastPoint = this._points[this._points.length - 1];
  6874. var continuedPoints = this._points.slice();
  6875. var curvePoints = curve.getPoints();
  6876. for (var i = 1; i < curvePoints.length; i++) {
  6877. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  6878. }
  6879. var continuedCurve = new Curve3(continuedPoints);
  6880. return continuedCurve;
  6881. };
  6882. Curve3.prototype._computeLength = function (path) {
  6883. var l = 0;
  6884. for (var i = 1; i < path.length; i++) {
  6885. l += (path[i].subtract(path[i - 1])).length();
  6886. }
  6887. return l;
  6888. };
  6889. return Curve3;
  6890. }());
  6891. BABYLON.Curve3 = Curve3;
  6892. // Vertex formats
  6893. var PositionNormalVertex = /** @class */ (function () {
  6894. function PositionNormalVertex(position, normal) {
  6895. if (position === void 0) { position = Vector3.Zero(); }
  6896. if (normal === void 0) { normal = Vector3.Up(); }
  6897. this.position = position;
  6898. this.normal = normal;
  6899. }
  6900. PositionNormalVertex.prototype.clone = function () {
  6901. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  6902. };
  6903. return PositionNormalVertex;
  6904. }());
  6905. BABYLON.PositionNormalVertex = PositionNormalVertex;
  6906. var PositionNormalTextureVertex = /** @class */ (function () {
  6907. function PositionNormalTextureVertex(position, normal, uv) {
  6908. if (position === void 0) { position = Vector3.Zero(); }
  6909. if (normal === void 0) { normal = Vector3.Up(); }
  6910. if (uv === void 0) { uv = Vector2.Zero(); }
  6911. this.position = position;
  6912. this.normal = normal;
  6913. this.uv = uv;
  6914. }
  6915. PositionNormalTextureVertex.prototype.clone = function () {
  6916. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  6917. };
  6918. return PositionNormalTextureVertex;
  6919. }());
  6920. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  6921. // Temporary pre-allocated objects for engine internal use
  6922. // usage in any internal function :
  6923. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  6924. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  6925. var Tmp = /** @class */ (function () {
  6926. function Tmp() {
  6927. }
  6928. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  6929. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  6930. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  6931. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  6932. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  6933. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  6934. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  6935. Matrix.Zero(), Matrix.Zero(),
  6936. Matrix.Zero(), Matrix.Zero(),
  6937. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  6938. return Tmp;
  6939. }());
  6940. BABYLON.Tmp = Tmp;
  6941. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  6942. var MathTmp = /** @class */ (function () {
  6943. function MathTmp() {
  6944. }
  6945. MathTmp.Vector3 = [Vector3.Zero()];
  6946. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  6947. MathTmp.Quaternion = [Quaternion.Zero()];
  6948. return MathTmp;
  6949. }());
  6950. })(BABYLON || (BABYLON = {}));
  6951. //# sourceMappingURL=babylon.math.js.map
  6952. "use strict";
  6953. var BABYLON;
  6954. (function (BABYLON) {
  6955. var Scalar = /** @class */ (function () {
  6956. function Scalar() {
  6957. }
  6958. /**
  6959. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  6960. */
  6961. Scalar.WithinEpsilon = function (a, b, epsilon) {
  6962. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  6963. var num = a - b;
  6964. return -epsilon <= num && num <= epsilon;
  6965. };
  6966. /**
  6967. * Returns a string : the upper case translation of the number i to hexadecimal.
  6968. */
  6969. Scalar.ToHex = function (i) {
  6970. var str = i.toString(16);
  6971. if (i <= 15) {
  6972. return ("0" + str).toUpperCase();
  6973. }
  6974. return str.toUpperCase();
  6975. };
  6976. /**
  6977. * Returns -1 if value is negative and +1 is value is positive.
  6978. * Returns the value itself if it's equal to zero.
  6979. */
  6980. Scalar.Sign = function (value) {
  6981. value = +value; // convert to a number
  6982. if (value === 0 || isNaN(value))
  6983. return value;
  6984. return value > 0 ? 1 : -1;
  6985. };
  6986. /**
  6987. * Returns the value itself if it's between min and max.
  6988. * Returns min if the value is lower than min.
  6989. * Returns max if the value is greater than max.
  6990. */
  6991. Scalar.Clamp = function (value, min, max) {
  6992. if (min === void 0) { min = 0; }
  6993. if (max === void 0) { max = 1; }
  6994. return Math.min(max, Math.max(min, value));
  6995. };
  6996. /**
  6997. * Returns the log2 of value.
  6998. */
  6999. Scalar.Log2 = function (value) {
  7000. return Math.log(value) * Math.LOG2E;
  7001. };
  7002. /**
  7003. * Loops the value, so that it is never larger than length and never smaller than 0.
  7004. *
  7005. * This is similar to the modulo operator but it works with floating point numbers.
  7006. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  7007. * With t = 5 and length = 2.5, the result would be 0.0.
  7008. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  7009. */
  7010. Scalar.Repeat = function (value, length) {
  7011. return value - Math.floor(value / length) * length;
  7012. };
  7013. /**
  7014. * Normalize the value between 0.0 and 1.0 using min and max values
  7015. */
  7016. Scalar.Normalize = function (value, min, max) {
  7017. return (value - min) / (max - min);
  7018. };
  7019. /**
  7020. * Denormalize the value from 0.0 and 1.0 using min and max values
  7021. */
  7022. Scalar.Denormalize = function (normalized, min, max) {
  7023. return (normalized * (max - min) + min);
  7024. };
  7025. /**
  7026. * Calculates the shortest difference between two given angles given in degrees.
  7027. */
  7028. Scalar.DeltaAngle = function (current, target) {
  7029. var num = Scalar.Repeat(target - current, 360.0);
  7030. if (num > 180.0) {
  7031. num -= 360.0;
  7032. }
  7033. return num;
  7034. };
  7035. /**
  7036. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  7037. *
  7038. * The returned value will move back and forth between 0 and length
  7039. */
  7040. Scalar.PingPong = function (tx, length) {
  7041. var t = Scalar.Repeat(tx, length * 2.0);
  7042. return length - Math.abs(t - length);
  7043. };
  7044. /**
  7045. * Interpolates between min and max with smoothing at the limits.
  7046. *
  7047. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  7048. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  7049. */
  7050. Scalar.SmoothStep = function (from, to, tx) {
  7051. var t = Scalar.Clamp(tx);
  7052. t = -2.0 * t * t * t + 3.0 * t * t;
  7053. return to * t + from * (1.0 - t);
  7054. };
  7055. /**
  7056. * Moves a value current towards target.
  7057. *
  7058. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  7059. * Negative values of maxDelta pushes the value away from target.
  7060. */
  7061. Scalar.MoveTowards = function (current, target, maxDelta) {
  7062. var result = 0;
  7063. if (Math.abs(target - current) <= maxDelta) {
  7064. result = target;
  7065. }
  7066. else {
  7067. result = current + Scalar.Sign(target - current) * maxDelta;
  7068. }
  7069. return result;
  7070. };
  7071. /**
  7072. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7073. *
  7074. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7075. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7076. */
  7077. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7078. var num = Scalar.DeltaAngle(current, target);
  7079. var result = 0;
  7080. if (-maxDelta < num && num < maxDelta) {
  7081. result = target;
  7082. }
  7083. else {
  7084. target = current + num;
  7085. result = Scalar.MoveTowards(current, target, maxDelta);
  7086. }
  7087. return result;
  7088. };
  7089. /**
  7090. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7091. */
  7092. Scalar.Lerp = function (start, end, amount) {
  7093. return start + ((end - start) * amount);
  7094. };
  7095. /**
  7096. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7097. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7098. */
  7099. Scalar.LerpAngle = function (start, end, amount) {
  7100. var num = Scalar.Repeat(end - start, 360.0);
  7101. if (num > 180.0) {
  7102. num -= 360.0;
  7103. }
  7104. return start + num * Scalar.Clamp(amount);
  7105. };
  7106. /**
  7107. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7108. */
  7109. Scalar.InverseLerp = function (a, b, value) {
  7110. var result = 0;
  7111. if (a != b) {
  7112. result = Scalar.Clamp((value - a) / (b - a));
  7113. }
  7114. else {
  7115. result = 0.0;
  7116. }
  7117. return result;
  7118. };
  7119. /**
  7120. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7121. */
  7122. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7123. var squared = amount * amount;
  7124. var cubed = amount * squared;
  7125. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7126. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7127. var part3 = (cubed - (2.0 * squared)) + amount;
  7128. var part4 = cubed - squared;
  7129. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7130. };
  7131. /**
  7132. * Returns a random float number between and min and max values
  7133. */
  7134. Scalar.RandomRange = function (min, max) {
  7135. if (min === max)
  7136. return min;
  7137. return ((Math.random() * (max - min)) + min);
  7138. };
  7139. /**
  7140. * This function returns percentage of a number in a given range.
  7141. *
  7142. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7143. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7144. */
  7145. Scalar.RangeToPercent = function (number, min, max) {
  7146. return ((number - min) / (max - min));
  7147. };
  7148. /**
  7149. * This function returns number that corresponds to the percentage in a given range.
  7150. *
  7151. * PercentToRange(0.34,0,100) will return 34.
  7152. */
  7153. Scalar.PercentToRange = function (percent, min, max) {
  7154. return ((max - min) * percent + min);
  7155. };
  7156. /**
  7157. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7158. * @param angle The angle to normalize in radian.
  7159. * @return The converted angle.
  7160. */
  7161. Scalar.NormalizeRadians = function (angle) {
  7162. // More precise but slower version kept for reference.
  7163. // angle = angle % Tools.TwoPi;
  7164. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7165. //if (angle > Math.PI) {
  7166. // angle -= Tools.TwoPi;
  7167. //}
  7168. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7169. return angle;
  7170. };
  7171. /**
  7172. * Two pi constants convenient for computation.
  7173. */
  7174. Scalar.TwoPi = Math.PI * 2;
  7175. return Scalar;
  7176. }());
  7177. BABYLON.Scalar = Scalar;
  7178. })(BABYLON || (BABYLON = {}));
  7179. //# sourceMappingURL=babylon.math.scalar.js.map
  7180. "use strict";
  7181. //# sourceMappingURL=babylon.mixins.js.map
  7182. "use strict";
  7183. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7184. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7185. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7186. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7187. //# sourceMappingURL=babylon.webgl2.js.map
  7188. "use strict";
  7189. var BABYLON;
  7190. (function (BABYLON) {
  7191. var __decoratorInitialStore = {};
  7192. var __mergedStore = {};
  7193. var _copySource = function (creationFunction, source, instanciate) {
  7194. var destination = creationFunction();
  7195. // Tags
  7196. if (BABYLON.Tags) {
  7197. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7198. }
  7199. var classStore = getMergedStore(destination);
  7200. // Properties
  7201. for (var property in classStore) {
  7202. var propertyDescriptor = classStore[property];
  7203. var sourceProperty = source[property];
  7204. var propertyType = propertyDescriptor.type;
  7205. if (sourceProperty !== undefined && sourceProperty !== null) {
  7206. switch (propertyType) {
  7207. case 0: // Value
  7208. case 6:// Mesh reference
  7209. destination[property] = sourceProperty;
  7210. break;
  7211. case 1:// Texture
  7212. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7213. break;
  7214. case 2: // Color3
  7215. case 3: // FresnelParameters
  7216. case 4: // Vector2
  7217. case 5: // Vector3
  7218. case 7: // Color Curves
  7219. case 10:// Quaternion
  7220. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7221. break;
  7222. }
  7223. }
  7224. }
  7225. return destination;
  7226. };
  7227. function getDirectStore(target) {
  7228. var classKey = target.getClassName();
  7229. if (!__decoratorInitialStore[classKey]) {
  7230. __decoratorInitialStore[classKey] = {};
  7231. }
  7232. return __decoratorInitialStore[classKey];
  7233. }
  7234. /**
  7235. * Return the list of properties flagged as serializable
  7236. * @param target: host object
  7237. */
  7238. function getMergedStore(target) {
  7239. var classKey = target.getClassName();
  7240. if (__mergedStore[classKey]) {
  7241. return __mergedStore[classKey];
  7242. }
  7243. __mergedStore[classKey] = {};
  7244. var store = __mergedStore[classKey];
  7245. var currentTarget = target;
  7246. var currentKey = classKey;
  7247. while (currentKey) {
  7248. var initialStore = __decoratorInitialStore[currentKey];
  7249. for (var property in initialStore) {
  7250. store[property] = initialStore[property];
  7251. }
  7252. var parent_1 = void 0;
  7253. var done = false;
  7254. do {
  7255. parent_1 = Object.getPrototypeOf(currentTarget);
  7256. if (!parent_1.getClassName) {
  7257. done = true;
  7258. break;
  7259. }
  7260. if (parent_1.getClassName() !== currentKey) {
  7261. break;
  7262. }
  7263. currentTarget = parent_1;
  7264. } while (parent_1);
  7265. if (done) {
  7266. break;
  7267. }
  7268. currentKey = parent_1.getClassName();
  7269. currentTarget = parent_1;
  7270. }
  7271. return store;
  7272. }
  7273. function generateSerializableMember(type, sourceName) {
  7274. return function (target, propertyKey) {
  7275. var classStore = getDirectStore(target);
  7276. if (!classStore[propertyKey]) {
  7277. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7278. }
  7279. };
  7280. }
  7281. function generateExpandMember(setCallback, targetKey) {
  7282. if (targetKey === void 0) { targetKey = null; }
  7283. return function (target, propertyKey) {
  7284. var key = targetKey || ("_" + propertyKey);
  7285. Object.defineProperty(target, propertyKey, {
  7286. get: function () {
  7287. return this[key];
  7288. },
  7289. set: function (value) {
  7290. if (this[key] === value) {
  7291. return;
  7292. }
  7293. this[key] = value;
  7294. target[setCallback].apply(this);
  7295. },
  7296. enumerable: true,
  7297. configurable: true
  7298. });
  7299. };
  7300. }
  7301. function expandToProperty(callback, targetKey) {
  7302. if (targetKey === void 0) { targetKey = null; }
  7303. return generateExpandMember(callback, targetKey);
  7304. }
  7305. BABYLON.expandToProperty = expandToProperty;
  7306. function serialize(sourceName) {
  7307. return generateSerializableMember(0, sourceName); // value member
  7308. }
  7309. BABYLON.serialize = serialize;
  7310. function serializeAsTexture(sourceName) {
  7311. return generateSerializableMember(1, sourceName); // texture member
  7312. }
  7313. BABYLON.serializeAsTexture = serializeAsTexture;
  7314. function serializeAsColor3(sourceName) {
  7315. return generateSerializableMember(2, sourceName); // color3 member
  7316. }
  7317. BABYLON.serializeAsColor3 = serializeAsColor3;
  7318. function serializeAsFresnelParameters(sourceName) {
  7319. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7320. }
  7321. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7322. function serializeAsVector2(sourceName) {
  7323. return generateSerializableMember(4, sourceName); // vector2 member
  7324. }
  7325. BABYLON.serializeAsVector2 = serializeAsVector2;
  7326. function serializeAsVector3(sourceName) {
  7327. return generateSerializableMember(5, sourceName); // vector3 member
  7328. }
  7329. BABYLON.serializeAsVector3 = serializeAsVector3;
  7330. function serializeAsMeshReference(sourceName) {
  7331. return generateSerializableMember(6, sourceName); // mesh reference member
  7332. }
  7333. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7334. function serializeAsColorCurves(sourceName) {
  7335. return generateSerializableMember(7, sourceName); // color curves
  7336. }
  7337. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7338. function serializeAsColor4(sourceName) {
  7339. return generateSerializableMember(8, sourceName); // color 4
  7340. }
  7341. BABYLON.serializeAsColor4 = serializeAsColor4;
  7342. function serializeAsImageProcessingConfiguration(sourceName) {
  7343. return generateSerializableMember(9, sourceName); // image processing
  7344. }
  7345. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7346. function serializeAsQuaternion(sourceName) {
  7347. return generateSerializableMember(10, sourceName); // quaternion member
  7348. }
  7349. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7350. var SerializationHelper = /** @class */ (function () {
  7351. function SerializationHelper() {
  7352. }
  7353. SerializationHelper.Serialize = function (entity, serializationObject) {
  7354. if (!serializationObject) {
  7355. serializationObject = {};
  7356. }
  7357. // Tags
  7358. if (BABYLON.Tags) {
  7359. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7360. }
  7361. var serializedProperties = getMergedStore(entity);
  7362. // Properties
  7363. for (var property in serializedProperties) {
  7364. var propertyDescriptor = serializedProperties[property];
  7365. var targetPropertyName = propertyDescriptor.sourceName || property;
  7366. var propertyType = propertyDescriptor.type;
  7367. var sourceProperty = entity[property];
  7368. if (sourceProperty !== undefined && sourceProperty !== null) {
  7369. switch (propertyType) {
  7370. case 0:// Value
  7371. serializationObject[targetPropertyName] = sourceProperty;
  7372. break;
  7373. case 1:// Texture
  7374. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7375. break;
  7376. case 2:// Color3
  7377. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7378. break;
  7379. case 3:// FresnelParameters
  7380. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7381. break;
  7382. case 4:// Vector2
  7383. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7384. break;
  7385. case 5:// Vector3
  7386. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7387. break;
  7388. case 6:// Mesh reference
  7389. serializationObject[targetPropertyName] = sourceProperty.id;
  7390. break;
  7391. case 7:// Color Curves
  7392. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7393. break;
  7394. case 8:// Color 4
  7395. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7396. break;
  7397. case 9:// Image Processing
  7398. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7399. break;
  7400. }
  7401. }
  7402. }
  7403. return serializationObject;
  7404. };
  7405. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7406. if (rootUrl === void 0) { rootUrl = null; }
  7407. var destination = creationFunction();
  7408. if (!rootUrl) {
  7409. rootUrl = "";
  7410. }
  7411. // Tags
  7412. if (BABYLON.Tags) {
  7413. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7414. }
  7415. var classStore = getMergedStore(destination);
  7416. // Properties
  7417. for (var property in classStore) {
  7418. var propertyDescriptor = classStore[property];
  7419. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7420. var propertyType = propertyDescriptor.type;
  7421. if (sourceProperty !== undefined && sourceProperty !== null) {
  7422. var dest = destination;
  7423. switch (propertyType) {
  7424. case 0:// Value
  7425. dest[property] = sourceProperty;
  7426. break;
  7427. case 1:// Texture
  7428. if (scene) {
  7429. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7430. }
  7431. break;
  7432. case 2:// Color3
  7433. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7434. break;
  7435. case 3:// FresnelParameters
  7436. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7437. break;
  7438. case 4:// Vector2
  7439. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7440. break;
  7441. case 5:// Vector3
  7442. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7443. break;
  7444. case 6:// Mesh reference
  7445. if (scene) {
  7446. dest[property] = scene.getLastMeshByID(sourceProperty);
  7447. }
  7448. break;
  7449. case 7:// Color Curves
  7450. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7451. break;
  7452. case 8:// Color 4
  7453. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7454. break;
  7455. case 9:// Image Processing
  7456. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7457. break;
  7458. }
  7459. }
  7460. }
  7461. return destination;
  7462. };
  7463. SerializationHelper.Clone = function (creationFunction, source) {
  7464. return _copySource(creationFunction, source, false);
  7465. };
  7466. SerializationHelper.Instanciate = function (creationFunction, source) {
  7467. return _copySource(creationFunction, source, true);
  7468. };
  7469. return SerializationHelper;
  7470. }());
  7471. BABYLON.SerializationHelper = SerializationHelper;
  7472. })(BABYLON || (BABYLON = {}));
  7473. //# sourceMappingURL=babylon.decorators.js.map
  7474. "use strict";
  7475. var BABYLON;
  7476. (function (BABYLON) {
  7477. /**
  7478. * Wrapper class for promise with external resolve and reject.
  7479. */
  7480. var Deferred = /** @class */ (function () {
  7481. /**
  7482. * Constructor for this deferred object.
  7483. */
  7484. function Deferred() {
  7485. var _this = this;
  7486. this.promise = new Promise(function (resolve, reject) {
  7487. _this._resolve = resolve;
  7488. _this._reject = reject;
  7489. });
  7490. }
  7491. Object.defineProperty(Deferred.prototype, "resolve", {
  7492. /**
  7493. * The resolve method of the promise associated with this deferred object.
  7494. */
  7495. get: function () {
  7496. return this._resolve;
  7497. },
  7498. enumerable: true,
  7499. configurable: true
  7500. });
  7501. Object.defineProperty(Deferred.prototype, "reject", {
  7502. /**
  7503. * The reject method of the promise associated with this deferred object.
  7504. */
  7505. get: function () {
  7506. return this._reject;
  7507. },
  7508. enumerable: true,
  7509. configurable: true
  7510. });
  7511. return Deferred;
  7512. }());
  7513. BABYLON.Deferred = Deferred;
  7514. })(BABYLON || (BABYLON = {}));
  7515. //# sourceMappingURL=babylon.deferred.js.map
  7516. "use strict";
  7517. var BABYLON;
  7518. (function (BABYLON) {
  7519. /**
  7520. * A class serves as a medium between the observable and its observers
  7521. */
  7522. var EventState = /** @class */ (function () {
  7523. /**
  7524. * Create a new EventState
  7525. * @param mask defines the mask associated with this state
  7526. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7527. * @param target defines the original target of the state
  7528. * @param currentTarget defines the current target of the state
  7529. */
  7530. function EventState(mask, skipNextObservers, target, currentTarget) {
  7531. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7532. this.initalize(mask, skipNextObservers, target, currentTarget);
  7533. }
  7534. /**
  7535. * Initialize the current event state
  7536. * @param mask defines the mask associated with this state
  7537. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7538. * @param target defines the original target of the state
  7539. * @param currentTarget defines the current target of the state
  7540. * @returns the current event state
  7541. */
  7542. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  7543. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7544. this.mask = mask;
  7545. this.skipNextObservers = skipNextObservers;
  7546. this.target = target;
  7547. this.currentTarget = currentTarget;
  7548. return this;
  7549. };
  7550. return EventState;
  7551. }());
  7552. BABYLON.EventState = EventState;
  7553. /**
  7554. * Represent an Observer registered to a given Observable object.
  7555. */
  7556. var Observer = /** @class */ (function () {
  7557. /**
  7558. * Creates a new observer
  7559. * @param callback defines the callback to call when the observer is notified
  7560. * @param mask defines the mask of the observer (used to filter notifications)
  7561. * @param scope defines the current scope used to restore the JS context
  7562. */
  7563. function Observer(
  7564. /**
  7565. * Defines the callback to call when the observer is notified
  7566. */
  7567. callback,
  7568. /**
  7569. * Defines the mask of the observer (used to filter notifications)
  7570. */
  7571. mask,
  7572. /**
  7573. * Defines the current scope used to restore the JS context
  7574. */
  7575. scope) {
  7576. if (scope === void 0) { scope = null; }
  7577. this.callback = callback;
  7578. this.mask = mask;
  7579. this.scope = scope;
  7580. /** @ignore */
  7581. this._willBeUnregistered = false;
  7582. /**
  7583. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  7584. */
  7585. this.unregisterOnNextCall = false;
  7586. }
  7587. return Observer;
  7588. }());
  7589. BABYLON.Observer = Observer;
  7590. /**
  7591. * Represent a list of observers registered to multiple Observables object.
  7592. */
  7593. var MultiObserver = /** @class */ (function () {
  7594. function MultiObserver() {
  7595. }
  7596. /**
  7597. * Release associated resources
  7598. */
  7599. MultiObserver.prototype.dispose = function () {
  7600. if (this._observers && this._observables) {
  7601. for (var index = 0; index < this._observers.length; index++) {
  7602. this._observables[index].remove(this._observers[index]);
  7603. }
  7604. }
  7605. this._observers = null;
  7606. this._observables = null;
  7607. };
  7608. /**
  7609. * Raise a callback when one of the observable will notify
  7610. * @param observables defines a list of observables to watch
  7611. * @param callback defines the callback to call on notification
  7612. * @param mask defines the mask used to filter notifications
  7613. * @param scope defines the current scope used to restore the JS context
  7614. * @returns the new MultiObserver
  7615. */
  7616. MultiObserver.Watch = function (observables, callback, mask, scope) {
  7617. if (mask === void 0) { mask = -1; }
  7618. if (scope === void 0) { scope = null; }
  7619. var result = new MultiObserver();
  7620. result._observers = new Array();
  7621. result._observables = observables;
  7622. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  7623. var observable = observables_1[_i];
  7624. var observer = observable.add(callback, mask, false, scope);
  7625. if (observer) {
  7626. result._observers.push(observer);
  7627. }
  7628. }
  7629. return result;
  7630. };
  7631. return MultiObserver;
  7632. }());
  7633. BABYLON.MultiObserver = MultiObserver;
  7634. /**
  7635. * The Observable class is a simple implementation of the Observable pattern.
  7636. * 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.
  7637. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  7638. * 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).
  7639. * 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.
  7640. */
  7641. var Observable = /** @class */ (function () {
  7642. /**
  7643. * Creates a new observable
  7644. * @param onObserverAdded defines a callback to call when a new observer is added
  7645. */
  7646. function Observable(onObserverAdded) {
  7647. this._observers = new Array();
  7648. this._eventState = new EventState(0);
  7649. if (onObserverAdded) {
  7650. this._onObserverAdded = onObserverAdded;
  7651. }
  7652. }
  7653. /**
  7654. * Create a new Observer with the specified callback
  7655. * @param callback the callback that will be executed for that Observer
  7656. * @param mask the mask used to filter observers
  7657. * @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.
  7658. * @param scope optional scope for the callback to be called from
  7659. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  7660. * @returns the new observer created for the callback
  7661. */
  7662. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  7663. if (mask === void 0) { mask = -1; }
  7664. if (insertFirst === void 0) { insertFirst = false; }
  7665. if (scope === void 0) { scope = null; }
  7666. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  7667. if (!callback) {
  7668. return null;
  7669. }
  7670. var observer = new Observer(callback, mask, scope);
  7671. observer.unregisterOnNextCall = unregisterOnFirstCall;
  7672. if (insertFirst) {
  7673. this._observers.unshift(observer);
  7674. }
  7675. else {
  7676. this._observers.push(observer);
  7677. }
  7678. if (this._onObserverAdded) {
  7679. this._onObserverAdded(observer);
  7680. }
  7681. return observer;
  7682. };
  7683. /**
  7684. * Remove an Observer from the Observable object
  7685. * @param observer the instance of the Observer to remove
  7686. * @returns false if it doesn't belong to this Observable
  7687. */
  7688. Observable.prototype.remove = function (observer) {
  7689. if (!observer) {
  7690. return false;
  7691. }
  7692. var index = this._observers.indexOf(observer);
  7693. if (index !== -1) {
  7694. this._observers.splice(index, 1);
  7695. return true;
  7696. }
  7697. return false;
  7698. };
  7699. /**
  7700. * Remove a callback from the Observable object
  7701. * @param callback the callback to remove
  7702. * @param scope optional scope. If used only the callbacks with this scope will be removed
  7703. * @returns false if it doesn't belong to this Observable
  7704. */
  7705. Observable.prototype.removeCallback = function (callback, scope) {
  7706. for (var index = 0; index < this._observers.length; index++) {
  7707. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  7708. this._observers.splice(index, 1);
  7709. return true;
  7710. }
  7711. }
  7712. return false;
  7713. };
  7714. Observable.prototype._deferUnregister = function (observer) {
  7715. var _this = this;
  7716. observer.unregisterOnNextCall = false;
  7717. observer._willBeUnregistered = true;
  7718. BABYLON.Tools.SetImmediate(function () {
  7719. _this.remove(observer);
  7720. });
  7721. };
  7722. /**
  7723. * Notify all Observers by calling their respective callback with the given data
  7724. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  7725. * @param eventData defines the data to send to all observers
  7726. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  7727. * @param target defines the original target of the state
  7728. * @param currentTarget defines the current target of the state
  7729. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  7730. */
  7731. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  7732. if (mask === void 0) { mask = -1; }
  7733. if (!this._observers.length) {
  7734. return true;
  7735. }
  7736. var state = this._eventState;
  7737. state.mask = mask;
  7738. state.target = target;
  7739. state.currentTarget = currentTarget;
  7740. state.skipNextObservers = false;
  7741. state.lastReturnValue = eventData;
  7742. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7743. var obs = _a[_i];
  7744. if (obs._willBeUnregistered) {
  7745. continue;
  7746. }
  7747. if (obs.mask & mask) {
  7748. if (obs.scope) {
  7749. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  7750. }
  7751. else {
  7752. state.lastReturnValue = obs.callback(eventData, state);
  7753. }
  7754. if (obs.unregisterOnNextCall) {
  7755. this._deferUnregister(obs);
  7756. }
  7757. }
  7758. if (state.skipNextObservers) {
  7759. return false;
  7760. }
  7761. }
  7762. return true;
  7763. };
  7764. /**
  7765. * Calling this will execute each callback, expecting it to be a promise or return a value.
  7766. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  7767. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  7768. * and it is crucial that all callbacks will be executed.
  7769. * The order of the callbacks is kept, callbacks are not executed parallel.
  7770. *
  7771. * @param eventData The data to be sent to each callback
  7772. * @param mask is used to filter observers defaults to -1
  7773. * @param target defines the callback target (see EventState)
  7774. * @param currentTarget defines he current object in the bubbling phase
  7775. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  7776. */
  7777. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  7778. var _this = this;
  7779. if (mask === void 0) { mask = -1; }
  7780. // create an empty promise
  7781. var p = Promise.resolve(eventData);
  7782. // no observers? return this promise.
  7783. if (!this._observers.length) {
  7784. return p;
  7785. }
  7786. var state = this._eventState;
  7787. state.mask = mask;
  7788. state.target = target;
  7789. state.currentTarget = currentTarget;
  7790. state.skipNextObservers = false;
  7791. // execute one callback after another (not using Promise.all, the order is important)
  7792. this._observers.forEach(function (obs) {
  7793. if (state.skipNextObservers) {
  7794. return;
  7795. }
  7796. if (obs._willBeUnregistered) {
  7797. return;
  7798. }
  7799. if (obs.mask & mask) {
  7800. if (obs.scope) {
  7801. p = p.then(function (lastReturnedValue) {
  7802. state.lastReturnValue = lastReturnedValue;
  7803. return obs.callback.apply(obs.scope, [eventData, state]);
  7804. });
  7805. }
  7806. else {
  7807. p = p.then(function (lastReturnedValue) {
  7808. state.lastReturnValue = lastReturnedValue;
  7809. return obs.callback(eventData, state);
  7810. });
  7811. }
  7812. if (obs.unregisterOnNextCall) {
  7813. _this._deferUnregister(obs);
  7814. }
  7815. }
  7816. });
  7817. // return the eventData
  7818. return p.then(function () { return eventData; });
  7819. };
  7820. /**
  7821. * Notify a specific observer
  7822. * @param observer defines the observer to notify
  7823. * @param eventData defines the data to be sent to each callback
  7824. * @param mask is used to filter observers defaults to -1
  7825. */
  7826. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  7827. if (mask === void 0) { mask = -1; }
  7828. var state = this._eventState;
  7829. state.mask = mask;
  7830. state.skipNextObservers = false;
  7831. observer.callback(eventData, state);
  7832. };
  7833. /**
  7834. * Gets a boolean indicating if the observable has at least one observer
  7835. * @returns true is the Observable has at least one Observer registered
  7836. */
  7837. Observable.prototype.hasObservers = function () {
  7838. return this._observers.length > 0;
  7839. };
  7840. /**
  7841. * Clear the list of observers
  7842. */
  7843. Observable.prototype.clear = function () {
  7844. this._observers = new Array();
  7845. this._onObserverAdded = null;
  7846. };
  7847. /**
  7848. * Clone the current observable
  7849. * @returns a new observable
  7850. */
  7851. Observable.prototype.clone = function () {
  7852. var result = new Observable();
  7853. result._observers = this._observers.slice(0);
  7854. return result;
  7855. };
  7856. /**
  7857. * Does this observable handles observer registered with a given mask
  7858. * @param mask defines the mask to be tested
  7859. * @return whether or not one observer registered with the given mask is handeled
  7860. **/
  7861. Observable.prototype.hasSpecificMask = function (mask) {
  7862. if (mask === void 0) { mask = -1; }
  7863. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7864. var obs = _a[_i];
  7865. if (obs.mask & mask || obs.mask === mask) {
  7866. return true;
  7867. }
  7868. }
  7869. return false;
  7870. };
  7871. return Observable;
  7872. }());
  7873. BABYLON.Observable = Observable;
  7874. })(BABYLON || (BABYLON = {}));
  7875. //# sourceMappingURL=babylon.observable.js.map
  7876. "use strict";
  7877. var BABYLON;
  7878. (function (BABYLON) {
  7879. var SmartArray = /** @class */ (function () {
  7880. function SmartArray(capacity) {
  7881. this.length = 0;
  7882. this.data = new Array(capacity);
  7883. this._id = SmartArray._GlobalId++;
  7884. }
  7885. SmartArray.prototype.push = function (value) {
  7886. this.data[this.length++] = value;
  7887. if (this.length > this.data.length) {
  7888. this.data.length *= 2;
  7889. }
  7890. };
  7891. SmartArray.prototype.forEach = function (func) {
  7892. for (var index = 0; index < this.length; index++) {
  7893. func(this.data[index]);
  7894. }
  7895. };
  7896. SmartArray.prototype.sort = function (compareFn) {
  7897. this.data.sort(compareFn);
  7898. };
  7899. SmartArray.prototype.reset = function () {
  7900. this.length = 0;
  7901. };
  7902. SmartArray.prototype.dispose = function () {
  7903. this.reset();
  7904. if (this.data) {
  7905. this.data.length = 0;
  7906. this.data = [];
  7907. }
  7908. };
  7909. SmartArray.prototype.concat = function (array) {
  7910. if (array.length === 0) {
  7911. return;
  7912. }
  7913. if (this.length + array.length > this.data.length) {
  7914. this.data.length = (this.length + array.length) * 2;
  7915. }
  7916. for (var index = 0; index < array.length; index++) {
  7917. this.data[this.length++] = (array.data || array)[index];
  7918. }
  7919. };
  7920. SmartArray.prototype.indexOf = function (value) {
  7921. var position = this.data.indexOf(value);
  7922. if (position >= this.length) {
  7923. return -1;
  7924. }
  7925. return position;
  7926. };
  7927. SmartArray.prototype.contains = function (value) {
  7928. return this.data.indexOf(value) !== -1;
  7929. };
  7930. // Statics
  7931. SmartArray._GlobalId = 0;
  7932. return SmartArray;
  7933. }());
  7934. BABYLON.SmartArray = SmartArray;
  7935. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  7936. __extends(SmartArrayNoDuplicate, _super);
  7937. function SmartArrayNoDuplicate() {
  7938. var _this = _super !== null && _super.apply(this, arguments) || this;
  7939. _this._duplicateId = 0;
  7940. return _this;
  7941. }
  7942. SmartArrayNoDuplicate.prototype.push = function (value) {
  7943. _super.prototype.push.call(this, value);
  7944. if (!value.__smartArrayFlags) {
  7945. value.__smartArrayFlags = {};
  7946. }
  7947. value.__smartArrayFlags[this._id] = this._duplicateId;
  7948. };
  7949. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  7950. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  7951. return false;
  7952. }
  7953. this.push(value);
  7954. return true;
  7955. };
  7956. SmartArrayNoDuplicate.prototype.reset = function () {
  7957. _super.prototype.reset.call(this);
  7958. this._duplicateId++;
  7959. };
  7960. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  7961. if (array.length === 0) {
  7962. return;
  7963. }
  7964. if (this.length + array.length > this.data.length) {
  7965. this.data.length = (this.length + array.length) * 2;
  7966. }
  7967. for (var index = 0; index < array.length; index++) {
  7968. var item = (array.data || array)[index];
  7969. this.pushNoDuplicate(item);
  7970. }
  7971. };
  7972. return SmartArrayNoDuplicate;
  7973. }(SmartArray));
  7974. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  7975. })(BABYLON || (BABYLON = {}));
  7976. //# sourceMappingURL=babylon.smartArray.js.map
  7977. "use strict";
  7978. var BABYLON;
  7979. (function (BABYLON) {
  7980. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  7981. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  7982. var LoadFileError = /** @class */ (function (_super) {
  7983. __extends(LoadFileError, _super);
  7984. function LoadFileError(message, request) {
  7985. var _this = _super.call(this, message) || this;
  7986. _this.request = request;
  7987. _this.name = "LoadFileError";
  7988. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  7989. return _this;
  7990. }
  7991. // Polyfill for Object.setPrototypeOf if necessary.
  7992. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  7993. return LoadFileError;
  7994. }(Error));
  7995. BABYLON.LoadFileError = LoadFileError;
  7996. var RetryStrategy = /** @class */ (function () {
  7997. function RetryStrategy() {
  7998. }
  7999. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8000. if (maxRetries === void 0) { maxRetries = 3; }
  8001. if (baseInterval === void 0) { baseInterval = 500; }
  8002. return function (url, request, retryIndex) {
  8003. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8004. return -1;
  8005. }
  8006. return Math.pow(2, retryIndex) * baseInterval;
  8007. };
  8008. };
  8009. return RetryStrategy;
  8010. }());
  8011. BABYLON.RetryStrategy = RetryStrategy;
  8012. // Screenshots
  8013. var screenshotCanvas;
  8014. var cloneValue = function (source, destinationObject) {
  8015. if (!source)
  8016. return null;
  8017. if (source instanceof BABYLON.Mesh) {
  8018. return null;
  8019. }
  8020. if (source instanceof BABYLON.SubMesh) {
  8021. return source.clone(destinationObject);
  8022. }
  8023. else if (source.clone) {
  8024. return source.clone();
  8025. }
  8026. return null;
  8027. };
  8028. var Tools = /** @class */ (function () {
  8029. function Tools() {
  8030. }
  8031. /**
  8032. * Interpolates between a and b via alpha
  8033. * @param a The lower value (returned when alpha = 0)
  8034. * @param b The upper value (returned when alpha = 1)
  8035. * @param alpha The interpolation-factor
  8036. * @return The mixed value
  8037. */
  8038. Tools.Mix = function (a, b, alpha) {
  8039. return a * (1 - alpha) + b * alpha;
  8040. };
  8041. Tools.Instantiate = function (className) {
  8042. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8043. return Tools.RegisteredExternalClasses[className];
  8044. }
  8045. var arr = className.split(".");
  8046. var fn = (window || this);
  8047. for (var i = 0, len = arr.length; i < len; i++) {
  8048. fn = fn[arr[i]];
  8049. }
  8050. if (typeof fn !== "function") {
  8051. return null;
  8052. }
  8053. return fn;
  8054. };
  8055. /**
  8056. * Provides a slice function that will work even on IE
  8057. * @param data defines the array to slice
  8058. * @returns the new sliced array
  8059. */
  8060. Tools.Slice = function (data) {
  8061. if (data.slice) {
  8062. return data.slice();
  8063. }
  8064. return Array.prototype.slice.call(data);
  8065. };
  8066. Tools.SetImmediate = function (action) {
  8067. if (window.setImmediate) {
  8068. window.setImmediate(action);
  8069. }
  8070. else {
  8071. setTimeout(action, 1);
  8072. }
  8073. };
  8074. Tools.IsExponentOfTwo = function (value) {
  8075. var count = 1;
  8076. do {
  8077. count *= 2;
  8078. } while (count < value);
  8079. return count === value;
  8080. };
  8081. /**
  8082. * Find the next highest power of two.
  8083. * @param x Number to start search from.
  8084. * @return Next highest power of two.
  8085. */
  8086. Tools.CeilingPOT = function (x) {
  8087. x--;
  8088. x |= x >> 1;
  8089. x |= x >> 2;
  8090. x |= x >> 4;
  8091. x |= x >> 8;
  8092. x |= x >> 16;
  8093. x++;
  8094. return x;
  8095. };
  8096. /**
  8097. * Find the next lowest power of two.
  8098. * @param x Number to start search from.
  8099. * @return Next lowest power of two.
  8100. */
  8101. Tools.FloorPOT = function (x) {
  8102. x = x | (x >> 1);
  8103. x = x | (x >> 2);
  8104. x = x | (x >> 4);
  8105. x = x | (x >> 8);
  8106. x = x | (x >> 16);
  8107. return x - (x >> 1);
  8108. };
  8109. /**
  8110. * Find the nearest power of two.
  8111. * @param x Number to start search from.
  8112. * @return Next nearest power of two.
  8113. */
  8114. Tools.NearestPOT = function (x) {
  8115. var c = Tools.CeilingPOT(x);
  8116. var f = Tools.FloorPOT(x);
  8117. return (c - x) > (x - f) ? f : c;
  8118. };
  8119. Tools.GetExponentOfTwo = function (value, max, mode) {
  8120. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8121. var pot;
  8122. switch (mode) {
  8123. case BABYLON.Engine.SCALEMODE_FLOOR:
  8124. pot = Tools.FloorPOT(value);
  8125. break;
  8126. case BABYLON.Engine.SCALEMODE_NEAREST:
  8127. pot = Tools.NearestPOT(value);
  8128. break;
  8129. case BABYLON.Engine.SCALEMODE_CEILING:
  8130. default:
  8131. pot = Tools.CeilingPOT(value);
  8132. break;
  8133. }
  8134. return Math.min(pot, max);
  8135. };
  8136. Tools.GetFilename = function (path) {
  8137. var index = path.lastIndexOf("/");
  8138. if (index < 0)
  8139. return path;
  8140. return path.substring(index + 1);
  8141. };
  8142. /**
  8143. * Extracts the "folder" part of a path (everything before the filename).
  8144. * @param uri The URI to extract the info from
  8145. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8146. * @returns The "folder" part of the path
  8147. */
  8148. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8149. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8150. var index = uri.lastIndexOf("/");
  8151. if (index < 0) {
  8152. if (returnUnchangedIfNoSlash) {
  8153. return uri;
  8154. }
  8155. return "";
  8156. }
  8157. return uri.substring(0, index + 1);
  8158. };
  8159. Tools.GetDOMTextContent = function (element) {
  8160. var result = "";
  8161. var child = element.firstChild;
  8162. while (child) {
  8163. if (child.nodeType === 3) {
  8164. result += child.textContent;
  8165. }
  8166. child = child.nextSibling;
  8167. }
  8168. return result;
  8169. };
  8170. Tools.ToDegrees = function (angle) {
  8171. return angle * 180 / Math.PI;
  8172. };
  8173. Tools.ToRadians = function (angle) {
  8174. return angle * Math.PI / 180;
  8175. };
  8176. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8177. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8178. var output = "";
  8179. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8180. var i = 0;
  8181. var bytes = new Uint8Array(buffer);
  8182. while (i < bytes.length) {
  8183. chr1 = bytes[i++];
  8184. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8185. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8186. enc1 = chr1 >> 2;
  8187. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8188. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8189. enc4 = chr3 & 63;
  8190. if (isNaN(chr2)) {
  8191. enc3 = enc4 = 64;
  8192. }
  8193. else if (isNaN(chr3)) {
  8194. enc4 = 64;
  8195. }
  8196. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8197. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8198. }
  8199. return "data:image/png;base64," + output;
  8200. };
  8201. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8202. if (bias === void 0) { bias = null; }
  8203. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8204. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8205. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8206. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8207. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8208. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8209. }
  8210. if (bias) {
  8211. minimum.x -= minimum.x * bias.x + bias.y;
  8212. minimum.y -= minimum.y * bias.x + bias.y;
  8213. minimum.z -= minimum.z * bias.x + bias.y;
  8214. maximum.x += maximum.x * bias.x + bias.y;
  8215. maximum.y += maximum.y * bias.x + bias.y;
  8216. maximum.z += maximum.z * bias.x + bias.y;
  8217. }
  8218. return {
  8219. minimum: minimum,
  8220. maximum: maximum
  8221. };
  8222. };
  8223. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8224. if (bias === void 0) { bias = null; }
  8225. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8226. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8227. if (!stride) {
  8228. stride = 3;
  8229. }
  8230. for (var index = start; index < start + count; index++) {
  8231. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8232. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8233. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8234. }
  8235. if (bias) {
  8236. minimum.x -= minimum.x * bias.x + bias.y;
  8237. minimum.y -= minimum.y * bias.x + bias.y;
  8238. minimum.z -= minimum.z * bias.x + bias.y;
  8239. maximum.x += maximum.x * bias.x + bias.y;
  8240. maximum.y += maximum.y * bias.x + bias.y;
  8241. maximum.z += maximum.z * bias.x + bias.y;
  8242. }
  8243. return {
  8244. minimum: minimum,
  8245. maximum: maximum
  8246. };
  8247. };
  8248. Tools.Vector2ArrayFeeder = function (array) {
  8249. return function (index) {
  8250. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8251. var length = isFloatArray ? array.length / 2 : array.length;
  8252. if (index >= length) {
  8253. return null;
  8254. }
  8255. if (isFloatArray) {
  8256. var fa = array;
  8257. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8258. }
  8259. var a = array;
  8260. return a[index];
  8261. };
  8262. };
  8263. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8264. if (bias === void 0) { bias = null; }
  8265. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8266. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8267. var i = 0;
  8268. var cur = feeder(i++);
  8269. while (cur) {
  8270. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8271. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8272. cur = feeder(i++);
  8273. }
  8274. if (bias) {
  8275. minimum.x -= minimum.x * bias.x + bias.y;
  8276. minimum.y -= minimum.y * bias.x + bias.y;
  8277. maximum.x += maximum.x * bias.x + bias.y;
  8278. maximum.y += maximum.y * bias.x + bias.y;
  8279. }
  8280. return {
  8281. minimum: minimum,
  8282. maximum: maximum
  8283. };
  8284. };
  8285. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8286. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8287. return null;
  8288. return Array.isArray(obj) ? obj : [obj];
  8289. };
  8290. // Misc.
  8291. Tools.GetPointerPrefix = function () {
  8292. var eventPrefix = "pointer";
  8293. // Check if pointer events are supported
  8294. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8295. eventPrefix = "mouse";
  8296. }
  8297. return eventPrefix;
  8298. };
  8299. /**
  8300. * @param func - the function to be called
  8301. * @param requester - the object that will request the next frame. Falls back to window.
  8302. */
  8303. Tools.QueueNewFrame = function (func, requester) {
  8304. if (!Tools.IsWindowObjectExist()) {
  8305. return setTimeout(func, 16);
  8306. }
  8307. if (!requester) {
  8308. requester = window;
  8309. }
  8310. if (requester.requestAnimationFrame) {
  8311. return requester.requestAnimationFrame(func);
  8312. }
  8313. else if (requester.msRequestAnimationFrame) {
  8314. return requester.msRequestAnimationFrame(func);
  8315. }
  8316. else if (requester.webkitRequestAnimationFrame) {
  8317. return requester.webkitRequestAnimationFrame(func);
  8318. }
  8319. else if (requester.mozRequestAnimationFrame) {
  8320. return requester.mozRequestAnimationFrame(func);
  8321. }
  8322. else if (requester.oRequestAnimationFrame) {
  8323. return requester.oRequestAnimationFrame(func);
  8324. }
  8325. else {
  8326. return window.setTimeout(func, 16);
  8327. }
  8328. };
  8329. Tools.RequestFullscreen = function (element) {
  8330. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8331. if (!requestFunction)
  8332. return;
  8333. requestFunction.call(element);
  8334. };
  8335. Tools.ExitFullscreen = function () {
  8336. if (document.exitFullscreen) {
  8337. document.exitFullscreen();
  8338. }
  8339. else if (document.mozCancelFullScreen) {
  8340. document.mozCancelFullScreen();
  8341. }
  8342. else if (document.webkitCancelFullScreen) {
  8343. document.webkitCancelFullScreen();
  8344. }
  8345. else if (document.msCancelFullScreen) {
  8346. document.msCancelFullScreen();
  8347. }
  8348. };
  8349. Tools.SetCorsBehavior = function (url, element) {
  8350. if (url && url.indexOf("data:") === 0) {
  8351. return;
  8352. }
  8353. if (Tools.CorsBehavior) {
  8354. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8355. element.crossOrigin = Tools.CorsBehavior;
  8356. }
  8357. else {
  8358. var result = Tools.CorsBehavior(url);
  8359. if (result) {
  8360. element.crossOrigin = result;
  8361. }
  8362. }
  8363. }
  8364. };
  8365. // External files
  8366. Tools.CleanUrl = function (url) {
  8367. url = url.replace(/#/mg, "%23");
  8368. return url;
  8369. };
  8370. Tools.LoadImage = function (url, onLoad, onError, database) {
  8371. if (url instanceof ArrayBuffer) {
  8372. url = Tools.EncodeArrayBufferTobase64(url);
  8373. }
  8374. url = Tools.CleanUrl(url);
  8375. url = Tools.PreprocessUrl(url);
  8376. var img = new Image();
  8377. Tools.SetCorsBehavior(url, img);
  8378. var loadHandler = function () {
  8379. img.removeEventListener("load", loadHandler);
  8380. img.removeEventListener("error", errorHandler);
  8381. onLoad(img);
  8382. };
  8383. var errorHandler = function (err) {
  8384. img.removeEventListener("load", loadHandler);
  8385. img.removeEventListener("error", errorHandler);
  8386. Tools.Error("Error while trying to load image: " + url);
  8387. if (onError) {
  8388. onError("Error while trying to load image: " + url, err);
  8389. }
  8390. };
  8391. img.addEventListener("load", loadHandler);
  8392. img.addEventListener("error", errorHandler);
  8393. var noIndexedDB = function () {
  8394. img.src = url;
  8395. };
  8396. var loadFromIndexedDB = function () {
  8397. if (database) {
  8398. database.loadImageFromDB(url, img);
  8399. }
  8400. };
  8401. //ANY database to do!
  8402. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8403. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8404. }
  8405. else {
  8406. if (url.indexOf("file:") !== -1) {
  8407. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8408. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8409. try {
  8410. var blobURL;
  8411. try {
  8412. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8413. }
  8414. catch (ex) {
  8415. // Chrome doesn't support oneTimeOnly parameter
  8416. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8417. }
  8418. img.src = blobURL;
  8419. }
  8420. catch (e) {
  8421. img.src = "";
  8422. }
  8423. return img;
  8424. }
  8425. }
  8426. noIndexedDB();
  8427. }
  8428. return img;
  8429. };
  8430. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  8431. url = Tools.CleanUrl(url);
  8432. url = Tools.PreprocessUrl(url);
  8433. // If file and file input are set
  8434. if (url.indexOf("file:") !== -1) {
  8435. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  8436. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  8437. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  8438. }
  8439. }
  8440. var loadUrl = Tools.BaseUrl + url;
  8441. var aborted = false;
  8442. var fileRequest = {
  8443. onCompleteObservable: new BABYLON.Observable(),
  8444. abort: function () { return aborted = true; },
  8445. };
  8446. var requestFile = function () {
  8447. var request = new XMLHttpRequest();
  8448. var retryHandle = null;
  8449. fileRequest.abort = function () {
  8450. aborted = true;
  8451. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  8452. request.abort();
  8453. }
  8454. if (retryHandle !== null) {
  8455. clearTimeout(retryHandle);
  8456. retryHandle = null;
  8457. }
  8458. };
  8459. var retryLoop = function (retryIndex) {
  8460. request.open('GET', loadUrl, true);
  8461. if (useArrayBuffer) {
  8462. request.responseType = "arraybuffer";
  8463. }
  8464. if (onProgress) {
  8465. request.addEventListener("progress", onProgress);
  8466. }
  8467. var onLoadEnd = function () {
  8468. request.removeEventListener("loadend", onLoadEnd);
  8469. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8470. fileRequest.onCompleteObservable.clear();
  8471. };
  8472. request.addEventListener("loadend", onLoadEnd);
  8473. var onReadyStateChange = function () {
  8474. if (aborted) {
  8475. return;
  8476. }
  8477. // In case of undefined state in some browsers.
  8478. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  8479. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  8480. request.removeEventListener("readystatechange", onReadyStateChange);
  8481. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  8482. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  8483. return;
  8484. }
  8485. var retryStrategy = Tools.DefaultRetryStrategy;
  8486. if (retryStrategy) {
  8487. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  8488. if (waitTime !== -1) {
  8489. // Prevent the request from completing for retry.
  8490. request.removeEventListener("loadend", onLoadEnd);
  8491. request = new XMLHttpRequest();
  8492. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  8493. return;
  8494. }
  8495. }
  8496. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  8497. if (onError) {
  8498. onError(request, e);
  8499. }
  8500. else {
  8501. throw e;
  8502. }
  8503. }
  8504. };
  8505. request.addEventListener("readystatechange", onReadyStateChange);
  8506. request.send();
  8507. };
  8508. retryLoop(0);
  8509. };
  8510. // Caching all files
  8511. if (database && database.enableSceneOffline) {
  8512. var noIndexedDB_1 = function () {
  8513. if (!aborted) {
  8514. requestFile();
  8515. }
  8516. };
  8517. var loadFromIndexedDB = function () {
  8518. // TODO: database needs to support aborting and should return a IFileRequest
  8519. if (aborted) {
  8520. return;
  8521. }
  8522. if (database) {
  8523. database.loadFileFromDB(url, function (data) {
  8524. if (!aborted) {
  8525. onSuccess(data);
  8526. }
  8527. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8528. }, onProgress ? function (event) {
  8529. if (!aborted) {
  8530. onProgress(event);
  8531. }
  8532. } : undefined, noIndexedDB_1, useArrayBuffer);
  8533. }
  8534. };
  8535. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  8536. }
  8537. else {
  8538. requestFile();
  8539. }
  8540. return fileRequest;
  8541. };
  8542. /**
  8543. * Load a script (identified by an url). When the url returns, the
  8544. * content of this file is added into a new script element, attached to the DOM (body element)
  8545. */
  8546. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  8547. var head = document.getElementsByTagName('head')[0];
  8548. var script = document.createElement('script');
  8549. script.type = 'text/javascript';
  8550. script.src = scriptUrl;
  8551. script.onload = function () {
  8552. if (onSuccess) {
  8553. onSuccess();
  8554. }
  8555. };
  8556. script.onerror = function (e) {
  8557. if (onError) {
  8558. onError("Unable to load script", e);
  8559. }
  8560. };
  8561. head.appendChild(script);
  8562. };
  8563. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  8564. var reader = new FileReader();
  8565. var request = {
  8566. onCompleteObservable: new BABYLON.Observable(),
  8567. abort: function () { return reader.abort(); },
  8568. };
  8569. reader.onloadend = function (e) {
  8570. request.onCompleteObservable.notifyObservers(request);
  8571. };
  8572. reader.onload = function (e) {
  8573. //target doesn't have result from ts 1.3
  8574. callback(e.target['result']);
  8575. };
  8576. reader.onprogress = progressCallback;
  8577. reader.readAsDataURL(fileToLoad);
  8578. return request;
  8579. };
  8580. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  8581. var reader = new FileReader();
  8582. var request = {
  8583. onCompleteObservable: new BABYLON.Observable(),
  8584. abort: function () { return reader.abort(); },
  8585. };
  8586. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  8587. reader.onerror = function (e) {
  8588. Tools.Log("Error while reading file: " + fileToLoad.name);
  8589. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  8590. };
  8591. reader.onload = function (e) {
  8592. //target doesn't have result from ts 1.3
  8593. callback(e.target['result']);
  8594. };
  8595. if (progressCallBack) {
  8596. reader.onprogress = progressCallBack;
  8597. }
  8598. if (!useArrayBuffer) {
  8599. // Asynchronous read
  8600. reader.readAsText(fileToLoad);
  8601. }
  8602. else {
  8603. reader.readAsArrayBuffer(fileToLoad);
  8604. }
  8605. return request;
  8606. };
  8607. //returns a downloadable url to a file content.
  8608. Tools.FileAsURL = function (content) {
  8609. var fileBlob = new Blob([content]);
  8610. var url = window.URL || window.webkitURL;
  8611. var link = url.createObjectURL(fileBlob);
  8612. return link;
  8613. };
  8614. // Misc.
  8615. Tools.Format = function (value, decimals) {
  8616. if (decimals === void 0) { decimals = 2; }
  8617. return value.toFixed(decimals);
  8618. };
  8619. Tools.CheckExtends = function (v, min, max) {
  8620. if (v.x < min.x)
  8621. min.x = v.x;
  8622. if (v.y < min.y)
  8623. min.y = v.y;
  8624. if (v.z < min.z)
  8625. min.z = v.z;
  8626. if (v.x > max.x)
  8627. max.x = v.x;
  8628. if (v.y > max.y)
  8629. max.y = v.y;
  8630. if (v.z > max.z)
  8631. max.z = v.z;
  8632. };
  8633. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  8634. for (var prop in source) {
  8635. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  8636. continue;
  8637. }
  8638. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  8639. continue;
  8640. }
  8641. var sourceValue = source[prop];
  8642. var typeOfSourceValue = typeof sourceValue;
  8643. if (typeOfSourceValue === "function") {
  8644. continue;
  8645. }
  8646. try {
  8647. if (typeOfSourceValue === "object") {
  8648. if (sourceValue instanceof Array) {
  8649. destination[prop] = [];
  8650. if (sourceValue.length > 0) {
  8651. if (typeof sourceValue[0] == "object") {
  8652. for (var index = 0; index < sourceValue.length; index++) {
  8653. var clonedValue = cloneValue(sourceValue[index], destination);
  8654. if (destination[prop].indexOf(clonedValue) === -1) {
  8655. destination[prop].push(clonedValue);
  8656. }
  8657. }
  8658. }
  8659. else {
  8660. destination[prop] = sourceValue.slice(0);
  8661. }
  8662. }
  8663. }
  8664. else {
  8665. destination[prop] = cloneValue(sourceValue, destination);
  8666. }
  8667. }
  8668. else {
  8669. destination[prop] = sourceValue;
  8670. }
  8671. }
  8672. catch (e) {
  8673. // Just ignore error (it could be because of a read-only property)
  8674. }
  8675. }
  8676. };
  8677. Tools.IsEmpty = function (obj) {
  8678. for (var i in obj) {
  8679. if (obj.hasOwnProperty(i)) {
  8680. return false;
  8681. }
  8682. }
  8683. return true;
  8684. };
  8685. Tools.RegisterTopRootEvents = function (events) {
  8686. for (var index = 0; index < events.length; index++) {
  8687. var event = events[index];
  8688. window.addEventListener(event.name, event.handler, false);
  8689. try {
  8690. if (window.parent) {
  8691. window.parent.addEventListener(event.name, event.handler, false);
  8692. }
  8693. }
  8694. catch (e) {
  8695. // Silently fails...
  8696. }
  8697. }
  8698. };
  8699. Tools.UnregisterTopRootEvents = function (events) {
  8700. for (var index = 0; index < events.length; index++) {
  8701. var event = events[index];
  8702. window.removeEventListener(event.name, event.handler);
  8703. try {
  8704. if (window.parent) {
  8705. window.parent.removeEventListener(event.name, event.handler);
  8706. }
  8707. }
  8708. catch (e) {
  8709. // Silently fails...
  8710. }
  8711. }
  8712. };
  8713. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  8714. if (mimeType === void 0) { mimeType = "image/png"; }
  8715. // Read the contents of the framebuffer
  8716. var numberOfChannelsByLine = width * 4;
  8717. var halfHeight = height / 2;
  8718. //Reading datas from WebGL
  8719. var data = engine.readPixels(0, 0, width, height);
  8720. //To flip image on Y axis.
  8721. for (var i = 0; i < halfHeight; i++) {
  8722. for (var j = 0; j < numberOfChannelsByLine; j++) {
  8723. var currentCell = j + i * numberOfChannelsByLine;
  8724. var targetLine = height - i - 1;
  8725. var targetCell = j + targetLine * numberOfChannelsByLine;
  8726. var temp = data[currentCell];
  8727. data[currentCell] = data[targetCell];
  8728. data[targetCell] = temp;
  8729. }
  8730. }
  8731. // Create a 2D canvas to store the result
  8732. if (!screenshotCanvas) {
  8733. screenshotCanvas = document.createElement('canvas');
  8734. }
  8735. screenshotCanvas.width = width;
  8736. screenshotCanvas.height = height;
  8737. var context = screenshotCanvas.getContext('2d');
  8738. if (context) {
  8739. // Copy the pixels to a 2D canvas
  8740. var imageData = context.createImageData(width, height);
  8741. var castData = (imageData.data);
  8742. castData.set(data);
  8743. context.putImageData(imageData, 0, 0);
  8744. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  8745. }
  8746. };
  8747. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  8748. if (mimeType === void 0) { mimeType = "image/png"; }
  8749. var base64Image = screenshotCanvas.toDataURL(mimeType);
  8750. if (successCallback) {
  8751. successCallback(base64Image);
  8752. }
  8753. else {
  8754. // We need HTMLCanvasElement.toBlob for HD screenshots
  8755. if (!screenshotCanvas.toBlob) {
  8756. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  8757. screenshotCanvas.toBlob = function (callback, type, quality) {
  8758. var _this = this;
  8759. setTimeout(function () {
  8760. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  8761. for (var i = 0; i < len; i++) {
  8762. arr[i] = binStr.charCodeAt(i);
  8763. }
  8764. callback(new Blob([arr], { type: type || 'image/png' }));
  8765. });
  8766. };
  8767. }
  8768. screenshotCanvas.toBlob(function (blob) {
  8769. var url = URL.createObjectURL(blob);
  8770. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  8771. if (("download" in document.createElement("a"))) {
  8772. var a = window.document.createElement("a");
  8773. a.href = url;
  8774. if (fileName) {
  8775. a.setAttribute("download", fileName);
  8776. }
  8777. else {
  8778. var date = new Date();
  8779. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  8780. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  8781. }
  8782. window.document.body.appendChild(a);
  8783. a.addEventListener("click", function () {
  8784. if (a.parentElement) {
  8785. a.parentElement.removeChild(a);
  8786. }
  8787. });
  8788. a.click();
  8789. }
  8790. else {
  8791. var newWindow = window.open("");
  8792. if (!newWindow)
  8793. return;
  8794. var img = newWindow.document.createElement("img");
  8795. img.onload = function () {
  8796. // no longer need to read the blob so it's revoked
  8797. URL.revokeObjectURL(url);
  8798. };
  8799. img.src = url;
  8800. newWindow.document.body.appendChild(img);
  8801. }
  8802. });
  8803. }
  8804. };
  8805. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  8806. if (mimeType === void 0) { mimeType = "image/png"; }
  8807. var width;
  8808. var height;
  8809. // If a precision value is specified
  8810. if (size.precision) {
  8811. width = Math.round(engine.getRenderWidth() * size.precision);
  8812. height = Math.round(width / engine.getAspectRatio(camera));
  8813. }
  8814. else if (size.width && size.height) {
  8815. width = size.width;
  8816. height = size.height;
  8817. }
  8818. else if (size.width && !size.height) {
  8819. width = size.width;
  8820. height = Math.round(width / engine.getAspectRatio(camera));
  8821. }
  8822. else if (size.height && !size.width) {
  8823. height = size.height;
  8824. width = Math.round(height * engine.getAspectRatio(camera));
  8825. }
  8826. else if (!isNaN(size)) {
  8827. height = size;
  8828. width = size;
  8829. }
  8830. else {
  8831. Tools.Error("Invalid 'size' parameter !");
  8832. return;
  8833. }
  8834. if (!screenshotCanvas) {
  8835. screenshotCanvas = document.createElement('canvas');
  8836. }
  8837. screenshotCanvas.width = width;
  8838. screenshotCanvas.height = height;
  8839. var renderContext = screenshotCanvas.getContext("2d");
  8840. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  8841. var newWidth = width;
  8842. var newHeight = newWidth / ratio;
  8843. if (newHeight > height) {
  8844. newHeight = height;
  8845. newWidth = newHeight * ratio;
  8846. }
  8847. var offsetX = Math.max(0, width - newWidth) / 2;
  8848. var offsetY = Math.max(0, height - newHeight) / 2;
  8849. var renderingCanvas = engine.getRenderingCanvas();
  8850. if (renderContext && renderingCanvas) {
  8851. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  8852. }
  8853. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  8854. };
  8855. /**
  8856. * Generates an image screenshot from the specified camera.
  8857. *
  8858. * @param engine The engine to use for rendering
  8859. * @param camera The camera to use for rendering
  8860. * @param size This parameter can be set to a single number or to an object with the
  8861. * following (optional) properties: precision, width, height. If a single number is passed,
  8862. * it will be used for both width and height. If an object is passed, the screenshot size
  8863. * will be derived from the parameters. The precision property is a multiplier allowing
  8864. * rendering at a higher or lower resolution.
  8865. * @param successCallback The callback receives a single parameter which contains the
  8866. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  8867. * src parameter of an <img> to display it.
  8868. * @param mimeType The MIME type of the screenshot image (default: image/png).
  8869. * Check your browser for supported MIME types.
  8870. * @param samples Texture samples (default: 1)
  8871. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  8872. * @param fileName A name for for the downloaded file.
  8873. * @constructor
  8874. */
  8875. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  8876. if (mimeType === void 0) { mimeType = "image/png"; }
  8877. if (samples === void 0) { samples = 1; }
  8878. if (antialiasing === void 0) { antialiasing = false; }
  8879. var width;
  8880. var height;
  8881. //If a precision value is specified
  8882. if (size.precision) {
  8883. width = Math.round(engine.getRenderWidth() * size.precision);
  8884. height = Math.round(width / engine.getAspectRatio(camera));
  8885. size = { width: width, height: height };
  8886. }
  8887. else if (size.width && size.height) {
  8888. width = size.width;
  8889. height = size.height;
  8890. }
  8891. else if (size.width && !size.height) {
  8892. width = size.width;
  8893. height = Math.round(width / engine.getAspectRatio(camera));
  8894. size = { width: width, height: height };
  8895. }
  8896. else if (size.height && !size.width) {
  8897. height = size.height;
  8898. width = Math.round(height * engine.getAspectRatio(camera));
  8899. size = { width: width, height: height };
  8900. }
  8901. else if (!isNaN(size)) {
  8902. height = size;
  8903. width = size;
  8904. }
  8905. else {
  8906. Tools.Error("Invalid 'size' parameter !");
  8907. return;
  8908. }
  8909. var scene = camera.getScene();
  8910. var previousCamera = null;
  8911. if (scene.activeCamera !== camera) {
  8912. previousCamera = scene.activeCamera;
  8913. scene.activeCamera = camera;
  8914. }
  8915. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  8916. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8917. texture.renderList = null;
  8918. texture.samples = samples;
  8919. if (antialiasing) {
  8920. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  8921. }
  8922. texture.onAfterRenderObservable.add(function () {
  8923. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  8924. });
  8925. scene.incrementRenderId();
  8926. scene.resetCachedMaterial();
  8927. texture.render(true);
  8928. texture.dispose();
  8929. if (previousCamera) {
  8930. scene.activeCamera = previousCamera;
  8931. }
  8932. camera.getProjectionMatrix(true); // Force cache refresh;
  8933. };
  8934. // XHR response validator for local file scenario
  8935. Tools.ValidateXHRData = function (xhr, dataType) {
  8936. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  8937. if (dataType === void 0) { dataType = 7; }
  8938. try {
  8939. if (dataType & 1) {
  8940. if (xhr.responseText && xhr.responseText.length > 0) {
  8941. return true;
  8942. }
  8943. else if (dataType === 1) {
  8944. return false;
  8945. }
  8946. }
  8947. if (dataType & 2) {
  8948. // Check header width and height since there is no "TGA" magic number
  8949. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  8950. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  8951. return true;
  8952. }
  8953. else if (dataType === 2) {
  8954. return false;
  8955. }
  8956. }
  8957. if (dataType & 4) {
  8958. // Check for the "DDS" magic number
  8959. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  8960. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  8961. return true;
  8962. }
  8963. else {
  8964. return false;
  8965. }
  8966. }
  8967. }
  8968. catch (e) {
  8969. // Global protection
  8970. }
  8971. return false;
  8972. };
  8973. /**
  8974. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  8975. * Be aware Math.random() could cause collisions, but:
  8976. * "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"
  8977. */
  8978. Tools.RandomId = function () {
  8979. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  8980. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  8981. return v.toString(16);
  8982. });
  8983. };
  8984. /**
  8985. * Test if the given uri is a base64 string.
  8986. * @param uri The uri to test
  8987. * @return True if the uri is a base64 string or false otherwise.
  8988. */
  8989. Tools.IsBase64 = function (uri) {
  8990. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  8991. };
  8992. /**
  8993. * Decode the given base64 uri.
  8994. * @param uri The uri to decode
  8995. * @return The decoded base64 data.
  8996. */
  8997. Tools.DecodeBase64 = function (uri) {
  8998. var decodedString = atob(uri.split(",")[1]);
  8999. var bufferLength = decodedString.length;
  9000. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9001. for (var i = 0; i < bufferLength; i++) {
  9002. bufferView[i] = decodedString.charCodeAt(i);
  9003. }
  9004. return bufferView.buffer;
  9005. };
  9006. Object.defineProperty(Tools, "NoneLogLevel", {
  9007. get: function () {
  9008. return Tools._NoneLogLevel;
  9009. },
  9010. enumerable: true,
  9011. configurable: true
  9012. });
  9013. Object.defineProperty(Tools, "MessageLogLevel", {
  9014. get: function () {
  9015. return Tools._MessageLogLevel;
  9016. },
  9017. enumerable: true,
  9018. configurable: true
  9019. });
  9020. Object.defineProperty(Tools, "WarningLogLevel", {
  9021. get: function () {
  9022. return Tools._WarningLogLevel;
  9023. },
  9024. enumerable: true,
  9025. configurable: true
  9026. });
  9027. Object.defineProperty(Tools, "ErrorLogLevel", {
  9028. get: function () {
  9029. return Tools._ErrorLogLevel;
  9030. },
  9031. enumerable: true,
  9032. configurable: true
  9033. });
  9034. Object.defineProperty(Tools, "AllLogLevel", {
  9035. get: function () {
  9036. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9037. },
  9038. enumerable: true,
  9039. configurable: true
  9040. });
  9041. Tools._AddLogEntry = function (entry) {
  9042. Tools._LogCache = entry + Tools._LogCache;
  9043. if (Tools.OnNewCacheEntry) {
  9044. Tools.OnNewCacheEntry(entry);
  9045. }
  9046. };
  9047. Tools._FormatMessage = function (message) {
  9048. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9049. var date = new Date();
  9050. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9051. };
  9052. Tools._LogDisabled = function (message) {
  9053. // nothing to do
  9054. };
  9055. Tools._LogEnabled = function (message) {
  9056. var formattedMessage = Tools._FormatMessage(message);
  9057. console.log("BJS - " + formattedMessage);
  9058. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9059. Tools._AddLogEntry(entry);
  9060. };
  9061. Tools._WarnDisabled = function (message) {
  9062. // nothing to do
  9063. };
  9064. Tools._WarnEnabled = function (message) {
  9065. var formattedMessage = Tools._FormatMessage(message);
  9066. console.warn("BJS - " + formattedMessage);
  9067. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9068. Tools._AddLogEntry(entry);
  9069. };
  9070. Tools._ErrorDisabled = function (message) {
  9071. // nothing to do
  9072. };
  9073. Tools._ErrorEnabled = function (message) {
  9074. Tools.errorsCount++;
  9075. var formattedMessage = Tools._FormatMessage(message);
  9076. console.error("BJS - " + formattedMessage);
  9077. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9078. Tools._AddLogEntry(entry);
  9079. };
  9080. Object.defineProperty(Tools, "LogCache", {
  9081. get: function () {
  9082. return Tools._LogCache;
  9083. },
  9084. enumerable: true,
  9085. configurable: true
  9086. });
  9087. Tools.ClearLogCache = function () {
  9088. Tools._LogCache = "";
  9089. Tools.errorsCount = 0;
  9090. };
  9091. Object.defineProperty(Tools, "LogLevels", {
  9092. set: function (level) {
  9093. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9094. Tools.Log = Tools._LogEnabled;
  9095. }
  9096. else {
  9097. Tools.Log = Tools._LogDisabled;
  9098. }
  9099. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9100. Tools.Warn = Tools._WarnEnabled;
  9101. }
  9102. else {
  9103. Tools.Warn = Tools._WarnDisabled;
  9104. }
  9105. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9106. Tools.Error = Tools._ErrorEnabled;
  9107. }
  9108. else {
  9109. Tools.Error = Tools._ErrorDisabled;
  9110. }
  9111. },
  9112. enumerable: true,
  9113. configurable: true
  9114. });
  9115. Tools.IsWindowObjectExist = function () {
  9116. return (typeof window) !== "undefined";
  9117. };
  9118. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9119. get: function () {
  9120. return Tools._PerformanceNoneLogLevel;
  9121. },
  9122. enumerable: true,
  9123. configurable: true
  9124. });
  9125. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9126. get: function () {
  9127. return Tools._PerformanceUserMarkLogLevel;
  9128. },
  9129. enumerable: true,
  9130. configurable: true
  9131. });
  9132. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9133. get: function () {
  9134. return Tools._PerformanceConsoleLogLevel;
  9135. },
  9136. enumerable: true,
  9137. configurable: true
  9138. });
  9139. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9140. set: function (level) {
  9141. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9142. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9143. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9144. return;
  9145. }
  9146. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9147. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9148. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9149. return;
  9150. }
  9151. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9152. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9153. },
  9154. enumerable: true,
  9155. configurable: true
  9156. });
  9157. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9158. };
  9159. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9160. };
  9161. Tools._StartUserMark = function (counterName, condition) {
  9162. if (condition === void 0) { condition = true; }
  9163. if (!Tools._performance) {
  9164. if (!Tools.IsWindowObjectExist()) {
  9165. return;
  9166. }
  9167. Tools._performance = window.performance;
  9168. }
  9169. if (!condition || !Tools._performance.mark) {
  9170. return;
  9171. }
  9172. Tools._performance.mark(counterName + "-Begin");
  9173. };
  9174. Tools._EndUserMark = function (counterName, condition) {
  9175. if (condition === void 0) { condition = true; }
  9176. if (!condition || !Tools._performance.mark) {
  9177. return;
  9178. }
  9179. Tools._performance.mark(counterName + "-End");
  9180. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9181. };
  9182. Tools._StartPerformanceConsole = function (counterName, condition) {
  9183. if (condition === void 0) { condition = true; }
  9184. if (!condition) {
  9185. return;
  9186. }
  9187. Tools._StartUserMark(counterName, condition);
  9188. if (console.time) {
  9189. console.time(counterName);
  9190. }
  9191. };
  9192. Tools._EndPerformanceConsole = function (counterName, condition) {
  9193. if (condition === void 0) { condition = true; }
  9194. if (!condition) {
  9195. return;
  9196. }
  9197. Tools._EndUserMark(counterName, condition);
  9198. if (console.time) {
  9199. console.timeEnd(counterName);
  9200. }
  9201. };
  9202. Object.defineProperty(Tools, "Now", {
  9203. get: function () {
  9204. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9205. return window.performance.now();
  9206. }
  9207. return new Date().getTime();
  9208. },
  9209. enumerable: true,
  9210. configurable: true
  9211. });
  9212. /**
  9213. * This method will return the name of the class used to create the instance of the given object.
  9214. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9215. * @param object the object to get the class name from
  9216. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9217. */
  9218. Tools.GetClassName = function (object, isType) {
  9219. if (isType === void 0) { isType = false; }
  9220. var name = null;
  9221. if (!isType && object.getClassName) {
  9222. name = object.getClassName();
  9223. }
  9224. else {
  9225. if (object instanceof Object) {
  9226. var classObj = isType ? object : Object.getPrototypeOf(object);
  9227. name = classObj.constructor["__bjsclassName__"];
  9228. }
  9229. if (!name) {
  9230. name = typeof object;
  9231. }
  9232. }
  9233. return name;
  9234. };
  9235. Tools.First = function (array, predicate) {
  9236. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9237. var el = array_1[_i];
  9238. if (predicate(el)) {
  9239. return el;
  9240. }
  9241. }
  9242. return null;
  9243. };
  9244. /**
  9245. * This method will return the name of the full name of the class, including its owning module (if any).
  9246. * 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).
  9247. * @param object the object to get the class name from
  9248. * @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.
  9249. */
  9250. Tools.getFullClassName = function (object, isType) {
  9251. if (isType === void 0) { isType = false; }
  9252. var className = null;
  9253. var moduleName = null;
  9254. if (!isType && object.getClassName) {
  9255. className = object.getClassName();
  9256. }
  9257. else {
  9258. if (object instanceof Object) {
  9259. var classObj = isType ? object : Object.getPrototypeOf(object);
  9260. className = classObj.constructor["__bjsclassName__"];
  9261. moduleName = classObj.constructor["__bjsmoduleName__"];
  9262. }
  9263. if (!className) {
  9264. className = typeof object;
  9265. }
  9266. }
  9267. if (!className) {
  9268. return null;
  9269. }
  9270. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9271. };
  9272. /**
  9273. * 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.
  9274. * @param array
  9275. */
  9276. Tools.arrayOrStringFeeder = function (array) {
  9277. return function (index) {
  9278. if (index >= array.length) {
  9279. return null;
  9280. }
  9281. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9282. if (val && val.getHashCode) {
  9283. val = val.getHashCode();
  9284. }
  9285. if (typeof val === "string") {
  9286. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9287. }
  9288. return val;
  9289. };
  9290. };
  9291. /**
  9292. * Compute the hashCode of a stream of number
  9293. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9294. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9295. * @return the hash code computed
  9296. */
  9297. Tools.hashCodeFromStream = function (feeder) {
  9298. // Based from here: http://stackoverflow.com/a/7616484/802124
  9299. var hash = 0;
  9300. var index = 0;
  9301. var chr = feeder(index++);
  9302. while (chr != null) {
  9303. hash = ((hash << 5) - hash) + chr;
  9304. hash |= 0; // Convert to 32bit integer
  9305. chr = feeder(index++);
  9306. }
  9307. return hash;
  9308. };
  9309. /**
  9310. * Returns a promise that resolves after the given amount of time.
  9311. * @param delay Number of milliseconds to delay
  9312. * @returns Promise that resolves after the given amount of time
  9313. */
  9314. Tools.DelayAsync = function (delay) {
  9315. return new Promise(function (resolve) {
  9316. setTimeout(function () {
  9317. resolve();
  9318. }, delay);
  9319. });
  9320. };
  9321. Tools.BaseUrl = "";
  9322. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9323. /**
  9324. * Default behaviour for cors in the application.
  9325. * It can be a string if the expected behavior is identical in the entire app.
  9326. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9327. */
  9328. Tools.CorsBehavior = "anonymous";
  9329. Tools.UseFallbackTexture = true;
  9330. /**
  9331. * Use this object to register external classes like custom textures or material
  9332. * to allow the laoders to instantiate them
  9333. */
  9334. Tools.RegisteredExternalClasses = {};
  9335. // Used in case of a texture loading problem
  9336. 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";
  9337. Tools.PreprocessUrl = function (url) {
  9338. return url;
  9339. };
  9340. // Logs
  9341. Tools._NoneLogLevel = 0;
  9342. Tools._MessageLogLevel = 1;
  9343. Tools._WarningLogLevel = 2;
  9344. Tools._ErrorLogLevel = 4;
  9345. Tools._LogCache = "";
  9346. Tools.errorsCount = 0;
  9347. Tools.Log = Tools._LogEnabled;
  9348. Tools.Warn = Tools._WarnEnabled;
  9349. Tools.Error = Tools._ErrorEnabled;
  9350. // Performances
  9351. Tools._PerformanceNoneLogLevel = 0;
  9352. Tools._PerformanceUserMarkLogLevel = 1;
  9353. Tools._PerformanceConsoleLogLevel = 2;
  9354. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9355. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9356. return Tools;
  9357. }());
  9358. BABYLON.Tools = Tools;
  9359. /**
  9360. * This class is used to track a performance counter which is number based.
  9361. * The user has access to many properties which give statistics of different nature
  9362. *
  9363. * The implementer can track two kinds of Performance Counter: time and count
  9364. * 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.
  9365. * 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.
  9366. */
  9367. var PerfCounter = /** @class */ (function () {
  9368. function PerfCounter() {
  9369. this._startMonitoringTime = 0;
  9370. this._min = 0;
  9371. this._max = 0;
  9372. this._average = 0;
  9373. this._lastSecAverage = 0;
  9374. this._current = 0;
  9375. this._totalValueCount = 0;
  9376. this._totalAccumulated = 0;
  9377. this._lastSecAccumulated = 0;
  9378. this._lastSecTime = 0;
  9379. this._lastSecValueCount = 0;
  9380. }
  9381. Object.defineProperty(PerfCounter.prototype, "min", {
  9382. /**
  9383. * Returns the smallest value ever
  9384. */
  9385. get: function () {
  9386. return this._min;
  9387. },
  9388. enumerable: true,
  9389. configurable: true
  9390. });
  9391. Object.defineProperty(PerfCounter.prototype, "max", {
  9392. /**
  9393. * Returns the biggest value ever
  9394. */
  9395. get: function () {
  9396. return this._max;
  9397. },
  9398. enumerable: true,
  9399. configurable: true
  9400. });
  9401. Object.defineProperty(PerfCounter.prototype, "average", {
  9402. /**
  9403. * Returns the average value since the performance counter is running
  9404. */
  9405. get: function () {
  9406. return this._average;
  9407. },
  9408. enumerable: true,
  9409. configurable: true
  9410. });
  9411. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  9412. /**
  9413. * Returns the average value of the last second the counter was monitored
  9414. */
  9415. get: function () {
  9416. return this._lastSecAverage;
  9417. },
  9418. enumerable: true,
  9419. configurable: true
  9420. });
  9421. Object.defineProperty(PerfCounter.prototype, "current", {
  9422. /**
  9423. * Returns the current value
  9424. */
  9425. get: function () {
  9426. return this._current;
  9427. },
  9428. enumerable: true,
  9429. configurable: true
  9430. });
  9431. Object.defineProperty(PerfCounter.prototype, "total", {
  9432. get: function () {
  9433. return this._totalAccumulated;
  9434. },
  9435. enumerable: true,
  9436. configurable: true
  9437. });
  9438. Object.defineProperty(PerfCounter.prototype, "count", {
  9439. get: function () {
  9440. return this._totalValueCount;
  9441. },
  9442. enumerable: true,
  9443. configurable: true
  9444. });
  9445. /**
  9446. * Call this method to start monitoring a new frame.
  9447. * 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.
  9448. */
  9449. PerfCounter.prototype.fetchNewFrame = function () {
  9450. this._totalValueCount++;
  9451. this._current = 0;
  9452. this._lastSecValueCount++;
  9453. };
  9454. /**
  9455. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  9456. * @param newCount the count value to add to the monitored count
  9457. * @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.
  9458. */
  9459. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  9460. if (!PerfCounter.Enabled) {
  9461. return;
  9462. }
  9463. this._current += newCount;
  9464. if (fetchResult) {
  9465. this._fetchResult();
  9466. }
  9467. };
  9468. /**
  9469. * Start monitoring this performance counter
  9470. */
  9471. PerfCounter.prototype.beginMonitoring = function () {
  9472. if (!PerfCounter.Enabled) {
  9473. return;
  9474. }
  9475. this._startMonitoringTime = Tools.Now;
  9476. };
  9477. /**
  9478. * Compute the time lapsed since the previous beginMonitoring() call.
  9479. * @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
  9480. */
  9481. PerfCounter.prototype.endMonitoring = function (newFrame) {
  9482. if (newFrame === void 0) { newFrame = true; }
  9483. if (!PerfCounter.Enabled) {
  9484. return;
  9485. }
  9486. if (newFrame) {
  9487. this.fetchNewFrame();
  9488. }
  9489. var currentTime = Tools.Now;
  9490. this._current = currentTime - this._startMonitoringTime;
  9491. if (newFrame) {
  9492. this._fetchResult();
  9493. }
  9494. };
  9495. PerfCounter.prototype._fetchResult = function () {
  9496. this._totalAccumulated += this._current;
  9497. this._lastSecAccumulated += this._current;
  9498. // Min/Max update
  9499. this._min = Math.min(this._min, this._current);
  9500. this._max = Math.max(this._max, this._current);
  9501. this._average = this._totalAccumulated / this._totalValueCount;
  9502. // Reset last sec?
  9503. var now = Tools.Now;
  9504. if ((now - this._lastSecTime) > 1000) {
  9505. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  9506. this._lastSecTime = now;
  9507. this._lastSecAccumulated = 0;
  9508. this._lastSecValueCount = 0;
  9509. }
  9510. };
  9511. PerfCounter.Enabled = true;
  9512. return PerfCounter;
  9513. }());
  9514. BABYLON.PerfCounter = PerfCounter;
  9515. /**
  9516. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  9517. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  9518. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  9519. * @param name The name of the class, case should be preserved
  9520. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  9521. */
  9522. function className(name, module) {
  9523. return function (target) {
  9524. target["__bjsclassName__"] = name;
  9525. target["__bjsmoduleName__"] = (module != null) ? module : null;
  9526. };
  9527. }
  9528. BABYLON.className = className;
  9529. /**
  9530. * An implementation of a loop for asynchronous functions.
  9531. */
  9532. var AsyncLoop = /** @class */ (function () {
  9533. /**
  9534. * Constroctor.
  9535. * @param iterations the number of iterations.
  9536. * @param _fn the function to run each iteration
  9537. * @param _successCallback the callback that will be called upon succesful execution
  9538. * @param offset starting offset.
  9539. */
  9540. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  9541. if (offset === void 0) { offset = 0; }
  9542. this.iterations = iterations;
  9543. this._fn = _fn;
  9544. this._successCallback = _successCallback;
  9545. this.index = offset - 1;
  9546. this._done = false;
  9547. }
  9548. /**
  9549. * Execute the next iteration. Must be called after the last iteration was finished.
  9550. */
  9551. AsyncLoop.prototype.executeNext = function () {
  9552. if (!this._done) {
  9553. if (this.index + 1 < this.iterations) {
  9554. ++this.index;
  9555. this._fn(this);
  9556. }
  9557. else {
  9558. this.breakLoop();
  9559. }
  9560. }
  9561. };
  9562. /**
  9563. * Break the loop and run the success callback.
  9564. */
  9565. AsyncLoop.prototype.breakLoop = function () {
  9566. this._done = true;
  9567. this._successCallback();
  9568. };
  9569. /**
  9570. * Helper function
  9571. */
  9572. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  9573. if (offset === void 0) { offset = 0; }
  9574. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  9575. loop.executeNext();
  9576. return loop;
  9577. };
  9578. /**
  9579. * A for-loop that will run a given number of iterations synchronous and the rest async.
  9580. * @param iterations total number of iterations
  9581. * @param syncedIterations number of synchronous iterations in each async iteration.
  9582. * @param fn the function to call each iteration.
  9583. * @param callback a success call back that will be called when iterating stops.
  9584. * @param breakFunction a break condition (optional)
  9585. * @param timeout timeout settings for the setTimeout function. default - 0.
  9586. * @constructor
  9587. */
  9588. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  9589. if (timeout === void 0) { timeout = 0; }
  9590. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  9591. if (breakFunction && breakFunction())
  9592. loop.breakLoop();
  9593. else {
  9594. setTimeout(function () {
  9595. for (var i = 0; i < syncedIterations; ++i) {
  9596. var iteration = (loop.index * syncedIterations) + i;
  9597. if (iteration >= iterations)
  9598. break;
  9599. fn(iteration);
  9600. if (breakFunction && breakFunction()) {
  9601. loop.breakLoop();
  9602. break;
  9603. }
  9604. }
  9605. loop.executeNext();
  9606. }, timeout);
  9607. }
  9608. }, callback);
  9609. };
  9610. return AsyncLoop;
  9611. }());
  9612. BABYLON.AsyncLoop = AsyncLoop;
  9613. })(BABYLON || (BABYLON = {}));
  9614. //# sourceMappingURL=babylon.tools.js.map
  9615. "use strict";
  9616. var BABYLON;
  9617. (function (BABYLON) {
  9618. var PromiseStates;
  9619. (function (PromiseStates) {
  9620. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  9621. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  9622. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  9623. })(PromiseStates || (PromiseStates = {}));
  9624. var FulFillmentAgregator = /** @class */ (function () {
  9625. function FulFillmentAgregator() {
  9626. this.count = 0;
  9627. this.target = 0;
  9628. this.results = [];
  9629. }
  9630. return FulFillmentAgregator;
  9631. }());
  9632. var InternalPromise = /** @class */ (function () {
  9633. function InternalPromise(resolver) {
  9634. var _this = this;
  9635. this._state = PromiseStates.Pending;
  9636. this._children = new Array();
  9637. this._rejectWasConsumed = false;
  9638. if (!resolver) {
  9639. return;
  9640. }
  9641. try {
  9642. resolver(function (value) {
  9643. _this._resolve(value);
  9644. }, function (reason) {
  9645. _this._reject(reason);
  9646. });
  9647. }
  9648. catch (e) {
  9649. this._reject(e);
  9650. }
  9651. }
  9652. InternalPromise.prototype.catch = function (onRejected) {
  9653. return this.then(undefined, onRejected);
  9654. };
  9655. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  9656. var _this = this;
  9657. var newPromise = new InternalPromise();
  9658. newPromise._onFulfilled = onFulfilled;
  9659. newPromise._onRejected = onRejected;
  9660. // Composition
  9661. this._children.push(newPromise);
  9662. if (this._state !== PromiseStates.Pending) {
  9663. BABYLON.Tools.SetImmediate(function () {
  9664. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  9665. var returnedValue = newPromise._resolve(_this._result);
  9666. if (returnedValue !== undefined && returnedValue !== null) {
  9667. if (returnedValue._state !== undefined) {
  9668. var returnedPromise = returnedValue;
  9669. newPromise._children.push(returnedPromise);
  9670. newPromise = returnedPromise;
  9671. }
  9672. else {
  9673. newPromise._result = returnedValue;
  9674. }
  9675. }
  9676. }
  9677. else {
  9678. newPromise._reject(_this._reason);
  9679. }
  9680. });
  9681. }
  9682. return newPromise;
  9683. };
  9684. InternalPromise.prototype._moveChildren = function (children) {
  9685. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  9686. if (this._state === PromiseStates.Fulfilled) {
  9687. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  9688. var child = _b[_i];
  9689. child._resolve(this._result);
  9690. }
  9691. }
  9692. else if (this._state === PromiseStates.Rejected) {
  9693. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  9694. var child = _d[_c];
  9695. child._reject(this._reason);
  9696. }
  9697. }
  9698. var _a;
  9699. };
  9700. InternalPromise.prototype._resolve = function (value) {
  9701. try {
  9702. this._state = PromiseStates.Fulfilled;
  9703. var returnedValue = null;
  9704. if (this._onFulfilled) {
  9705. returnedValue = this._onFulfilled(value);
  9706. }
  9707. if (returnedValue !== undefined && returnedValue !== null) {
  9708. if (returnedValue._state !== undefined) {
  9709. // Transmit children
  9710. var returnedPromise = returnedValue;
  9711. returnedPromise._moveChildren(this._children);
  9712. value = returnedPromise._result;
  9713. }
  9714. else {
  9715. value = returnedValue;
  9716. }
  9717. }
  9718. this._result = value;
  9719. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9720. var child = _a[_i];
  9721. child._resolve(value);
  9722. }
  9723. this._children.length = 0;
  9724. delete this._onFulfilled;
  9725. delete this._onRejected;
  9726. }
  9727. catch (e) {
  9728. this._reject(e, true);
  9729. }
  9730. };
  9731. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  9732. if (onLocalThrow === void 0) { onLocalThrow = false; }
  9733. this._state = PromiseStates.Rejected;
  9734. this._reason = reason;
  9735. if (this._onRejected && !onLocalThrow) {
  9736. try {
  9737. this._onRejected(reason);
  9738. this._rejectWasConsumed = true;
  9739. }
  9740. catch (e) {
  9741. reason = e;
  9742. }
  9743. }
  9744. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9745. var child = _a[_i];
  9746. if (this._rejectWasConsumed) {
  9747. child._resolve(null);
  9748. }
  9749. else {
  9750. child._reject(reason);
  9751. }
  9752. }
  9753. this._children.length = 0;
  9754. delete this._onFulfilled;
  9755. delete this._onRejected;
  9756. };
  9757. InternalPromise.resolve = function (value) {
  9758. var newPromise = new InternalPromise();
  9759. newPromise._resolve(value);
  9760. return newPromise;
  9761. };
  9762. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  9763. promise.then(function (value) {
  9764. agregator.results[index] = value;
  9765. agregator.count++;
  9766. if (agregator.count === agregator.target) {
  9767. agregator.rootPromise._resolve(agregator.results);
  9768. }
  9769. return null;
  9770. }, function (reason) {
  9771. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  9772. agregator.rootPromise._reject(reason);
  9773. }
  9774. });
  9775. };
  9776. InternalPromise.all = function (promises) {
  9777. var newPromise = new InternalPromise();
  9778. var agregator = new FulFillmentAgregator();
  9779. agregator.target = promises.length;
  9780. agregator.rootPromise = newPromise;
  9781. if (promises.length) {
  9782. for (var index = 0; index < promises.length; index++) {
  9783. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  9784. }
  9785. }
  9786. else {
  9787. newPromise._resolve([]);
  9788. }
  9789. return newPromise;
  9790. };
  9791. InternalPromise.race = function (promises) {
  9792. var newPromise = new InternalPromise();
  9793. if (promises.length) {
  9794. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  9795. var promise = promises_1[_i];
  9796. promise.then(function (value) {
  9797. if (newPromise) {
  9798. newPromise._resolve(value);
  9799. newPromise = null;
  9800. }
  9801. return null;
  9802. }, function (reason) {
  9803. if (newPromise) {
  9804. newPromise._reject(reason);
  9805. newPromise = null;
  9806. }
  9807. });
  9808. }
  9809. }
  9810. return newPromise;
  9811. };
  9812. return InternalPromise;
  9813. }());
  9814. /**
  9815. * Helper class that provides a small promise polyfill
  9816. */
  9817. var PromisePolyfill = /** @class */ (function () {
  9818. function PromisePolyfill() {
  9819. }
  9820. /**
  9821. * Static function used to check if the polyfill is required
  9822. * If this is the case then the function will inject the polyfill to window.Promise
  9823. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  9824. */
  9825. PromisePolyfill.Apply = function (force) {
  9826. if (force === void 0) { force = false; }
  9827. if (force || typeof Promise === 'undefined') {
  9828. var root = window;
  9829. root.Promise = InternalPromise;
  9830. }
  9831. };
  9832. return PromisePolyfill;
  9833. }());
  9834. BABYLON.PromisePolyfill = PromisePolyfill;
  9835. })(BABYLON || (BABYLON = {}));
  9836. //# sourceMappingURL=babylon.promise.js.map
  9837. "use strict";
  9838. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  9839. var BABYLON;
  9840. (function (BABYLON) {
  9841. /**
  9842. * Helper class to push actions to a pool of workers.
  9843. */
  9844. var WorkerPool = /** @class */ (function () {
  9845. /**
  9846. * Constructor
  9847. * @param workers Array of workers to use for actions
  9848. */
  9849. function WorkerPool(workers) {
  9850. this._pendingActions = new Array();
  9851. this._workerInfos = workers.map(function (worker) { return ({
  9852. worker: worker,
  9853. active: false
  9854. }); });
  9855. }
  9856. /**
  9857. * Terminates all workers and clears any pending actions.
  9858. */
  9859. WorkerPool.prototype.dispose = function () {
  9860. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  9861. var workerInfo = _a[_i];
  9862. workerInfo.worker.terminate();
  9863. }
  9864. delete this._workerInfos;
  9865. delete this._pendingActions;
  9866. };
  9867. /**
  9868. * Pushes an action to the worker pool. If all the workers are active, the action will be
  9869. * pended until a worker has completed its action.
  9870. * @param action The action to perform. Call onComplete when the action is complete.
  9871. */
  9872. WorkerPool.prototype.push = function (action) {
  9873. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  9874. var workerInfo = _a[_i];
  9875. if (!workerInfo.active) {
  9876. this._execute(workerInfo, action);
  9877. return;
  9878. }
  9879. }
  9880. this._pendingActions.push(action);
  9881. };
  9882. WorkerPool.prototype._execute = function (workerInfo, action) {
  9883. var _this = this;
  9884. workerInfo.active = true;
  9885. action(workerInfo.worker, function () {
  9886. workerInfo.active = false;
  9887. var nextAction = _this._pendingActions.shift();
  9888. if (nextAction) {
  9889. _this._execute(workerInfo, nextAction);
  9890. }
  9891. });
  9892. };
  9893. return WorkerPool;
  9894. }());
  9895. BABYLON.WorkerPool = WorkerPool;
  9896. })(BABYLON || (BABYLON = {}));
  9897. //# sourceMappingURL=babylon.workerPool.js.map
  9898. "use strict";
  9899. var BABYLON;
  9900. (function (BABYLON) {
  9901. var _AlphaState = /** @class */ (function () {
  9902. /**
  9903. * Initializes the state.
  9904. */
  9905. function _AlphaState() {
  9906. this._isAlphaBlendDirty = false;
  9907. this._isBlendFunctionParametersDirty = false;
  9908. this._isBlendEquationParametersDirty = false;
  9909. this._isBlendConstantsDirty = false;
  9910. this._alphaBlend = false;
  9911. this._blendFunctionParameters = new Array(4);
  9912. this._blendEquationParameters = new Array(2);
  9913. this._blendConstants = new Array(4);
  9914. this.reset();
  9915. }
  9916. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  9917. get: function () {
  9918. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  9919. },
  9920. enumerable: true,
  9921. configurable: true
  9922. });
  9923. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  9924. get: function () {
  9925. return this._alphaBlend;
  9926. },
  9927. set: function (value) {
  9928. if (this._alphaBlend === value) {
  9929. return;
  9930. }
  9931. this._alphaBlend = value;
  9932. this._isAlphaBlendDirty = true;
  9933. },
  9934. enumerable: true,
  9935. configurable: true
  9936. });
  9937. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  9938. if (this._blendConstants[0] === r &&
  9939. this._blendConstants[1] === g &&
  9940. this._blendConstants[2] === b &&
  9941. this._blendConstants[3] === a) {
  9942. return;
  9943. }
  9944. this._blendConstants[0] = r;
  9945. this._blendConstants[1] = g;
  9946. this._blendConstants[2] = b;
  9947. this._blendConstants[3] = a;
  9948. this._isBlendConstantsDirty = true;
  9949. };
  9950. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  9951. if (this._blendFunctionParameters[0] === value0 &&
  9952. this._blendFunctionParameters[1] === value1 &&
  9953. this._blendFunctionParameters[2] === value2 &&
  9954. this._blendFunctionParameters[3] === value3) {
  9955. return;
  9956. }
  9957. this._blendFunctionParameters[0] = value0;
  9958. this._blendFunctionParameters[1] = value1;
  9959. this._blendFunctionParameters[2] = value2;
  9960. this._blendFunctionParameters[3] = value3;
  9961. this._isBlendFunctionParametersDirty = true;
  9962. };
  9963. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  9964. if (this._blendEquationParameters[0] === rgb &&
  9965. this._blendEquationParameters[1] === alpha) {
  9966. return;
  9967. }
  9968. this._blendEquationParameters[0] = rgb;
  9969. this._blendEquationParameters[1] = alpha;
  9970. this._isBlendEquationParametersDirty = true;
  9971. };
  9972. _AlphaState.prototype.reset = function () {
  9973. this._alphaBlend = false;
  9974. this._blendFunctionParameters[0] = null;
  9975. this._blendFunctionParameters[1] = null;
  9976. this._blendFunctionParameters[2] = null;
  9977. this._blendFunctionParameters[3] = null;
  9978. this._blendEquationParameters[0] = null;
  9979. this._blendEquationParameters[1] = null;
  9980. this._blendConstants[0] = null;
  9981. this._blendConstants[1] = null;
  9982. this._blendConstants[2] = null;
  9983. this._blendConstants[3] = null;
  9984. this._isAlphaBlendDirty = true;
  9985. this._isBlendFunctionParametersDirty = false;
  9986. this._isBlendEquationParametersDirty = false;
  9987. this._isBlendConstantsDirty = false;
  9988. };
  9989. _AlphaState.prototype.apply = function (gl) {
  9990. if (!this.isDirty) {
  9991. return;
  9992. }
  9993. // Alpha blend
  9994. if (this._isAlphaBlendDirty) {
  9995. if (this._alphaBlend) {
  9996. gl.enable(gl.BLEND);
  9997. }
  9998. else {
  9999. gl.disable(gl.BLEND);
  10000. }
  10001. this._isAlphaBlendDirty = false;
  10002. }
  10003. // Alpha function
  10004. if (this._isBlendFunctionParametersDirty) {
  10005. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  10006. this._isBlendFunctionParametersDirty = false;
  10007. }
  10008. // Alpha equation
  10009. if (this._isBlendEquationParametersDirty) {
  10010. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  10011. this._isBlendEquationParametersDirty = false;
  10012. }
  10013. // Constants
  10014. if (this._isBlendConstantsDirty) {
  10015. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10016. this._isBlendConstantsDirty = false;
  10017. }
  10018. };
  10019. return _AlphaState;
  10020. }());
  10021. BABYLON._AlphaState = _AlphaState;
  10022. })(BABYLON || (BABYLON = {}));
  10023. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10024. "use strict";
  10025. var BABYLON;
  10026. (function (BABYLON) {
  10027. var _DepthCullingState = /** @class */ (function () {
  10028. /**
  10029. * Initializes the state.
  10030. */
  10031. function _DepthCullingState() {
  10032. this._isDepthTestDirty = false;
  10033. this._isDepthMaskDirty = false;
  10034. this._isDepthFuncDirty = false;
  10035. this._isCullFaceDirty = false;
  10036. this._isCullDirty = false;
  10037. this._isZOffsetDirty = false;
  10038. this._isFrontFaceDirty = false;
  10039. this.reset();
  10040. }
  10041. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10042. get: function () {
  10043. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10044. },
  10045. enumerable: true,
  10046. configurable: true
  10047. });
  10048. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10049. get: function () {
  10050. return this._zOffset;
  10051. },
  10052. set: function (value) {
  10053. if (this._zOffset === value) {
  10054. return;
  10055. }
  10056. this._zOffset = value;
  10057. this._isZOffsetDirty = true;
  10058. },
  10059. enumerable: true,
  10060. configurable: true
  10061. });
  10062. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10063. get: function () {
  10064. return this._cullFace;
  10065. },
  10066. set: function (value) {
  10067. if (this._cullFace === value) {
  10068. return;
  10069. }
  10070. this._cullFace = value;
  10071. this._isCullFaceDirty = true;
  10072. },
  10073. enumerable: true,
  10074. configurable: true
  10075. });
  10076. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10077. get: function () {
  10078. return this._cull;
  10079. },
  10080. set: function (value) {
  10081. if (this._cull === value) {
  10082. return;
  10083. }
  10084. this._cull = value;
  10085. this._isCullDirty = true;
  10086. },
  10087. enumerable: true,
  10088. configurable: true
  10089. });
  10090. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10091. get: function () {
  10092. return this._depthFunc;
  10093. },
  10094. set: function (value) {
  10095. if (this._depthFunc === value) {
  10096. return;
  10097. }
  10098. this._depthFunc = value;
  10099. this._isDepthFuncDirty = true;
  10100. },
  10101. enumerable: true,
  10102. configurable: true
  10103. });
  10104. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10105. get: function () {
  10106. return this._depthMask;
  10107. },
  10108. set: function (value) {
  10109. if (this._depthMask === value) {
  10110. return;
  10111. }
  10112. this._depthMask = value;
  10113. this._isDepthMaskDirty = true;
  10114. },
  10115. enumerable: true,
  10116. configurable: true
  10117. });
  10118. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10119. get: function () {
  10120. return this._depthTest;
  10121. },
  10122. set: function (value) {
  10123. if (this._depthTest === value) {
  10124. return;
  10125. }
  10126. this._depthTest = value;
  10127. this._isDepthTestDirty = true;
  10128. },
  10129. enumerable: true,
  10130. configurable: true
  10131. });
  10132. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10133. get: function () {
  10134. return this._frontFace;
  10135. },
  10136. set: function (value) {
  10137. if (this._frontFace === value) {
  10138. return;
  10139. }
  10140. this._frontFace = value;
  10141. this._isFrontFaceDirty = true;
  10142. },
  10143. enumerable: true,
  10144. configurable: true
  10145. });
  10146. _DepthCullingState.prototype.reset = function () {
  10147. this._depthMask = true;
  10148. this._depthTest = true;
  10149. this._depthFunc = null;
  10150. this._cullFace = null;
  10151. this._cull = null;
  10152. this._zOffset = 0;
  10153. this._frontFace = null;
  10154. this._isDepthTestDirty = true;
  10155. this._isDepthMaskDirty = true;
  10156. this._isDepthFuncDirty = false;
  10157. this._isCullFaceDirty = false;
  10158. this._isCullDirty = false;
  10159. this._isZOffsetDirty = false;
  10160. this._isFrontFaceDirty = false;
  10161. };
  10162. _DepthCullingState.prototype.apply = function (gl) {
  10163. if (!this.isDirty) {
  10164. return;
  10165. }
  10166. // Cull
  10167. if (this._isCullDirty) {
  10168. if (this.cull) {
  10169. gl.enable(gl.CULL_FACE);
  10170. }
  10171. else {
  10172. gl.disable(gl.CULL_FACE);
  10173. }
  10174. this._isCullDirty = false;
  10175. }
  10176. // Cull face
  10177. if (this._isCullFaceDirty) {
  10178. gl.cullFace(this.cullFace);
  10179. this._isCullFaceDirty = false;
  10180. }
  10181. // Depth mask
  10182. if (this._isDepthMaskDirty) {
  10183. gl.depthMask(this.depthMask);
  10184. this._isDepthMaskDirty = false;
  10185. }
  10186. // Depth test
  10187. if (this._isDepthTestDirty) {
  10188. if (this.depthTest) {
  10189. gl.enable(gl.DEPTH_TEST);
  10190. }
  10191. else {
  10192. gl.disable(gl.DEPTH_TEST);
  10193. }
  10194. this._isDepthTestDirty = false;
  10195. }
  10196. // Depth func
  10197. if (this._isDepthFuncDirty) {
  10198. gl.depthFunc(this.depthFunc);
  10199. this._isDepthFuncDirty = false;
  10200. }
  10201. // zOffset
  10202. if (this._isZOffsetDirty) {
  10203. if (this.zOffset) {
  10204. gl.enable(gl.POLYGON_OFFSET_FILL);
  10205. gl.polygonOffset(this.zOffset, 0);
  10206. }
  10207. else {
  10208. gl.disable(gl.POLYGON_OFFSET_FILL);
  10209. }
  10210. this._isZOffsetDirty = false;
  10211. }
  10212. // Front face
  10213. if (this._isFrontFaceDirty) {
  10214. gl.frontFace(this.frontFace);
  10215. this._isFrontFaceDirty = false;
  10216. }
  10217. };
  10218. return _DepthCullingState;
  10219. }());
  10220. BABYLON._DepthCullingState = _DepthCullingState;
  10221. })(BABYLON || (BABYLON = {}));
  10222. //# sourceMappingURL=babylon.depthCullingState.js.map
  10223. "use strict";
  10224. var BABYLON;
  10225. (function (BABYLON) {
  10226. var _StencilState = /** @class */ (function () {
  10227. function _StencilState() {
  10228. this._isStencilTestDirty = false;
  10229. this._isStencilMaskDirty = false;
  10230. this._isStencilFuncDirty = false;
  10231. this._isStencilOpDirty = false;
  10232. this.reset();
  10233. }
  10234. Object.defineProperty(_StencilState.prototype, "isDirty", {
  10235. get: function () {
  10236. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  10237. },
  10238. enumerable: true,
  10239. configurable: true
  10240. });
  10241. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  10242. get: function () {
  10243. return this._stencilFunc;
  10244. },
  10245. set: function (value) {
  10246. if (this._stencilFunc === value) {
  10247. return;
  10248. }
  10249. this._stencilFunc = value;
  10250. this._isStencilFuncDirty = true;
  10251. },
  10252. enumerable: true,
  10253. configurable: true
  10254. });
  10255. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  10256. get: function () {
  10257. return this._stencilFuncRef;
  10258. },
  10259. set: function (value) {
  10260. if (this._stencilFuncRef === value) {
  10261. return;
  10262. }
  10263. this._stencilFuncRef = value;
  10264. this._isStencilFuncDirty = true;
  10265. },
  10266. enumerable: true,
  10267. configurable: true
  10268. });
  10269. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  10270. get: function () {
  10271. return this._stencilFuncMask;
  10272. },
  10273. set: function (value) {
  10274. if (this._stencilFuncMask === value) {
  10275. return;
  10276. }
  10277. this._stencilFuncMask = value;
  10278. this._isStencilFuncDirty = true;
  10279. },
  10280. enumerable: true,
  10281. configurable: true
  10282. });
  10283. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10284. get: function () {
  10285. return this._stencilOpStencilFail;
  10286. },
  10287. set: function (value) {
  10288. if (this._stencilOpStencilFail === value) {
  10289. return;
  10290. }
  10291. this._stencilOpStencilFail = value;
  10292. this._isStencilOpDirty = true;
  10293. },
  10294. enumerable: true,
  10295. configurable: true
  10296. });
  10297. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  10298. get: function () {
  10299. return this._stencilOpDepthFail;
  10300. },
  10301. set: function (value) {
  10302. if (this._stencilOpDepthFail === value) {
  10303. return;
  10304. }
  10305. this._stencilOpDepthFail = value;
  10306. this._isStencilOpDirty = true;
  10307. },
  10308. enumerable: true,
  10309. configurable: true
  10310. });
  10311. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  10312. get: function () {
  10313. return this._stencilOpStencilDepthPass;
  10314. },
  10315. set: function (value) {
  10316. if (this._stencilOpStencilDepthPass === value) {
  10317. return;
  10318. }
  10319. this._stencilOpStencilDepthPass = value;
  10320. this._isStencilOpDirty = true;
  10321. },
  10322. enumerable: true,
  10323. configurable: true
  10324. });
  10325. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  10326. get: function () {
  10327. return this._stencilMask;
  10328. },
  10329. set: function (value) {
  10330. if (this._stencilMask === value) {
  10331. return;
  10332. }
  10333. this._stencilMask = value;
  10334. this._isStencilMaskDirty = true;
  10335. },
  10336. enumerable: true,
  10337. configurable: true
  10338. });
  10339. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  10340. get: function () {
  10341. return this._stencilTest;
  10342. },
  10343. set: function (value) {
  10344. if (this._stencilTest === value) {
  10345. return;
  10346. }
  10347. this._stencilTest = value;
  10348. this._isStencilTestDirty = true;
  10349. },
  10350. enumerable: true,
  10351. configurable: true
  10352. });
  10353. _StencilState.prototype.reset = function () {
  10354. this._stencilTest = false;
  10355. this._stencilMask = 0xFF;
  10356. this._stencilFunc = BABYLON.Engine.ALWAYS;
  10357. this._stencilFuncRef = 1;
  10358. this._stencilFuncMask = 0xFF;
  10359. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  10360. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  10361. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  10362. this._isStencilTestDirty = true;
  10363. this._isStencilMaskDirty = true;
  10364. this._isStencilFuncDirty = true;
  10365. this._isStencilOpDirty = true;
  10366. };
  10367. _StencilState.prototype.apply = function (gl) {
  10368. if (!this.isDirty) {
  10369. return;
  10370. }
  10371. // Stencil test
  10372. if (this._isStencilTestDirty) {
  10373. if (this.stencilTest) {
  10374. gl.enable(gl.STENCIL_TEST);
  10375. }
  10376. else {
  10377. gl.disable(gl.STENCIL_TEST);
  10378. }
  10379. this._isStencilTestDirty = false;
  10380. }
  10381. // Stencil mask
  10382. if (this._isStencilMaskDirty) {
  10383. gl.stencilMask(this.stencilMask);
  10384. this._isStencilMaskDirty = false;
  10385. }
  10386. // Stencil func
  10387. if (this._isStencilFuncDirty) {
  10388. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  10389. this._isStencilFuncDirty = false;
  10390. }
  10391. // Stencil op
  10392. if (this._isStencilOpDirty) {
  10393. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  10394. this._isStencilOpDirty = false;
  10395. }
  10396. };
  10397. return _StencilState;
  10398. }());
  10399. BABYLON._StencilState = _StencilState;
  10400. })(BABYLON || (BABYLON = {}));
  10401. //# sourceMappingURL=babylon.stencilState.js.map
  10402. "use strict";
  10403. var __assign = (this && this.__assign) || Object.assign || function(t) {
  10404. for (var s, i = 1, n = arguments.length; i < n; i++) {
  10405. s = arguments[i];
  10406. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  10407. t[p] = s[p];
  10408. }
  10409. return t;
  10410. };
  10411. var BABYLON;
  10412. (function (BABYLON) {
  10413. var compileShader = function (gl, source, type, defines, shaderVersion) {
  10414. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  10415. };
  10416. var compileRawShader = function (gl, source, type) {
  10417. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  10418. gl.shaderSource(shader, source);
  10419. gl.compileShader(shader);
  10420. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  10421. var log = gl.getShaderInfoLog(shader);
  10422. if (log) {
  10423. throw new Error(log);
  10424. }
  10425. }
  10426. if (!shader) {
  10427. throw new Error("Something went wrong while compile the shader.");
  10428. }
  10429. return shader;
  10430. };
  10431. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  10432. var magFilter = gl.NEAREST;
  10433. var minFilter = gl.NEAREST;
  10434. switch (samplingMode) {
  10435. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  10436. magFilter = gl.LINEAR;
  10437. if (generateMipMaps) {
  10438. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10439. }
  10440. else {
  10441. minFilter = gl.LINEAR;
  10442. }
  10443. break;
  10444. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  10445. magFilter = gl.LINEAR;
  10446. if (generateMipMaps) {
  10447. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10448. }
  10449. else {
  10450. minFilter = gl.LINEAR;
  10451. }
  10452. break;
  10453. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  10454. magFilter = gl.NEAREST;
  10455. if (generateMipMaps) {
  10456. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10457. }
  10458. else {
  10459. minFilter = gl.NEAREST;
  10460. }
  10461. break;
  10462. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  10463. magFilter = gl.NEAREST;
  10464. if (generateMipMaps) {
  10465. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10466. }
  10467. else {
  10468. minFilter = gl.NEAREST;
  10469. }
  10470. break;
  10471. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  10472. magFilter = gl.NEAREST;
  10473. if (generateMipMaps) {
  10474. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10475. }
  10476. else {
  10477. minFilter = gl.LINEAR;
  10478. }
  10479. break;
  10480. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  10481. magFilter = gl.NEAREST;
  10482. if (generateMipMaps) {
  10483. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10484. }
  10485. else {
  10486. minFilter = gl.LINEAR;
  10487. }
  10488. break;
  10489. case BABYLON.Texture.NEAREST_LINEAR:
  10490. magFilter = gl.NEAREST;
  10491. minFilter = gl.LINEAR;
  10492. break;
  10493. case BABYLON.Texture.NEAREST_NEAREST:
  10494. magFilter = gl.NEAREST;
  10495. minFilter = gl.NEAREST;
  10496. break;
  10497. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  10498. magFilter = gl.LINEAR;
  10499. if (generateMipMaps) {
  10500. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10501. }
  10502. else {
  10503. minFilter = gl.NEAREST;
  10504. }
  10505. break;
  10506. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  10507. magFilter = gl.LINEAR;
  10508. if (generateMipMaps) {
  10509. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10510. }
  10511. else {
  10512. minFilter = gl.NEAREST;
  10513. }
  10514. break;
  10515. case BABYLON.Texture.LINEAR_LINEAR:
  10516. magFilter = gl.LINEAR;
  10517. minFilter = gl.LINEAR;
  10518. break;
  10519. case BABYLON.Texture.LINEAR_NEAREST:
  10520. magFilter = gl.LINEAR;
  10521. minFilter = gl.NEAREST;
  10522. break;
  10523. }
  10524. return {
  10525. min: minFilter,
  10526. mag: magFilter
  10527. };
  10528. };
  10529. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  10530. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  10531. var img;
  10532. var onload = function () {
  10533. loadedImages[index] = img;
  10534. loadedImages._internalCount++;
  10535. if (scene) {
  10536. scene._removePendingData(img);
  10537. }
  10538. if (loadedImages._internalCount === 6) {
  10539. onfinish(loadedImages);
  10540. }
  10541. };
  10542. var onerror = function (message, exception) {
  10543. if (scene) {
  10544. scene._removePendingData(img);
  10545. }
  10546. if (onErrorCallBack) {
  10547. onErrorCallBack(message, exception);
  10548. }
  10549. };
  10550. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  10551. if (scene) {
  10552. scene._addPendingData(img);
  10553. }
  10554. };
  10555. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  10556. if (onError === void 0) { onError = null; }
  10557. var loadedImages = [];
  10558. loadedImages._internalCount = 0;
  10559. for (var index = 0; index < 6; index++) {
  10560. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  10561. }
  10562. };
  10563. var BufferPointer = /** @class */ (function () {
  10564. function BufferPointer() {
  10565. }
  10566. return BufferPointer;
  10567. }());
  10568. var InstancingAttributeInfo = /** @class */ (function () {
  10569. function InstancingAttributeInfo() {
  10570. }
  10571. return InstancingAttributeInfo;
  10572. }());
  10573. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  10574. /**
  10575. * Define options used to create a render target texture
  10576. */
  10577. var RenderTargetCreationOptions = /** @class */ (function () {
  10578. function RenderTargetCreationOptions() {
  10579. }
  10580. return RenderTargetCreationOptions;
  10581. }());
  10582. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  10583. /**
  10584. * Define options used to create a depth texture
  10585. */
  10586. var DepthTextureCreationOptions = /** @class */ (function () {
  10587. function DepthTextureCreationOptions() {
  10588. }
  10589. return DepthTextureCreationOptions;
  10590. }());
  10591. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  10592. /**
  10593. * Regroup several parameters relative to the browser in use
  10594. */
  10595. var EngineCapabilities = /** @class */ (function () {
  10596. function EngineCapabilities() {
  10597. }
  10598. return EngineCapabilities;
  10599. }());
  10600. BABYLON.EngineCapabilities = EngineCapabilities;
  10601. /**
  10602. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  10603. */
  10604. var Engine = /** @class */ (function () {
  10605. /**
  10606. * @constructor
  10607. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  10608. * @param antialias defines enable antialiasing (default: false)
  10609. * @param options defines further options to be sent to the getContext() function
  10610. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  10611. */
  10612. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  10613. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  10614. var _this = this;
  10615. // Public members
  10616. this.forcePOTTextures = false;
  10617. this.isFullscreen = false;
  10618. this.isPointerLock = false;
  10619. this.cullBackFaces = true;
  10620. this.renderEvenInBackground = true;
  10621. this.preventCacheWipeBetweenFrames = false;
  10622. // To enable/disable IDB support and avoid XHR on .manifest
  10623. this.enableOfflineSupport = false;
  10624. this.scenes = new Array();
  10625. this.postProcesses = new Array();
  10626. // Observables
  10627. /**
  10628. * Observable event triggered each time the rendering canvas is resized
  10629. */
  10630. this.onResizeObservable = new BABYLON.Observable();
  10631. /**
  10632. * Observable event triggered each time the canvas loses focus
  10633. */
  10634. this.onCanvasBlurObservable = new BABYLON.Observable();
  10635. /**
  10636. * Observable event triggered each time the canvas gains focus
  10637. */
  10638. this.onCanvasFocusObservable = new BABYLON.Observable();
  10639. /**
  10640. * Observable event triggered each time the canvas receives pointerout event
  10641. */
  10642. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  10643. /**
  10644. * Observable event triggered before each texture is initialized
  10645. */
  10646. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  10647. //WebVR
  10648. this._vrDisplay = undefined;
  10649. this._vrSupported = false;
  10650. this._vrExclusivePointerMode = false;
  10651. // Uniform buffers list
  10652. this.disableUniformBuffers = false;
  10653. this._uniformBuffers = new Array();
  10654. // Observables
  10655. /**
  10656. * Observable raised when the engine begins a new frame
  10657. */
  10658. this.onBeginFrameObservable = new BABYLON.Observable();
  10659. /**
  10660. * Observable raised when the engine ends the current frame
  10661. */
  10662. this.onEndFrameObservable = new BABYLON.Observable();
  10663. /**
  10664. * Observable raised when the engine is about to compile a shader
  10665. */
  10666. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  10667. /**
  10668. * Observable raised when the engine has jsut compiled a shader
  10669. */
  10670. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  10671. this._windowIsBackground = false;
  10672. this._webGLVersion = 1.0;
  10673. this._badOS = false;
  10674. this._badDesktopOS = false;
  10675. /**
  10676. * Gets or sets a value indicating if we want to disable texture binding optmization.
  10677. * This could be required on some buggy drivers which wants to have textures bound in a progressive order
  10678. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is.
  10679. */
  10680. this.disableTextureBindingOptimization = false;
  10681. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  10682. this.onVRRequestPresentComplete = new BABYLON.Observable();
  10683. this.onVRRequestPresentStart = new BABYLON.Observable();
  10684. this._colorWrite = true;
  10685. this._drawCalls = new BABYLON.PerfCounter();
  10686. this._textureCollisions = new BABYLON.PerfCounter();
  10687. this._renderingQueueLaunched = false;
  10688. this._activeRenderLoops = new Array();
  10689. // Deterministic lockstepMaxSteps
  10690. this._deterministicLockstep = false;
  10691. this._lockstepMaxSteps = 4;
  10692. // Lost context
  10693. this.onContextLostObservable = new BABYLON.Observable();
  10694. this.onContextRestoredObservable = new BABYLON.Observable();
  10695. this._contextWasLost = false;
  10696. this._doNotHandleContextLost = false;
  10697. // FPS
  10698. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  10699. this._fps = 60;
  10700. this._deltaTime = 0;
  10701. /**
  10702. * Turn this value on if you want to pause FPS computation when in background
  10703. */
  10704. this.disablePerformanceMonitorInBackground = false;
  10705. // States
  10706. this._depthCullingState = new BABYLON._DepthCullingState();
  10707. this._stencilState = new BABYLON._StencilState();
  10708. this._alphaState = new BABYLON._AlphaState();
  10709. this._alphaMode = Engine.ALPHA_DISABLE;
  10710. // Cache
  10711. this._internalTexturesCache = new Array();
  10712. this._activeChannel = 0;
  10713. this._currentTextureChannel = -1;
  10714. this._boundTexturesCache = {};
  10715. this._compiledEffects = {};
  10716. this._vertexAttribArraysEnabled = [];
  10717. this._uintIndicesCurrentlySet = false;
  10718. this._currentBoundBuffer = new Array();
  10719. this._currentBufferPointers = new Array();
  10720. this._currentInstanceLocations = new Array();
  10721. this._currentInstanceBuffers = new Array();
  10722. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10723. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10724. this._vaoRecordInProgress = false;
  10725. this._mustWipeVertexAttributes = false;
  10726. this._nextFreeTextureSlots = new Array();
  10727. this._maxSimultaneousTextures = 0;
  10728. this._activeRequests = new Array();
  10729. // Hardware supported Compressed Textures
  10730. this._texturesSupported = new Array();
  10731. this._onVRFullScreenTriggered = function () {
  10732. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  10733. //get the old size before we change
  10734. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  10735. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  10736. //get the width and height, change the render size
  10737. var leftEye = _this._vrDisplay.getEyeParameters('left');
  10738. _this.setHardwareScalingLevel(1);
  10739. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  10740. }
  10741. else {
  10742. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  10743. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  10744. }
  10745. };
  10746. this._boundUniforms = {};
  10747. // Register promises
  10748. BABYLON.PromisePolyfill.Apply();
  10749. var canvas = null;
  10750. Engine.Instances.push(this);
  10751. if (!canvasOrContext) {
  10752. return;
  10753. }
  10754. options = options || {};
  10755. if (canvasOrContext.getContext) {
  10756. canvas = canvasOrContext;
  10757. this._renderingCanvas = canvas;
  10758. if (antialias != null) {
  10759. options.antialias = antialias;
  10760. }
  10761. if (options.deterministicLockstep === undefined) {
  10762. options.deterministicLockstep = false;
  10763. }
  10764. if (options.lockstepMaxSteps === undefined) {
  10765. options.lockstepMaxSteps = 4;
  10766. }
  10767. if (options.preserveDrawingBuffer === undefined) {
  10768. options.preserveDrawingBuffer = false;
  10769. }
  10770. if (options.audioEngine === undefined) {
  10771. options.audioEngine = true;
  10772. }
  10773. if (options.stencil === undefined) {
  10774. options.stencil = true;
  10775. }
  10776. this._deterministicLockstep = options.deterministicLockstep;
  10777. this._lockstepMaxSteps = options.lockstepMaxSteps;
  10778. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  10779. // Exceptions
  10780. if (navigator && navigator.userAgent) {
  10781. var ua = navigator.userAgent;
  10782. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  10783. var exception = _a[_i];
  10784. var key = exception.key;
  10785. var targets = exception.targets;
  10786. if (ua.indexOf(key) > -1) {
  10787. if (exception.capture && exception.captureConstraint) {
  10788. var capture = exception.capture;
  10789. var constraint = exception.captureConstraint;
  10790. var regex = new RegExp(capture);
  10791. var matches = regex.exec(ua);
  10792. if (matches && matches.length > 0) {
  10793. var capturedValue = parseInt(matches[matches.length - 1]);
  10794. if (capturedValue >= constraint) {
  10795. continue;
  10796. }
  10797. }
  10798. }
  10799. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  10800. var target = targets_1[_b];
  10801. switch (target) {
  10802. case "uniformBuffer":
  10803. this.disableUniformBuffers = true;
  10804. break;
  10805. case "textureBindingOptimization":
  10806. this.disableTextureBindingOptimization = true;
  10807. break;
  10808. }
  10809. }
  10810. }
  10811. }
  10812. }
  10813. // GL
  10814. if (!options.disableWebGL2Support) {
  10815. try {
  10816. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  10817. if (this._gl) {
  10818. this._webGLVersion = 2.0;
  10819. }
  10820. }
  10821. catch (e) {
  10822. // Do nothing
  10823. }
  10824. }
  10825. if (!this._gl) {
  10826. if (!canvas) {
  10827. throw new Error("The provided canvas is null or undefined.");
  10828. }
  10829. try {
  10830. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  10831. }
  10832. catch (e) {
  10833. throw new Error("WebGL not supported");
  10834. }
  10835. }
  10836. if (!this._gl) {
  10837. throw new Error("WebGL not supported");
  10838. }
  10839. this._onCanvasFocus = function () {
  10840. _this.onCanvasFocusObservable.notifyObservers(_this);
  10841. };
  10842. this._onCanvasBlur = function () {
  10843. _this.onCanvasBlurObservable.notifyObservers(_this);
  10844. };
  10845. canvas.addEventListener("focus", this._onCanvasFocus);
  10846. canvas.addEventListener("blur", this._onCanvasBlur);
  10847. this._onBlur = function () {
  10848. if (_this.disablePerformanceMonitorInBackground) {
  10849. _this._performanceMonitor.disable();
  10850. }
  10851. _this._windowIsBackground = true;
  10852. };
  10853. this._onFocus = function () {
  10854. if (_this.disablePerformanceMonitorInBackground) {
  10855. _this._performanceMonitor.enable();
  10856. }
  10857. _this._windowIsBackground = false;
  10858. };
  10859. this._onCanvasPointerOut = function (ev) {
  10860. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  10861. };
  10862. window.addEventListener("blur", this._onBlur);
  10863. window.addEventListener("focus", this._onFocus);
  10864. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  10865. // Context lost
  10866. if (!this._doNotHandleContextLost) {
  10867. this._onContextLost = function (evt) {
  10868. evt.preventDefault();
  10869. _this._contextWasLost = true;
  10870. BABYLON.Tools.Warn("WebGL context lost.");
  10871. _this.onContextLostObservable.notifyObservers(_this);
  10872. };
  10873. this._onContextRestored = function (evt) {
  10874. // Adding a timeout to avoid race condition at browser level
  10875. setTimeout(function () {
  10876. // Rebuild gl context
  10877. _this._initGLContext();
  10878. // Rebuild effects
  10879. _this._rebuildEffects();
  10880. // Rebuild textures
  10881. _this._rebuildInternalTextures();
  10882. // Rebuild buffers
  10883. _this._rebuildBuffers();
  10884. // Cache
  10885. _this.wipeCaches(true);
  10886. BABYLON.Tools.Warn("WebGL context successfully restored.");
  10887. _this.onContextRestoredObservable.notifyObservers(_this);
  10888. _this._contextWasLost = false;
  10889. }, 0);
  10890. };
  10891. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  10892. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  10893. }
  10894. }
  10895. else {
  10896. this._gl = canvasOrContext;
  10897. this._renderingCanvas = this._gl.canvas;
  10898. if (this._gl.renderbufferStorageMultisample) {
  10899. this._webGLVersion = 2.0;
  10900. }
  10901. options.stencil = this._gl.getContextAttributes().stencil;
  10902. }
  10903. // Viewport
  10904. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  10905. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  10906. this.resize();
  10907. this._isStencilEnable = options.stencil ? true : false;
  10908. this._initGLContext();
  10909. if (canvas) {
  10910. // Fullscreen
  10911. this._onFullscreenChange = function () {
  10912. if (document.fullscreen !== undefined) {
  10913. _this.isFullscreen = document.fullscreen;
  10914. }
  10915. else if (document.mozFullScreen !== undefined) {
  10916. _this.isFullscreen = document.mozFullScreen;
  10917. }
  10918. else if (document.webkitIsFullScreen !== undefined) {
  10919. _this.isFullscreen = document.webkitIsFullScreen;
  10920. }
  10921. else if (document.msIsFullScreen !== undefined) {
  10922. _this.isFullscreen = document.msIsFullScreen;
  10923. }
  10924. // Pointer lock
  10925. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  10926. canvas.requestPointerLock = canvas.requestPointerLock ||
  10927. canvas.msRequestPointerLock ||
  10928. canvas.mozRequestPointerLock ||
  10929. canvas.webkitRequestPointerLock;
  10930. if (canvas.requestPointerLock) {
  10931. canvas.requestPointerLock();
  10932. }
  10933. }
  10934. };
  10935. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  10936. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  10937. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  10938. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  10939. // Pointer lock
  10940. this._onPointerLockChange = function () {
  10941. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  10942. document.webkitPointerLockElement === canvas ||
  10943. document.msPointerLockElement === canvas ||
  10944. document.pointerLockElement === canvas);
  10945. };
  10946. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  10947. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  10948. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  10949. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  10950. this._onVRDisplayPointerRestricted = function () {
  10951. if (canvas) {
  10952. canvas.requestPointerLock();
  10953. }
  10954. };
  10955. this._onVRDisplayPointerUnrestricted = function () {
  10956. document.exitPointerLock();
  10957. };
  10958. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  10959. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  10960. }
  10961. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  10962. Engine.audioEngine = new BABYLON.AudioEngine();
  10963. }
  10964. // Prepare buffer pointers
  10965. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10966. this._currentBufferPointers[i] = new BufferPointer();
  10967. }
  10968. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  10969. // Load WebVR Devices
  10970. if (options.autoEnableWebVR) {
  10971. this.initWebVR();
  10972. }
  10973. // Detect if we are running on a faulty buggy OS.
  10974. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  10975. // Detect if we are running on a faulty buggy desktop OS.
  10976. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  10977. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  10978. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  10979. }
  10980. Object.defineProperty(Engine, "LastCreatedEngine", {
  10981. get: function () {
  10982. if (Engine.Instances.length === 0) {
  10983. return null;
  10984. }
  10985. return Engine.Instances[Engine.Instances.length - 1];
  10986. },
  10987. enumerable: true,
  10988. configurable: true
  10989. });
  10990. Object.defineProperty(Engine, "LastCreatedScene", {
  10991. get: function () {
  10992. var lastCreatedEngine = Engine.LastCreatedEngine;
  10993. if (!lastCreatedEngine) {
  10994. return null;
  10995. }
  10996. if (lastCreatedEngine.scenes.length === 0) {
  10997. return null;
  10998. }
  10999. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11000. },
  11001. enumerable: true,
  11002. configurable: true
  11003. });
  11004. /**
  11005. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11006. */
  11007. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11008. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11009. var engine = Engine.Instances[engineIndex];
  11010. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11011. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11012. }
  11013. }
  11014. };
  11015. Object.defineProperty(Engine, "NEVER", {
  11016. get: function () {
  11017. return Engine._NEVER;
  11018. },
  11019. enumerable: true,
  11020. configurable: true
  11021. });
  11022. Object.defineProperty(Engine, "ALWAYS", {
  11023. get: function () {
  11024. return Engine._ALWAYS;
  11025. },
  11026. enumerable: true,
  11027. configurable: true
  11028. });
  11029. Object.defineProperty(Engine, "LESS", {
  11030. get: function () {
  11031. return Engine._LESS;
  11032. },
  11033. enumerable: true,
  11034. configurable: true
  11035. });
  11036. Object.defineProperty(Engine, "EQUAL", {
  11037. get: function () {
  11038. return Engine._EQUAL;
  11039. },
  11040. enumerable: true,
  11041. configurable: true
  11042. });
  11043. Object.defineProperty(Engine, "LEQUAL", {
  11044. get: function () {
  11045. return Engine._LEQUAL;
  11046. },
  11047. enumerable: true,
  11048. configurable: true
  11049. });
  11050. Object.defineProperty(Engine, "GREATER", {
  11051. get: function () {
  11052. return Engine._GREATER;
  11053. },
  11054. enumerable: true,
  11055. configurable: true
  11056. });
  11057. Object.defineProperty(Engine, "GEQUAL", {
  11058. get: function () {
  11059. return Engine._GEQUAL;
  11060. },
  11061. enumerable: true,
  11062. configurable: true
  11063. });
  11064. Object.defineProperty(Engine, "NOTEQUAL", {
  11065. get: function () {
  11066. return Engine._NOTEQUAL;
  11067. },
  11068. enumerable: true,
  11069. configurable: true
  11070. });
  11071. Object.defineProperty(Engine, "KEEP", {
  11072. get: function () {
  11073. return Engine._KEEP;
  11074. },
  11075. enumerable: true,
  11076. configurable: true
  11077. });
  11078. Object.defineProperty(Engine, "REPLACE", {
  11079. get: function () {
  11080. return Engine._REPLACE;
  11081. },
  11082. enumerable: true,
  11083. configurable: true
  11084. });
  11085. Object.defineProperty(Engine, "INCR", {
  11086. get: function () {
  11087. return Engine._INCR;
  11088. },
  11089. enumerable: true,
  11090. configurable: true
  11091. });
  11092. Object.defineProperty(Engine, "DECR", {
  11093. get: function () {
  11094. return Engine._DECR;
  11095. },
  11096. enumerable: true,
  11097. configurable: true
  11098. });
  11099. Object.defineProperty(Engine, "INVERT", {
  11100. get: function () {
  11101. return Engine._INVERT;
  11102. },
  11103. enumerable: true,
  11104. configurable: true
  11105. });
  11106. Object.defineProperty(Engine, "INCR_WRAP", {
  11107. get: function () {
  11108. return Engine._INCR_WRAP;
  11109. },
  11110. enumerable: true,
  11111. configurable: true
  11112. });
  11113. Object.defineProperty(Engine, "DECR_WRAP", {
  11114. get: function () {
  11115. return Engine._DECR_WRAP;
  11116. },
  11117. enumerable: true,
  11118. configurable: true
  11119. });
  11120. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  11121. get: function () {
  11122. return Engine._ALPHA_DISABLE;
  11123. },
  11124. enumerable: true,
  11125. configurable: true
  11126. });
  11127. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  11128. get: function () {
  11129. return Engine._ALPHA_ONEONE;
  11130. },
  11131. enumerable: true,
  11132. configurable: true
  11133. });
  11134. Object.defineProperty(Engine, "ALPHA_ADD", {
  11135. get: function () {
  11136. return Engine._ALPHA_ADD;
  11137. },
  11138. enumerable: true,
  11139. configurable: true
  11140. });
  11141. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  11142. get: function () {
  11143. return Engine._ALPHA_COMBINE;
  11144. },
  11145. enumerable: true,
  11146. configurable: true
  11147. });
  11148. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  11149. get: function () {
  11150. return Engine._ALPHA_SUBTRACT;
  11151. },
  11152. enumerable: true,
  11153. configurable: true
  11154. });
  11155. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  11156. get: function () {
  11157. return Engine._ALPHA_MULTIPLY;
  11158. },
  11159. enumerable: true,
  11160. configurable: true
  11161. });
  11162. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  11163. get: function () {
  11164. return Engine._ALPHA_MAXIMIZED;
  11165. },
  11166. enumerable: true,
  11167. configurable: true
  11168. });
  11169. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  11170. get: function () {
  11171. return Engine._ALPHA_PREMULTIPLIED;
  11172. },
  11173. enumerable: true,
  11174. configurable: true
  11175. });
  11176. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  11177. get: function () {
  11178. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  11179. },
  11180. enumerable: true,
  11181. configurable: true
  11182. });
  11183. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  11184. get: function () {
  11185. return Engine._ALPHA_INTERPOLATE;
  11186. },
  11187. enumerable: true,
  11188. configurable: true
  11189. });
  11190. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  11191. get: function () {
  11192. return Engine._ALPHA_SCREENMODE;
  11193. },
  11194. enumerable: true,
  11195. configurable: true
  11196. });
  11197. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  11198. get: function () {
  11199. return Engine._DELAYLOADSTATE_NONE;
  11200. },
  11201. enumerable: true,
  11202. configurable: true
  11203. });
  11204. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  11205. get: function () {
  11206. return Engine._DELAYLOADSTATE_LOADED;
  11207. },
  11208. enumerable: true,
  11209. configurable: true
  11210. });
  11211. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  11212. get: function () {
  11213. return Engine._DELAYLOADSTATE_LOADING;
  11214. },
  11215. enumerable: true,
  11216. configurable: true
  11217. });
  11218. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  11219. get: function () {
  11220. return Engine._DELAYLOADSTATE_NOTLOADED;
  11221. },
  11222. enumerable: true,
  11223. configurable: true
  11224. });
  11225. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  11226. get: function () {
  11227. return Engine._TEXTUREFORMAT_ALPHA;
  11228. },
  11229. enumerable: true,
  11230. configurable: true
  11231. });
  11232. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  11233. get: function () {
  11234. return Engine._TEXTUREFORMAT_LUMINANCE;
  11235. },
  11236. enumerable: true,
  11237. configurable: true
  11238. });
  11239. Object.defineProperty(Engine, "TEXTUREFORMAT_R32F", {
  11240. /**
  11241. * R32F
  11242. */
  11243. get: function () {
  11244. return Engine._TEXTUREFORMAT_R32F;
  11245. },
  11246. enumerable: true,
  11247. configurable: true
  11248. });
  11249. Object.defineProperty(Engine, "TEXTUREFORMAT_RG32F", {
  11250. /**
  11251. * RG32F
  11252. */
  11253. get: function () {
  11254. return Engine._TEXTUREFORMAT_RG32F;
  11255. },
  11256. enumerable: true,
  11257. configurable: true
  11258. });
  11259. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB32F", {
  11260. /**
  11261. * RGB32F
  11262. */
  11263. get: function () {
  11264. return Engine._TEXTUREFORMAT_RGB32F;
  11265. },
  11266. enumerable: true,
  11267. configurable: true
  11268. });
  11269. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA32F", {
  11270. /**
  11271. * RGBA32F
  11272. */
  11273. get: function () {
  11274. return Engine._TEXTUREFORMAT_RGBA32F;
  11275. },
  11276. enumerable: true,
  11277. configurable: true
  11278. });
  11279. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  11280. get: function () {
  11281. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  11282. },
  11283. enumerable: true,
  11284. configurable: true
  11285. });
  11286. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  11287. get: function () {
  11288. return Engine._TEXTUREFORMAT_RGB;
  11289. },
  11290. enumerable: true,
  11291. configurable: true
  11292. });
  11293. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  11294. get: function () {
  11295. return Engine._TEXTUREFORMAT_RGBA;
  11296. },
  11297. enumerable: true,
  11298. configurable: true
  11299. });
  11300. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  11301. get: function () {
  11302. return Engine._TEXTURETYPE_UNSIGNED_INT;
  11303. },
  11304. enumerable: true,
  11305. configurable: true
  11306. });
  11307. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  11308. get: function () {
  11309. return Engine._TEXTURETYPE_FLOAT;
  11310. },
  11311. enumerable: true,
  11312. configurable: true
  11313. });
  11314. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  11315. get: function () {
  11316. return Engine._TEXTURETYPE_HALF_FLOAT;
  11317. },
  11318. enumerable: true,
  11319. configurable: true
  11320. });
  11321. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  11322. get: function () {
  11323. return Engine._SCALEMODE_FLOOR;
  11324. },
  11325. enumerable: true,
  11326. configurable: true
  11327. });
  11328. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  11329. get: function () {
  11330. return Engine._SCALEMODE_NEAREST;
  11331. },
  11332. enumerable: true,
  11333. configurable: true
  11334. });
  11335. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  11336. get: function () {
  11337. return Engine._SCALEMODE_CEILING;
  11338. },
  11339. enumerable: true,
  11340. configurable: true
  11341. });
  11342. Object.defineProperty(Engine, "Version", {
  11343. get: function () {
  11344. return "3.2.0-beta.1";
  11345. },
  11346. enumerable: true,
  11347. configurable: true
  11348. });
  11349. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11350. get: function () {
  11351. return this._vrExclusivePointerMode;
  11352. },
  11353. enumerable: true,
  11354. configurable: true
  11355. });
  11356. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  11357. get: function () {
  11358. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  11359. },
  11360. enumerable: true,
  11361. configurable: true
  11362. });
  11363. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  11364. get: function () {
  11365. return this._webGLVersion < 2 || this.forcePOTTextures;
  11366. },
  11367. enumerable: true,
  11368. configurable: true
  11369. });
  11370. Object.defineProperty(Engine.prototype, "badOS", {
  11371. get: function () {
  11372. return this._badOS;
  11373. },
  11374. enumerable: true,
  11375. configurable: true
  11376. });
  11377. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  11378. get: function () {
  11379. return this._badDesktopOS;
  11380. },
  11381. enumerable: true,
  11382. configurable: true
  11383. });
  11384. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  11385. get: function () {
  11386. return this._performanceMonitor;
  11387. },
  11388. enumerable: true,
  11389. configurable: true
  11390. });
  11391. Object.defineProperty(Engine.prototype, "texturesSupported", {
  11392. get: function () {
  11393. return this._texturesSupported;
  11394. },
  11395. enumerable: true,
  11396. configurable: true
  11397. });
  11398. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  11399. get: function () {
  11400. return this._textureFormatInUse;
  11401. },
  11402. enumerable: true,
  11403. configurable: true
  11404. });
  11405. Object.defineProperty(Engine.prototype, "currentViewport", {
  11406. get: function () {
  11407. return this._cachedViewport;
  11408. },
  11409. enumerable: true,
  11410. configurable: true
  11411. });
  11412. Object.defineProperty(Engine.prototype, "emptyTexture", {
  11413. // Empty texture
  11414. get: function () {
  11415. if (!this._emptyTexture) {
  11416. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11417. }
  11418. return this._emptyTexture;
  11419. },
  11420. enumerable: true,
  11421. configurable: true
  11422. });
  11423. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  11424. get: function () {
  11425. if (!this._emptyTexture3D) {
  11426. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11427. }
  11428. return this._emptyTexture3D;
  11429. },
  11430. enumerable: true,
  11431. configurable: true
  11432. });
  11433. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  11434. get: function () {
  11435. if (!this._emptyCubeTexture) {
  11436. var faceData = new Uint8Array(4);
  11437. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  11438. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11439. }
  11440. return this._emptyCubeTexture;
  11441. },
  11442. enumerable: true,
  11443. configurable: true
  11444. });
  11445. Engine.prototype._rebuildInternalTextures = function () {
  11446. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  11447. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  11448. var internalTexture = currentState_1[_i];
  11449. internalTexture._rebuild();
  11450. }
  11451. };
  11452. Engine.prototype._rebuildEffects = function () {
  11453. for (var key in this._compiledEffects) {
  11454. var effect = this._compiledEffects[key];
  11455. effect._prepareEffect();
  11456. }
  11457. BABYLON.Effect.ResetCache();
  11458. };
  11459. Engine.prototype._rebuildBuffers = function () {
  11460. // Index / Vertex
  11461. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  11462. var scene = _a[_i];
  11463. scene.resetCachedMaterial();
  11464. scene._rebuildGeometries();
  11465. scene._rebuildTextures();
  11466. }
  11467. // Uniforms
  11468. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  11469. var uniformBuffer = _c[_b];
  11470. uniformBuffer._rebuild();
  11471. }
  11472. };
  11473. Engine.prototype._initGLContext = function () {
  11474. // Caps
  11475. this._caps = new EngineCapabilities();
  11476. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  11477. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  11478. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  11479. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  11480. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  11481. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  11482. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  11483. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  11484. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  11485. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  11486. // Infos
  11487. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  11488. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  11489. if (rendererInfo != null) {
  11490. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  11491. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  11492. }
  11493. if (!this._glVendor) {
  11494. this._glVendor = "Unknown vendor";
  11495. }
  11496. if (!this._glRenderer) {
  11497. this._glRenderer = "Unknown renderer";
  11498. }
  11499. // Constants
  11500. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  11501. if (this._gl.RGBA16F !== 0x881A) {
  11502. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  11503. }
  11504. if (this._gl.RGBA32F !== 0x8814) {
  11505. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  11506. }
  11507. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  11508. this._gl.DEPTH24_STENCIL8 = 35056;
  11509. }
  11510. // Extensions
  11511. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  11512. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  11513. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  11514. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  11515. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  11516. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  11517. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  11518. 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');
  11519. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  11520. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  11521. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  11522. this._caps.highPrecisionShaderSupported = true;
  11523. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  11524. if (this._caps.timerQuery) {
  11525. if (this._webGLVersion === 1) {
  11526. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  11527. }
  11528. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  11529. }
  11530. // Checks if some of the format renders first to allow the use of webgl inspector.
  11531. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  11532. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  11533. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  11534. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  11535. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  11536. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  11537. if (this._webGLVersion > 1) {
  11538. this._gl.HALF_FLOAT_OES = 0x140B;
  11539. }
  11540. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  11541. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  11542. // Draw buffers
  11543. if (this._webGLVersion > 1) {
  11544. this._caps.drawBuffersExtension = true;
  11545. }
  11546. else {
  11547. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  11548. if (drawBuffersExtension !== null) {
  11549. this._caps.drawBuffersExtension = true;
  11550. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  11551. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  11552. for (var i = 0; i < 16; i++) {
  11553. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  11554. }
  11555. }
  11556. else {
  11557. this._caps.drawBuffersExtension = false;
  11558. }
  11559. }
  11560. // Depth Texture
  11561. if (this._webGLVersion > 1) {
  11562. this._caps.depthTextureExtension = true;
  11563. }
  11564. else {
  11565. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  11566. if (depthTextureExtension != null) {
  11567. this._caps.depthTextureExtension = true;
  11568. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  11569. }
  11570. }
  11571. // Vertex array object
  11572. if (this._webGLVersion > 1) {
  11573. this._caps.vertexArrayObject = true;
  11574. }
  11575. else {
  11576. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  11577. if (vertexArrayObjectExtension != null) {
  11578. this._caps.vertexArrayObject = true;
  11579. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  11580. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  11581. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  11582. }
  11583. else {
  11584. this._caps.vertexArrayObject = false;
  11585. }
  11586. }
  11587. // Instances count
  11588. if (this._webGLVersion > 1) {
  11589. this._caps.instancedArrays = true;
  11590. }
  11591. else {
  11592. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  11593. if (instanceExtension != null) {
  11594. this._caps.instancedArrays = true;
  11595. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  11596. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  11597. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  11598. }
  11599. else {
  11600. this._caps.instancedArrays = false;
  11601. }
  11602. }
  11603. // Intelligently add supported compressed formats in order to check for.
  11604. // Check for ASTC support first as it is most powerful and to be very cross platform.
  11605. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  11606. // Likely no hardware which supports both PVR & DXT, so order matters little.
  11607. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  11608. if (this._caps.astc)
  11609. this.texturesSupported.push('-astc.ktx');
  11610. if (this._caps.s3tc)
  11611. this.texturesSupported.push('-dxt.ktx');
  11612. if (this._caps.pvrtc)
  11613. this.texturesSupported.push('-pvrtc.ktx');
  11614. if (this._caps.etc2)
  11615. this.texturesSupported.push('-etc2.ktx');
  11616. if (this._caps.etc1)
  11617. this.texturesSupported.push('-etc1.ktx');
  11618. if (this._gl.getShaderPrecisionFormat) {
  11619. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  11620. if (highp) {
  11621. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  11622. }
  11623. }
  11624. // Depth buffer
  11625. this.setDepthBuffer(true);
  11626. this.setDepthFunctionToLessOrEqual();
  11627. this.setDepthWrite(true);
  11628. // Texture maps
  11629. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  11630. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11631. this._nextFreeTextureSlots.push(slot);
  11632. }
  11633. };
  11634. Object.defineProperty(Engine.prototype, "webGLVersion", {
  11635. get: function () {
  11636. return this._webGLVersion;
  11637. },
  11638. enumerable: true,
  11639. configurable: true
  11640. });
  11641. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  11642. /**
  11643. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  11644. */
  11645. get: function () {
  11646. return this._isStencilEnable;
  11647. },
  11648. enumerable: true,
  11649. configurable: true
  11650. });
  11651. Engine.prototype._prepareWorkingCanvas = function () {
  11652. if (this._workingCanvas) {
  11653. return;
  11654. }
  11655. this._workingCanvas = document.createElement("canvas");
  11656. var context = this._workingCanvas.getContext("2d");
  11657. if (context) {
  11658. this._workingContext = context;
  11659. }
  11660. };
  11661. Engine.prototype.resetTextureCache = function () {
  11662. for (var key in this._boundTexturesCache) {
  11663. var boundTexture = this._boundTexturesCache[key];
  11664. if (boundTexture) {
  11665. this._removeDesignatedSlot(boundTexture);
  11666. }
  11667. this._boundTexturesCache[key] = null;
  11668. }
  11669. if (!this.disableTextureBindingOptimization) {
  11670. this._nextFreeTextureSlots = [];
  11671. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11672. this._nextFreeTextureSlots.push(slot);
  11673. }
  11674. }
  11675. this._currentTextureChannel = -1;
  11676. };
  11677. Engine.prototype.isDeterministicLockStep = function () {
  11678. return this._deterministicLockstep;
  11679. };
  11680. Engine.prototype.getLockstepMaxSteps = function () {
  11681. return this._lockstepMaxSteps;
  11682. };
  11683. Engine.prototype.getGlInfo = function () {
  11684. return {
  11685. vendor: this._glVendor,
  11686. renderer: this._glRenderer,
  11687. version: this._glVersion
  11688. };
  11689. };
  11690. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  11691. if (useScreen === void 0) { useScreen = false; }
  11692. var viewport = camera.viewport;
  11693. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  11694. };
  11695. Engine.prototype.getRenderWidth = function (useScreen) {
  11696. if (useScreen === void 0) { useScreen = false; }
  11697. if (!useScreen && this._currentRenderTarget) {
  11698. return this._currentRenderTarget.width;
  11699. }
  11700. return this._gl.drawingBufferWidth;
  11701. };
  11702. Engine.prototype.getRenderHeight = function (useScreen) {
  11703. if (useScreen === void 0) { useScreen = false; }
  11704. if (!useScreen && this._currentRenderTarget) {
  11705. return this._currentRenderTarget.height;
  11706. }
  11707. return this._gl.drawingBufferHeight;
  11708. };
  11709. Engine.prototype.getRenderingCanvas = function () {
  11710. return this._renderingCanvas;
  11711. };
  11712. Engine.prototype.getRenderingCanvasClientRect = function () {
  11713. if (!this._renderingCanvas) {
  11714. return null;
  11715. }
  11716. return this._renderingCanvas.getBoundingClientRect();
  11717. };
  11718. Engine.prototype.setHardwareScalingLevel = function (level) {
  11719. this._hardwareScalingLevel = level;
  11720. this.resize();
  11721. };
  11722. Engine.prototype.getHardwareScalingLevel = function () {
  11723. return this._hardwareScalingLevel;
  11724. };
  11725. Engine.prototype.getLoadedTexturesCache = function () {
  11726. return this._internalTexturesCache;
  11727. };
  11728. Engine.prototype.getCaps = function () {
  11729. return this._caps;
  11730. };
  11731. Object.defineProperty(Engine.prototype, "drawCalls", {
  11732. /** The number of draw calls submitted last frame */
  11733. get: function () {
  11734. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  11735. return 0;
  11736. },
  11737. enumerable: true,
  11738. configurable: true
  11739. });
  11740. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  11741. get: function () {
  11742. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  11743. return null;
  11744. },
  11745. enumerable: true,
  11746. configurable: true
  11747. });
  11748. Engine.prototype.getDepthFunction = function () {
  11749. return this._depthCullingState.depthFunc;
  11750. };
  11751. Engine.prototype.setDepthFunction = function (depthFunc) {
  11752. this._depthCullingState.depthFunc = depthFunc;
  11753. };
  11754. Engine.prototype.setDepthFunctionToGreater = function () {
  11755. this._depthCullingState.depthFunc = this._gl.GREATER;
  11756. };
  11757. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  11758. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  11759. };
  11760. Engine.prototype.setDepthFunctionToLess = function () {
  11761. this._depthCullingState.depthFunc = this._gl.LESS;
  11762. };
  11763. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  11764. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  11765. };
  11766. Engine.prototype.getStencilBuffer = function () {
  11767. return this._stencilState.stencilTest;
  11768. };
  11769. Engine.prototype.setStencilBuffer = function (enable) {
  11770. this._stencilState.stencilTest = enable;
  11771. };
  11772. Engine.prototype.getStencilMask = function () {
  11773. return this._stencilState.stencilMask;
  11774. };
  11775. Engine.prototype.setStencilMask = function (mask) {
  11776. this._stencilState.stencilMask = mask;
  11777. };
  11778. Engine.prototype.getStencilFunction = function () {
  11779. return this._stencilState.stencilFunc;
  11780. };
  11781. Engine.prototype.getStencilFunctionReference = function () {
  11782. return this._stencilState.stencilFuncRef;
  11783. };
  11784. Engine.prototype.getStencilFunctionMask = function () {
  11785. return this._stencilState.stencilFuncMask;
  11786. };
  11787. Engine.prototype.setStencilFunction = function (stencilFunc) {
  11788. this._stencilState.stencilFunc = stencilFunc;
  11789. };
  11790. Engine.prototype.setStencilFunctionReference = function (reference) {
  11791. this._stencilState.stencilFuncRef = reference;
  11792. };
  11793. Engine.prototype.setStencilFunctionMask = function (mask) {
  11794. this._stencilState.stencilFuncMask = mask;
  11795. };
  11796. Engine.prototype.getStencilOperationFail = function () {
  11797. return this._stencilState.stencilOpStencilFail;
  11798. };
  11799. Engine.prototype.getStencilOperationDepthFail = function () {
  11800. return this._stencilState.stencilOpDepthFail;
  11801. };
  11802. Engine.prototype.getStencilOperationPass = function () {
  11803. return this._stencilState.stencilOpStencilDepthPass;
  11804. };
  11805. Engine.prototype.setStencilOperationFail = function (operation) {
  11806. this._stencilState.stencilOpStencilFail = operation;
  11807. };
  11808. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  11809. this._stencilState.stencilOpDepthFail = operation;
  11810. };
  11811. Engine.prototype.setStencilOperationPass = function (operation) {
  11812. this._stencilState.stencilOpStencilDepthPass = operation;
  11813. };
  11814. Engine.prototype.setDitheringState = function (value) {
  11815. if (value) {
  11816. this._gl.enable(this._gl.DITHER);
  11817. }
  11818. else {
  11819. this._gl.disable(this._gl.DITHER);
  11820. }
  11821. };
  11822. Engine.prototype.setRasterizerState = function (value) {
  11823. if (value) {
  11824. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  11825. }
  11826. else {
  11827. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  11828. }
  11829. };
  11830. /**
  11831. * stop executing a render loop function and remove it from the execution array
  11832. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  11833. */
  11834. Engine.prototype.stopRenderLoop = function (renderFunction) {
  11835. if (!renderFunction) {
  11836. this._activeRenderLoops = [];
  11837. return;
  11838. }
  11839. var index = this._activeRenderLoops.indexOf(renderFunction);
  11840. if (index >= 0) {
  11841. this._activeRenderLoops.splice(index, 1);
  11842. }
  11843. };
  11844. Engine.prototype._renderLoop = function () {
  11845. if (!this._contextWasLost) {
  11846. var shouldRender = true;
  11847. if (!this.renderEvenInBackground && this._windowIsBackground) {
  11848. shouldRender = false;
  11849. }
  11850. if (shouldRender) {
  11851. // Start new frame
  11852. this.beginFrame();
  11853. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  11854. var renderFunction = this._activeRenderLoops[index];
  11855. renderFunction();
  11856. }
  11857. // Present
  11858. this.endFrame();
  11859. }
  11860. }
  11861. if (this._activeRenderLoops.length > 0) {
  11862. // Register new frame
  11863. var requester = null;
  11864. if (this._vrDisplay && this._vrDisplay.isPresenting)
  11865. requester = this._vrDisplay;
  11866. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  11867. }
  11868. else {
  11869. this._renderingQueueLaunched = false;
  11870. }
  11871. };
  11872. /**
  11873. * Register and execute a render loop. The engine can have more than one render function.
  11874. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  11875. * @example
  11876. * engine.runRenderLoop(function () {
  11877. * scene.render()
  11878. * })
  11879. */
  11880. Engine.prototype.runRenderLoop = function (renderFunction) {
  11881. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  11882. return;
  11883. }
  11884. this._activeRenderLoops.push(renderFunction);
  11885. if (!this._renderingQueueLaunched) {
  11886. this._renderingQueueLaunched = true;
  11887. this._bindedRenderFunction = this._renderLoop.bind(this);
  11888. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  11889. }
  11890. };
  11891. /**
  11892. * Toggle full screen mode.
  11893. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  11894. * @param {any} options - an options object to be sent to the requestFullscreen function
  11895. */
  11896. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  11897. if (this.isFullscreen) {
  11898. BABYLON.Tools.ExitFullscreen();
  11899. }
  11900. else {
  11901. this._pointerLockRequested = requestPointerLock;
  11902. if (this._renderingCanvas) {
  11903. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  11904. }
  11905. }
  11906. };
  11907. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  11908. if (stencil === void 0) { stencil = false; }
  11909. this.applyStates();
  11910. var mode = 0;
  11911. if (backBuffer && color) {
  11912. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  11913. mode |= this._gl.COLOR_BUFFER_BIT;
  11914. }
  11915. if (depth) {
  11916. this._gl.clearDepth(1.0);
  11917. mode |= this._gl.DEPTH_BUFFER_BIT;
  11918. }
  11919. if (stencil) {
  11920. this._gl.clearStencil(0);
  11921. mode |= this._gl.STENCIL_BUFFER_BIT;
  11922. }
  11923. this._gl.clear(mode);
  11924. };
  11925. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  11926. var gl = this._gl;
  11927. // Save state
  11928. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  11929. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  11930. // Change state
  11931. gl.enable(gl.SCISSOR_TEST);
  11932. gl.scissor(x, y, width, height);
  11933. // Clear
  11934. this.clear(clearColor, true, true, true);
  11935. // Restore state
  11936. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  11937. if (curScissor === true) {
  11938. gl.enable(gl.SCISSOR_TEST);
  11939. }
  11940. else {
  11941. gl.disable(gl.SCISSOR_TEST);
  11942. }
  11943. };
  11944. /**
  11945. * Set the WebGL's viewport
  11946. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  11947. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  11948. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  11949. */
  11950. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  11951. var width = requiredWidth || this.getRenderWidth();
  11952. var height = requiredHeight || this.getRenderHeight();
  11953. var x = viewport.x || 0;
  11954. var y = viewport.y || 0;
  11955. this._cachedViewport = viewport;
  11956. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  11957. };
  11958. /**
  11959. * Directly set the WebGL Viewport
  11960. * The x, y, width & height are directly passed to the WebGL call
  11961. * @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.
  11962. */
  11963. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  11964. var currentViewport = this._cachedViewport;
  11965. this._cachedViewport = null;
  11966. this._gl.viewport(x, y, width, height);
  11967. return currentViewport;
  11968. };
  11969. Engine.prototype.beginFrame = function () {
  11970. this.onBeginFrameObservable.notifyObservers(this);
  11971. this._measureFps();
  11972. };
  11973. Engine.prototype.endFrame = function () {
  11974. //force a flush in case we are using a bad OS.
  11975. if (this._badOS) {
  11976. this.flushFramebuffer();
  11977. }
  11978. //submit frame to the vr device, if enabled
  11979. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11980. // TODO: We should only submit the frame if we read frameData successfully.
  11981. this._vrDisplay.submitFrame();
  11982. }
  11983. this.onEndFrameObservable.notifyObservers(this);
  11984. };
  11985. /**
  11986. * resize the view according to the canvas' size.
  11987. * @example
  11988. * window.addEventListener("resize", function () {
  11989. * engine.resize();
  11990. * });
  11991. */
  11992. Engine.prototype.resize = function () {
  11993. // We're not resizing the size of the canvas while in VR mode & presenting
  11994. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  11995. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  11996. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  11997. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  11998. }
  11999. };
  12000. /**
  12001. * force a specific size of the canvas
  12002. * @param {number} width - the new canvas' width
  12003. * @param {number} height - the new canvas' height
  12004. */
  12005. Engine.prototype.setSize = function (width, height) {
  12006. if (!this._renderingCanvas) {
  12007. return;
  12008. }
  12009. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  12010. return;
  12011. }
  12012. this._renderingCanvas.width = width;
  12013. this._renderingCanvas.height = height;
  12014. for (var index = 0; index < this.scenes.length; index++) {
  12015. var scene = this.scenes[index];
  12016. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  12017. var cam = scene.cameras[camIndex];
  12018. cam._currentRenderId = 0;
  12019. }
  12020. }
  12021. if (this.onResizeObservable.hasObservers) {
  12022. this.onResizeObservable.notifyObservers(this);
  12023. }
  12024. };
  12025. // WebVR functions
  12026. Engine.prototype.isVRDevicePresent = function () {
  12027. return !!this._vrDisplay;
  12028. };
  12029. Engine.prototype.getVRDevice = function () {
  12030. return this._vrDisplay;
  12031. };
  12032. /**
  12033. * Initializes a webVR display and starts listening to display change events.
  12034. * The onVRDisplayChangedObservable will be notified upon these changes.
  12035. * @returns The onVRDisplayChangedObservable.
  12036. */
  12037. Engine.prototype.initWebVR = function () {
  12038. this.initWebVRAsync();
  12039. return this.onVRDisplayChangedObservable;
  12040. };
  12041. /**
  12042. * Initializes a webVR display and starts listening to display change events.
  12043. * The onVRDisplayChangedObservable will be notified upon these changes.
  12044. * @returns A promise containing a VRDisplay and if vr is supported.
  12045. */
  12046. Engine.prototype.initWebVRAsync = function () {
  12047. var _this = this;
  12048. var notifyObservers = function () {
  12049. var eventArgs = {
  12050. vrDisplay: _this._vrDisplay,
  12051. vrSupported: _this._vrSupported
  12052. };
  12053. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  12054. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  12055. };
  12056. if (!this._onVrDisplayConnect) {
  12057. this._onVrDisplayConnect = function (event) {
  12058. _this._vrDisplay = event.display;
  12059. notifyObservers();
  12060. };
  12061. this._onVrDisplayDisconnect = function () {
  12062. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  12063. _this._vrDisplay = undefined;
  12064. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  12065. notifyObservers();
  12066. };
  12067. this._onVrDisplayPresentChange = function () {
  12068. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  12069. };
  12070. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  12071. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  12072. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  12073. }
  12074. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  12075. this._webVRInitPromise.then(notifyObservers);
  12076. return this._webVRInitPromise;
  12077. };
  12078. Engine.prototype.enableVR = function () {
  12079. var _this = this;
  12080. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  12081. var onResolved = function () {
  12082. _this.onVRRequestPresentComplete.notifyObservers(true);
  12083. _this._onVRFullScreenTriggered();
  12084. };
  12085. var onRejected = function () {
  12086. _this.onVRRequestPresentComplete.notifyObservers(false);
  12087. };
  12088. this.onVRRequestPresentStart.notifyObservers(this);
  12089. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  12090. }
  12091. };
  12092. Engine.prototype.disableVR = function () {
  12093. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12094. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  12095. }
  12096. };
  12097. Engine.prototype._getVRDisplaysAsync = function () {
  12098. var _this = this;
  12099. return new Promise(function (res, rej) {
  12100. if (navigator.getVRDisplays) {
  12101. navigator.getVRDisplays().then(function (devices) {
  12102. _this._vrSupported = true;
  12103. // note that devices may actually be an empty array. This is fine;
  12104. // we expect this._vrDisplay to be undefined in this case.
  12105. _this._vrDisplay = devices[0];
  12106. res({
  12107. vrDisplay: _this._vrDisplay,
  12108. vrSupported: _this._vrSupported
  12109. });
  12110. });
  12111. }
  12112. else {
  12113. _this._vrDisplay = undefined;
  12114. _this._vrSupported = false;
  12115. res({
  12116. vrDisplay: _this._vrDisplay,
  12117. vrSupported: _this._vrSupported
  12118. });
  12119. }
  12120. });
  12121. };
  12122. /**
  12123. * Binds the frame buffer to the specified texture.
  12124. * @param texture The texture to render to or null for the default canvas
  12125. * @param faceIndex The face of the texture to render to in case of cube texture
  12126. * @param requiredWidth The width of the target to render to
  12127. * @param requiredHeight The height of the target to render to
  12128. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  12129. * @param depthStencilTexture The depth stencil texture to use to render
  12130. */
  12131. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture) {
  12132. if (this._currentRenderTarget) {
  12133. this.unBindFramebuffer(this._currentRenderTarget);
  12134. }
  12135. this._currentRenderTarget = texture;
  12136. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  12137. var gl = this._gl;
  12138. if (texture.isCube) {
  12139. if (faceIndex === undefined) {
  12140. faceIndex = 0;
  12141. }
  12142. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  12143. if (depthStencilTexture) {
  12144. if (depthStencilTexture._generateStencilBuffer) {
  12145. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  12146. }
  12147. else {
  12148. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  12149. }
  12150. }
  12151. }
  12152. if (this._cachedViewport && !forceFullscreenViewport) {
  12153. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  12154. }
  12155. else {
  12156. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  12157. }
  12158. this.wipeCaches();
  12159. };
  12160. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  12161. if (this._currentFramebuffer !== framebuffer) {
  12162. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  12163. this._currentFramebuffer = framebuffer;
  12164. }
  12165. };
  12166. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  12167. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12168. this._currentRenderTarget = null;
  12169. // If MSAA, we need to bitblt back to main texture
  12170. var gl = this._gl;
  12171. if (texture._MSAAFramebuffer) {
  12172. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  12173. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  12174. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12175. }
  12176. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12177. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12178. gl.generateMipmap(gl.TEXTURE_2D);
  12179. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12180. }
  12181. if (onBeforeUnbind) {
  12182. if (texture._MSAAFramebuffer) {
  12183. // Bind the correct framebuffer
  12184. this.bindUnboundFramebuffer(texture._framebuffer);
  12185. }
  12186. onBeforeUnbind();
  12187. }
  12188. this.bindUnboundFramebuffer(null);
  12189. };
  12190. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  12191. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12192. this._currentRenderTarget = null;
  12193. // If MSAA, we need to bitblt back to main texture
  12194. var gl = this._gl;
  12195. if (textures[0]._MSAAFramebuffer) {
  12196. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  12197. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  12198. var attachments = textures[0]._attachments;
  12199. if (!attachments) {
  12200. attachments = new Array(textures.length);
  12201. textures[0]._attachments = attachments;
  12202. }
  12203. for (var i = 0; i < textures.length; i++) {
  12204. var texture = textures[i];
  12205. for (var j = 0; j < attachments.length; j++) {
  12206. attachments[j] = gl.NONE;
  12207. }
  12208. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12209. gl.readBuffer(attachments[i]);
  12210. gl.drawBuffers(attachments);
  12211. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12212. }
  12213. for (var i = 0; i < attachments.length; i++) {
  12214. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12215. }
  12216. gl.drawBuffers(attachments);
  12217. }
  12218. for (var i = 0; i < textures.length; i++) {
  12219. var texture = textures[i];
  12220. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12221. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  12222. gl.generateMipmap(gl.TEXTURE_2D);
  12223. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12224. }
  12225. }
  12226. if (onBeforeUnbind) {
  12227. if (textures[0]._MSAAFramebuffer) {
  12228. // Bind the correct framebuffer
  12229. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  12230. }
  12231. onBeforeUnbind();
  12232. }
  12233. this.bindUnboundFramebuffer(null);
  12234. };
  12235. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  12236. if (texture.generateMipMaps) {
  12237. var gl = this._gl;
  12238. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12239. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12240. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12241. }
  12242. };
  12243. Engine.prototype.flushFramebuffer = function () {
  12244. this._gl.flush();
  12245. };
  12246. Engine.prototype.restoreDefaultFramebuffer = function () {
  12247. if (this._currentRenderTarget) {
  12248. this.unBindFramebuffer(this._currentRenderTarget);
  12249. }
  12250. else {
  12251. this.bindUnboundFramebuffer(null);
  12252. }
  12253. if (this._cachedViewport) {
  12254. this.setViewport(this._cachedViewport);
  12255. }
  12256. this.wipeCaches();
  12257. };
  12258. // UBOs
  12259. Engine.prototype.createUniformBuffer = function (elements) {
  12260. var ubo = this._gl.createBuffer();
  12261. if (!ubo) {
  12262. throw new Error("Unable to create uniform buffer");
  12263. }
  12264. this.bindUniformBuffer(ubo);
  12265. if (elements instanceof Float32Array) {
  12266. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  12267. }
  12268. else {
  12269. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  12270. }
  12271. this.bindUniformBuffer(null);
  12272. ubo.references = 1;
  12273. return ubo;
  12274. };
  12275. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  12276. var ubo = this._gl.createBuffer();
  12277. if (!ubo) {
  12278. throw new Error("Unable to create dynamic uniform buffer");
  12279. }
  12280. this.bindUniformBuffer(ubo);
  12281. if (elements instanceof Float32Array) {
  12282. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  12283. }
  12284. else {
  12285. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  12286. }
  12287. this.bindUniformBuffer(null);
  12288. ubo.references = 1;
  12289. return ubo;
  12290. };
  12291. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  12292. this.bindUniformBuffer(uniformBuffer);
  12293. if (offset === undefined) {
  12294. offset = 0;
  12295. }
  12296. if (count === undefined) {
  12297. if (elements instanceof Float32Array) {
  12298. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  12299. }
  12300. else {
  12301. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  12302. }
  12303. }
  12304. else {
  12305. if (elements instanceof Float32Array) {
  12306. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  12307. }
  12308. else {
  12309. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  12310. }
  12311. }
  12312. this.bindUniformBuffer(null);
  12313. };
  12314. // VBOs
  12315. Engine.prototype._resetVertexBufferBinding = function () {
  12316. this.bindArrayBuffer(null);
  12317. this._cachedVertexBuffers = null;
  12318. };
  12319. Engine.prototype.createVertexBuffer = function (vertices) {
  12320. var vbo = this._gl.createBuffer();
  12321. if (!vbo) {
  12322. throw new Error("Unable to create vertex buffer");
  12323. }
  12324. this.bindArrayBuffer(vbo);
  12325. if (vertices instanceof Float32Array) {
  12326. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  12327. }
  12328. else {
  12329. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  12330. }
  12331. this._resetVertexBufferBinding();
  12332. vbo.references = 1;
  12333. return vbo;
  12334. };
  12335. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  12336. var vbo = this._gl.createBuffer();
  12337. if (!vbo) {
  12338. throw new Error("Unable to create dynamic vertex buffer");
  12339. }
  12340. this.bindArrayBuffer(vbo);
  12341. if (vertices instanceof Float32Array) {
  12342. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  12343. }
  12344. else {
  12345. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  12346. }
  12347. this._resetVertexBufferBinding();
  12348. vbo.references = 1;
  12349. return vbo;
  12350. };
  12351. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  12352. if (offset === void 0) { offset = 0; }
  12353. // Force cache update
  12354. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  12355. this.bindIndexBuffer(indexBuffer);
  12356. var arrayBuffer;
  12357. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  12358. arrayBuffer = indices;
  12359. }
  12360. else {
  12361. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  12362. }
  12363. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  12364. this._resetIndexBufferBinding();
  12365. };
  12366. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  12367. this.bindArrayBuffer(vertexBuffer);
  12368. if (offset === undefined) {
  12369. offset = 0;
  12370. }
  12371. if (count === undefined) {
  12372. if (vertices instanceof Float32Array) {
  12373. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  12374. }
  12375. else {
  12376. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  12377. }
  12378. }
  12379. else {
  12380. if (vertices instanceof Float32Array) {
  12381. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  12382. }
  12383. else {
  12384. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  12385. }
  12386. }
  12387. this._resetVertexBufferBinding();
  12388. };
  12389. Engine.prototype._resetIndexBufferBinding = function () {
  12390. this.bindIndexBuffer(null);
  12391. this._cachedIndexBuffer = null;
  12392. };
  12393. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  12394. var vbo = this._gl.createBuffer();
  12395. if (!vbo) {
  12396. throw new Error("Unable to create index buffer");
  12397. }
  12398. this.bindIndexBuffer(vbo);
  12399. // Check for 32 bits indices
  12400. var arrayBuffer;
  12401. var need32Bits = false;
  12402. if (indices instanceof Uint16Array) {
  12403. arrayBuffer = indices;
  12404. }
  12405. else {
  12406. //check 32 bit support
  12407. if (this._caps.uintIndices) {
  12408. if (indices instanceof Uint32Array) {
  12409. arrayBuffer = indices;
  12410. need32Bits = true;
  12411. }
  12412. else {
  12413. //number[] or Int32Array, check if 32 bit is necessary
  12414. for (var index = 0; index < indices.length; index++) {
  12415. if (indices[index] > 65535) {
  12416. need32Bits = true;
  12417. break;
  12418. }
  12419. }
  12420. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  12421. }
  12422. }
  12423. else {
  12424. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  12425. arrayBuffer = new Uint16Array(indices);
  12426. }
  12427. }
  12428. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  12429. this._resetIndexBufferBinding();
  12430. vbo.references = 1;
  12431. vbo.is32Bits = need32Bits;
  12432. return vbo;
  12433. };
  12434. Engine.prototype.bindArrayBuffer = function (buffer) {
  12435. if (!this._vaoRecordInProgress) {
  12436. this._unbindVertexArrayObject();
  12437. }
  12438. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  12439. };
  12440. Engine.prototype.bindUniformBuffer = function (buffer) {
  12441. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  12442. };
  12443. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  12444. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  12445. };
  12446. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  12447. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  12448. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  12449. };
  12450. ;
  12451. Engine.prototype.bindIndexBuffer = function (buffer) {
  12452. if (!this._vaoRecordInProgress) {
  12453. this._unbindVertexArrayObject();
  12454. }
  12455. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  12456. };
  12457. Engine.prototype.bindBuffer = function (buffer, target) {
  12458. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  12459. this._gl.bindBuffer(target, buffer);
  12460. this._currentBoundBuffer[target] = buffer;
  12461. }
  12462. };
  12463. Engine.prototype.updateArrayBuffer = function (data) {
  12464. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12465. };
  12466. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  12467. var pointer = this._currentBufferPointers[indx];
  12468. var changed = false;
  12469. if (!pointer.active) {
  12470. changed = true;
  12471. pointer.active = true;
  12472. pointer.index = indx;
  12473. pointer.size = size;
  12474. pointer.type = type;
  12475. pointer.normalized = normalized;
  12476. pointer.stride = stride;
  12477. pointer.offset = offset;
  12478. pointer.buffer = buffer;
  12479. }
  12480. else {
  12481. if (pointer.buffer !== buffer) {
  12482. pointer.buffer = buffer;
  12483. changed = true;
  12484. }
  12485. if (pointer.size !== size) {
  12486. pointer.size = size;
  12487. changed = true;
  12488. }
  12489. if (pointer.type !== type) {
  12490. pointer.type = type;
  12491. changed = true;
  12492. }
  12493. if (pointer.normalized !== normalized) {
  12494. pointer.normalized = normalized;
  12495. changed = true;
  12496. }
  12497. if (pointer.stride !== stride) {
  12498. pointer.stride = stride;
  12499. changed = true;
  12500. }
  12501. if (pointer.offset !== offset) {
  12502. pointer.offset = offset;
  12503. changed = true;
  12504. }
  12505. }
  12506. if (changed || this._vaoRecordInProgress) {
  12507. this.bindArrayBuffer(buffer);
  12508. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  12509. }
  12510. };
  12511. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  12512. if (indexBuffer == null) {
  12513. return;
  12514. }
  12515. if (this._cachedIndexBuffer !== indexBuffer) {
  12516. this._cachedIndexBuffer = indexBuffer;
  12517. this.bindIndexBuffer(indexBuffer);
  12518. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  12519. }
  12520. };
  12521. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  12522. var attributes = effect.getAttributesNames();
  12523. if (!this._vaoRecordInProgress) {
  12524. this._unbindVertexArrayObject();
  12525. }
  12526. this.unbindAllAttributes();
  12527. for (var index = 0; index < attributes.length; index++) {
  12528. var order = effect.getAttributeLocation(index);
  12529. if (order >= 0) {
  12530. var vertexBuffer = vertexBuffers[attributes[index]];
  12531. if (!vertexBuffer) {
  12532. continue;
  12533. }
  12534. this._gl.enableVertexAttribArray(order);
  12535. if (!this._vaoRecordInProgress) {
  12536. this._vertexAttribArraysEnabled[order] = true;
  12537. }
  12538. var buffer = vertexBuffer.getBuffer();
  12539. if (buffer) {
  12540. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  12541. if (vertexBuffer.getIsInstanced()) {
  12542. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  12543. if (!this._vaoRecordInProgress) {
  12544. this._currentInstanceLocations.push(order);
  12545. this._currentInstanceBuffers.push(buffer);
  12546. }
  12547. }
  12548. }
  12549. }
  12550. }
  12551. };
  12552. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  12553. var vao = this._gl.createVertexArray();
  12554. this._vaoRecordInProgress = true;
  12555. this._gl.bindVertexArray(vao);
  12556. this._mustWipeVertexAttributes = true;
  12557. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12558. this.bindIndexBuffer(indexBuffer);
  12559. this._vaoRecordInProgress = false;
  12560. this._gl.bindVertexArray(null);
  12561. return vao;
  12562. };
  12563. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  12564. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  12565. this._cachedVertexArrayObject = vertexArrayObject;
  12566. this._gl.bindVertexArray(vertexArrayObject);
  12567. this._cachedVertexBuffers = null;
  12568. this._cachedIndexBuffer = null;
  12569. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  12570. this._mustWipeVertexAttributes = true;
  12571. }
  12572. };
  12573. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  12574. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  12575. this._cachedVertexBuffers = vertexBuffer;
  12576. this._cachedEffectForVertexBuffers = effect;
  12577. var attributesCount = effect.getAttributesCount();
  12578. this._unbindVertexArrayObject();
  12579. this.unbindAllAttributes();
  12580. var offset = 0;
  12581. for (var index = 0; index < attributesCount; index++) {
  12582. if (index < vertexDeclaration.length) {
  12583. var order = effect.getAttributeLocation(index);
  12584. if (order >= 0) {
  12585. this._gl.enableVertexAttribArray(order);
  12586. this._vertexAttribArraysEnabled[order] = true;
  12587. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  12588. }
  12589. offset += vertexDeclaration[index] * 4;
  12590. }
  12591. }
  12592. }
  12593. this._bindIndexBufferWithCache(indexBuffer);
  12594. };
  12595. Engine.prototype._unbindVertexArrayObject = function () {
  12596. if (!this._cachedVertexArrayObject) {
  12597. return;
  12598. }
  12599. this._cachedVertexArrayObject = null;
  12600. this._gl.bindVertexArray(null);
  12601. };
  12602. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  12603. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  12604. this._cachedVertexBuffers = vertexBuffers;
  12605. this._cachedEffectForVertexBuffers = effect;
  12606. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12607. }
  12608. this._bindIndexBufferWithCache(indexBuffer);
  12609. };
  12610. Engine.prototype.unbindInstanceAttributes = function () {
  12611. var boundBuffer;
  12612. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  12613. var instancesBuffer = this._currentInstanceBuffers[i];
  12614. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  12615. boundBuffer = instancesBuffer;
  12616. this.bindArrayBuffer(instancesBuffer);
  12617. }
  12618. var offsetLocation = this._currentInstanceLocations[i];
  12619. this._gl.vertexAttribDivisor(offsetLocation, 0);
  12620. }
  12621. this._currentInstanceBuffers.length = 0;
  12622. this._currentInstanceLocations.length = 0;
  12623. };
  12624. Engine.prototype.releaseVertexArrayObject = function (vao) {
  12625. this._gl.deleteVertexArray(vao);
  12626. };
  12627. Engine.prototype._releaseBuffer = function (buffer) {
  12628. buffer.references--;
  12629. if (buffer.references === 0) {
  12630. this._gl.deleteBuffer(buffer);
  12631. return true;
  12632. }
  12633. return false;
  12634. };
  12635. Engine.prototype.createInstancesBuffer = function (capacity) {
  12636. var buffer = this._gl.createBuffer();
  12637. if (!buffer) {
  12638. throw new Error("Unable to create instance buffer");
  12639. }
  12640. buffer.capacity = capacity;
  12641. this.bindArrayBuffer(buffer);
  12642. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  12643. return buffer;
  12644. };
  12645. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  12646. this._gl.deleteBuffer(buffer);
  12647. };
  12648. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  12649. this.bindArrayBuffer(instancesBuffer);
  12650. if (data) {
  12651. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12652. }
  12653. if (offsetLocations[0].index !== undefined) {
  12654. var stride = 0;
  12655. for (var i = 0; i < offsetLocations.length; i++) {
  12656. var ai = offsetLocations[i];
  12657. stride += ai.attributeSize * 4;
  12658. }
  12659. for (var i = 0; i < offsetLocations.length; i++) {
  12660. var ai = offsetLocations[i];
  12661. if (!this._vertexAttribArraysEnabled[ai.index]) {
  12662. this._gl.enableVertexAttribArray(ai.index);
  12663. this._vertexAttribArraysEnabled[ai.index] = true;
  12664. }
  12665. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  12666. this._gl.vertexAttribDivisor(ai.index, 1);
  12667. this._currentInstanceLocations.push(ai.index);
  12668. this._currentInstanceBuffers.push(instancesBuffer);
  12669. }
  12670. }
  12671. else {
  12672. for (var index = 0; index < 4; index++) {
  12673. var offsetLocation = offsetLocations[index];
  12674. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  12675. this._gl.enableVertexAttribArray(offsetLocation);
  12676. this._vertexAttribArraysEnabled[offsetLocation] = true;
  12677. }
  12678. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  12679. this._gl.vertexAttribDivisor(offsetLocation, 1);
  12680. this._currentInstanceLocations.push(offsetLocation);
  12681. this._currentInstanceBuffers.push(instancesBuffer);
  12682. }
  12683. }
  12684. };
  12685. Engine.prototype.applyStates = function () {
  12686. this._depthCullingState.apply(this._gl);
  12687. this._stencilState.apply(this._gl);
  12688. this._alphaState.apply(this._gl);
  12689. };
  12690. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  12691. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  12692. };
  12693. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  12694. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  12695. };
  12696. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  12697. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  12698. };
  12699. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  12700. // Apply states
  12701. this.applyStates();
  12702. this._drawCalls.addCount(1, false);
  12703. // Render
  12704. var drawMode = this._drawMode(fillMode);
  12705. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  12706. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  12707. if (instancesCount) {
  12708. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  12709. }
  12710. else {
  12711. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  12712. }
  12713. };
  12714. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  12715. // Apply states
  12716. this.applyStates();
  12717. this._drawCalls.addCount(1, false);
  12718. var drawMode = this._drawMode(fillMode);
  12719. if (instancesCount) {
  12720. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  12721. }
  12722. else {
  12723. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  12724. }
  12725. };
  12726. Engine.prototype._drawMode = function (fillMode) {
  12727. switch (fillMode) {
  12728. // Triangle views
  12729. case BABYLON.Material.TriangleFillMode:
  12730. return this._gl.TRIANGLES;
  12731. case BABYLON.Material.PointFillMode:
  12732. return this._gl.POINTS;
  12733. case BABYLON.Material.WireFrameFillMode:
  12734. return this._gl.LINES;
  12735. // Draw modes
  12736. case BABYLON.Material.PointListDrawMode:
  12737. return this._gl.POINTS;
  12738. case BABYLON.Material.LineListDrawMode:
  12739. return this._gl.LINES;
  12740. case BABYLON.Material.LineLoopDrawMode:
  12741. return this._gl.LINE_LOOP;
  12742. case BABYLON.Material.LineStripDrawMode:
  12743. return this._gl.LINE_STRIP;
  12744. case BABYLON.Material.TriangleStripDrawMode:
  12745. return this._gl.TRIANGLE_STRIP;
  12746. case BABYLON.Material.TriangleFanDrawMode:
  12747. return this._gl.TRIANGLE_FAN;
  12748. default:
  12749. return this._gl.TRIANGLES;
  12750. }
  12751. };
  12752. // Shaders
  12753. Engine.prototype._releaseEffect = function (effect) {
  12754. if (this._compiledEffects[effect._key]) {
  12755. delete this._compiledEffects[effect._key];
  12756. this._deleteProgram(effect.getProgram());
  12757. }
  12758. };
  12759. Engine.prototype._deleteProgram = function (program) {
  12760. if (program) {
  12761. program.__SPECTOR_rebuildProgram = null;
  12762. if (program.transformFeedback) {
  12763. this.deleteTransformFeedback(program.transformFeedback);
  12764. program.transformFeedback = null;
  12765. }
  12766. this._gl.deleteProgram(program);
  12767. }
  12768. };
  12769. /**
  12770. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  12771. * @param samplers An array of string used to represent textures
  12772. */
  12773. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  12774. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  12775. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  12776. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  12777. if (this._compiledEffects[name]) {
  12778. var compiledEffect = this._compiledEffects[name];
  12779. if (onCompiled && compiledEffect.isReady()) {
  12780. onCompiled(compiledEffect);
  12781. }
  12782. return compiledEffect;
  12783. }
  12784. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  12785. effect._key = name;
  12786. this._compiledEffects[name] = effect;
  12787. return effect;
  12788. };
  12789. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  12790. if (uniformsNames === void 0) { uniformsNames = []; }
  12791. if (samplers === void 0) { samplers = []; }
  12792. if (defines === void 0) { defines = ""; }
  12793. return this.createEffect({
  12794. vertex: "particles",
  12795. fragmentElement: fragmentName
  12796. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  12797. };
  12798. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  12799. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12800. context = context || this._gl;
  12801. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  12802. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  12803. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12804. };
  12805. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  12806. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12807. context = context || this._gl;
  12808. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  12809. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  12810. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  12811. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  12812. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12813. this.onAfterShaderCompilationObservable.notifyObservers(this);
  12814. return program;
  12815. };
  12816. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  12817. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12818. var shaderProgram = context.createProgram();
  12819. if (!shaderProgram) {
  12820. throw new Error("Unable to create program");
  12821. }
  12822. context.attachShader(shaderProgram, vertexShader);
  12823. context.attachShader(shaderProgram, fragmentShader);
  12824. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12825. var transformFeedback = this.createTransformFeedback();
  12826. this.bindTransformFeedback(transformFeedback);
  12827. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  12828. shaderProgram.transformFeedback = transformFeedback;
  12829. }
  12830. context.linkProgram(shaderProgram);
  12831. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12832. this.bindTransformFeedback(null);
  12833. }
  12834. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  12835. if (!linked) {
  12836. context.validateProgram(shaderProgram);
  12837. var error = context.getProgramInfoLog(shaderProgram);
  12838. if (error) {
  12839. throw new Error(error);
  12840. }
  12841. }
  12842. context.deleteShader(vertexShader);
  12843. context.deleteShader(fragmentShader);
  12844. return shaderProgram;
  12845. };
  12846. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  12847. var results = new Array();
  12848. for (var index = 0; index < uniformsNames.length; index++) {
  12849. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  12850. }
  12851. return results;
  12852. };
  12853. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  12854. var results = [];
  12855. for (var index = 0; index < attributesNames.length; index++) {
  12856. try {
  12857. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  12858. }
  12859. catch (e) {
  12860. results.push(-1);
  12861. }
  12862. }
  12863. return results;
  12864. };
  12865. Engine.prototype.enableEffect = function (effect) {
  12866. if (!effect) {
  12867. return;
  12868. }
  12869. // Use program
  12870. this.bindSamplers(effect);
  12871. this._currentEffect = effect;
  12872. if (effect.onBind) {
  12873. effect.onBind(effect);
  12874. }
  12875. effect.onBindObservable.notifyObservers(effect);
  12876. };
  12877. Engine.prototype.setIntArray = function (uniform, array) {
  12878. if (!uniform)
  12879. return;
  12880. this._gl.uniform1iv(uniform, array);
  12881. };
  12882. Engine.prototype.setIntArray2 = function (uniform, array) {
  12883. if (!uniform || array.length % 2 !== 0)
  12884. return;
  12885. this._gl.uniform2iv(uniform, array);
  12886. };
  12887. Engine.prototype.setIntArray3 = function (uniform, array) {
  12888. if (!uniform || array.length % 3 !== 0)
  12889. return;
  12890. this._gl.uniform3iv(uniform, array);
  12891. };
  12892. Engine.prototype.setIntArray4 = function (uniform, array) {
  12893. if (!uniform || array.length % 4 !== 0)
  12894. return;
  12895. this._gl.uniform4iv(uniform, array);
  12896. };
  12897. Engine.prototype.setFloatArray = function (uniform, array) {
  12898. if (!uniform)
  12899. return;
  12900. this._gl.uniform1fv(uniform, array);
  12901. };
  12902. Engine.prototype.setFloatArray2 = function (uniform, array) {
  12903. if (!uniform || array.length % 2 !== 0)
  12904. return;
  12905. this._gl.uniform2fv(uniform, array);
  12906. };
  12907. Engine.prototype.setFloatArray3 = function (uniform, array) {
  12908. if (!uniform || array.length % 3 !== 0)
  12909. return;
  12910. this._gl.uniform3fv(uniform, array);
  12911. };
  12912. Engine.prototype.setFloatArray4 = function (uniform, array) {
  12913. if (!uniform || array.length % 4 !== 0)
  12914. return;
  12915. this._gl.uniform4fv(uniform, array);
  12916. };
  12917. Engine.prototype.setArray = function (uniform, array) {
  12918. if (!uniform)
  12919. return;
  12920. this._gl.uniform1fv(uniform, array);
  12921. };
  12922. Engine.prototype.setArray2 = function (uniform, array) {
  12923. if (!uniform || array.length % 2 !== 0)
  12924. return;
  12925. this._gl.uniform2fv(uniform, array);
  12926. };
  12927. Engine.prototype.setArray3 = function (uniform, array) {
  12928. if (!uniform || array.length % 3 !== 0)
  12929. return;
  12930. this._gl.uniform3fv(uniform, array);
  12931. };
  12932. Engine.prototype.setArray4 = function (uniform, array) {
  12933. if (!uniform || array.length % 4 !== 0)
  12934. return;
  12935. this._gl.uniform4fv(uniform, array);
  12936. };
  12937. Engine.prototype.setMatrices = function (uniform, matrices) {
  12938. if (!uniform)
  12939. return;
  12940. this._gl.uniformMatrix4fv(uniform, false, matrices);
  12941. };
  12942. Engine.prototype.setMatrix = function (uniform, matrix) {
  12943. if (!uniform)
  12944. return;
  12945. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  12946. };
  12947. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  12948. if (!uniform)
  12949. return;
  12950. this._gl.uniformMatrix3fv(uniform, false, matrix);
  12951. };
  12952. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  12953. if (!uniform)
  12954. return;
  12955. this._gl.uniformMatrix2fv(uniform, false, matrix);
  12956. };
  12957. Engine.prototype.setInt = function (uniform, value) {
  12958. if (!uniform)
  12959. return;
  12960. this._gl.uniform1i(uniform, value);
  12961. };
  12962. Engine.prototype.setFloat = function (uniform, value) {
  12963. if (!uniform)
  12964. return;
  12965. this._gl.uniform1f(uniform, value);
  12966. };
  12967. Engine.prototype.setFloat2 = function (uniform, x, y) {
  12968. if (!uniform)
  12969. return;
  12970. this._gl.uniform2f(uniform, x, y);
  12971. };
  12972. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  12973. if (!uniform)
  12974. return;
  12975. this._gl.uniform3f(uniform, x, y, z);
  12976. };
  12977. Engine.prototype.setBool = function (uniform, bool) {
  12978. if (!uniform)
  12979. return;
  12980. this._gl.uniform1i(uniform, bool);
  12981. };
  12982. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  12983. if (!uniform)
  12984. return;
  12985. this._gl.uniform4f(uniform, x, y, z, w);
  12986. };
  12987. Engine.prototype.setColor3 = function (uniform, color3) {
  12988. if (!uniform)
  12989. return;
  12990. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  12991. };
  12992. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  12993. if (!uniform)
  12994. return;
  12995. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  12996. };
  12997. /**
  12998. * Sets a Color4 on a uniform variable
  12999. * @param uniform defines the uniform location
  13000. * @param color4 defines the value to be set
  13001. */
  13002. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  13003. if (!uniform)
  13004. return;
  13005. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  13006. };
  13007. // States
  13008. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  13009. if (zOffset === void 0) { zOffset = 0; }
  13010. if (reverseSide === void 0) { reverseSide = false; }
  13011. // Culling
  13012. if (this._depthCullingState.cull !== culling || force) {
  13013. this._depthCullingState.cull = culling;
  13014. }
  13015. // Cull face
  13016. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  13017. if (this._depthCullingState.cullFace !== cullFace || force) {
  13018. this._depthCullingState.cullFace = cullFace;
  13019. }
  13020. // Z offset
  13021. this.setZOffset(zOffset);
  13022. // Front face
  13023. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  13024. if (this._depthCullingState.frontFace !== frontFace || force) {
  13025. this._depthCullingState.frontFace = frontFace;
  13026. }
  13027. };
  13028. Engine.prototype.setZOffset = function (value) {
  13029. this._depthCullingState.zOffset = value;
  13030. };
  13031. Engine.prototype.getZOffset = function () {
  13032. return this._depthCullingState.zOffset;
  13033. };
  13034. Engine.prototype.setDepthBuffer = function (enable) {
  13035. this._depthCullingState.depthTest = enable;
  13036. };
  13037. Engine.prototype.getDepthWrite = function () {
  13038. return this._depthCullingState.depthMask;
  13039. };
  13040. Engine.prototype.setDepthWrite = function (enable) {
  13041. this._depthCullingState.depthMask = enable;
  13042. };
  13043. Engine.prototype.setColorWrite = function (enable) {
  13044. this._gl.colorMask(enable, enable, enable, enable);
  13045. this._colorWrite = enable;
  13046. };
  13047. Engine.prototype.getColorWrite = function () {
  13048. return this._colorWrite;
  13049. };
  13050. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  13051. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  13052. };
  13053. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  13054. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  13055. if (this._alphaMode === mode) {
  13056. return;
  13057. }
  13058. switch (mode) {
  13059. case Engine.ALPHA_DISABLE:
  13060. this._alphaState.alphaBlend = false;
  13061. break;
  13062. case Engine.ALPHA_PREMULTIPLIED:
  13063. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  13064. this._alphaState.alphaBlend = true;
  13065. break;
  13066. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  13067. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  13068. this._alphaState.alphaBlend = true;
  13069. break;
  13070. case Engine.ALPHA_COMBINE:
  13071. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  13072. this._alphaState.alphaBlend = true;
  13073. break;
  13074. case Engine.ALPHA_ONEONE:
  13075. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  13076. this._alphaState.alphaBlend = true;
  13077. break;
  13078. case Engine.ALPHA_ADD:
  13079. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  13080. this._alphaState.alphaBlend = true;
  13081. break;
  13082. case Engine.ALPHA_SUBTRACT:
  13083. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  13084. this._alphaState.alphaBlend = true;
  13085. break;
  13086. case Engine.ALPHA_MULTIPLY:
  13087. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  13088. this._alphaState.alphaBlend = true;
  13089. break;
  13090. case Engine.ALPHA_MAXIMIZED:
  13091. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  13092. this._alphaState.alphaBlend = true;
  13093. break;
  13094. case Engine.ALPHA_INTERPOLATE:
  13095. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  13096. this._alphaState.alphaBlend = true;
  13097. break;
  13098. case Engine.ALPHA_SCREENMODE:
  13099. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  13100. this._alphaState.alphaBlend = true;
  13101. break;
  13102. }
  13103. if (!noDepthWriteChange) {
  13104. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  13105. }
  13106. this._alphaMode = mode;
  13107. };
  13108. Engine.prototype.getAlphaMode = function () {
  13109. return this._alphaMode;
  13110. };
  13111. // Textures
  13112. Engine.prototype.wipeCaches = function (bruteForce) {
  13113. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  13114. return;
  13115. }
  13116. this._currentEffect = null;
  13117. // 6/8/2017: deltakosh: Should not be required anymore.
  13118. // This message is then mostly for the future myself who will scream out loud when seeing that it was actually required :)
  13119. if (bruteForce) {
  13120. this.resetTextureCache();
  13121. this._currentProgram = null;
  13122. this._stencilState.reset();
  13123. this._depthCullingState.reset();
  13124. this.setDepthFunctionToLessOrEqual();
  13125. this._alphaState.reset();
  13126. }
  13127. this._resetVertexBufferBinding();
  13128. this._cachedIndexBuffer = null;
  13129. this._cachedEffectForVertexBuffers = null;
  13130. this._unbindVertexArrayObject();
  13131. this.bindIndexBuffer(null);
  13132. };
  13133. /**
  13134. * Set the compressed texture format to use, based on the formats you have, and the formats
  13135. * supported by the hardware / browser.
  13136. *
  13137. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  13138. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  13139. * to API arguments needed to compressed textures. This puts the burden on the container
  13140. * generator to house the arcane code for determining these for current & future formats.
  13141. *
  13142. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  13143. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  13144. *
  13145. * Note: The result of this call is not taken into account when a texture is base64.
  13146. *
  13147. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  13148. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  13149. *
  13150. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  13151. * @returns The extension selected.
  13152. */
  13153. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  13154. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  13155. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  13156. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  13157. return this._textureFormatInUse = this._texturesSupported[i];
  13158. }
  13159. }
  13160. }
  13161. // actively set format to nothing, to allow this to be called more than once
  13162. // and possibly fail the 2nd time
  13163. this._textureFormatInUse = null;
  13164. return null;
  13165. };
  13166. Engine.prototype._createTexture = function () {
  13167. var texture = this._gl.createTexture();
  13168. if (!texture) {
  13169. throw new Error("Unable to create texture");
  13170. }
  13171. return texture;
  13172. };
  13173. /**
  13174. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  13175. * @param {string} urlArg- This contains one of the following:
  13176. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  13177. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  13178. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  13179. *
  13180. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  13181. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  13182. * @param {Scene} scene- Needed for loading to the correct scene.
  13183. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  13184. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  13185. * @param {callback} onError- Optional callback to be called upon failure.
  13186. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  13187. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  13188. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  13189. *
  13190. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  13191. */
  13192. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  13193. var _this = this;
  13194. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  13195. if (onLoad === void 0) { onLoad = null; }
  13196. if (onError === void 0) { onError = null; }
  13197. if (buffer === void 0) { buffer = null; }
  13198. if (fallBack === void 0) { fallBack = null; }
  13199. if (format === void 0) { format = null; }
  13200. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  13201. var fromData = url.substr(0, 5) === "data:";
  13202. var fromBlob = url.substr(0, 5) === "blob:";
  13203. var isBase64 = fromData && url.indexOf("base64") !== -1;
  13204. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  13205. // establish the file extension, if possible
  13206. var lastDot = url.lastIndexOf('.');
  13207. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  13208. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  13209. var isTGA = (extension.indexOf(".tga") === 0);
  13210. // determine if a ktx file should be substituted
  13211. var isKTX = false;
  13212. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  13213. url = url.substring(0, lastDot) + this._textureFormatInUse;
  13214. isKTX = true;
  13215. }
  13216. if (scene) {
  13217. scene._addPendingData(texture);
  13218. }
  13219. texture.url = url;
  13220. texture.generateMipMaps = !noMipmap;
  13221. texture.samplingMode = samplingMode;
  13222. texture.invertY = invertY;
  13223. if (!this._doNotHandleContextLost) {
  13224. // Keep a link to the buffer only if we plan to handle context lost
  13225. texture._buffer = buffer;
  13226. }
  13227. var onLoadObserver = null;
  13228. if (onLoad && !fallBack) {
  13229. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  13230. }
  13231. if (!fallBack)
  13232. this._internalTexturesCache.push(texture);
  13233. var onerror = function (message, exception) {
  13234. if (scene) {
  13235. scene._removePendingData(texture);
  13236. }
  13237. if (onLoadObserver) {
  13238. texture.onLoadedObservable.remove(onLoadObserver);
  13239. }
  13240. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  13241. if (isKTX) {
  13242. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  13243. }
  13244. else if (BABYLON.Tools.UseFallbackTexture) {
  13245. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  13246. }
  13247. if (onError) {
  13248. onError(message || "Unknown error", exception);
  13249. }
  13250. };
  13251. var callback = null;
  13252. // processing for non-image formats
  13253. if (isKTX || isTGA || isDDS) {
  13254. if (isKTX) {
  13255. callback = function (data) {
  13256. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  13257. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  13258. ktx.uploadLevels(_this._gl, !noMipmap);
  13259. return false;
  13260. }, samplingMode);
  13261. };
  13262. }
  13263. else if (isTGA) {
  13264. callback = function (arrayBuffer) {
  13265. var data = new Uint8Array(arrayBuffer);
  13266. var header = BABYLON.TGATools.GetTGAHeader(data);
  13267. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  13268. BABYLON.TGATools.UploadContent(_this._gl, data);
  13269. return false;
  13270. }, samplingMode);
  13271. };
  13272. }
  13273. else if (isDDS) {
  13274. callback = function (data) {
  13275. var info = BABYLON.DDSTools.GetDDSInfo(data);
  13276. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  13277. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  13278. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  13279. return false;
  13280. }, samplingMode);
  13281. };
  13282. }
  13283. if (!buffer) {
  13284. this._loadFile(url, function (data) {
  13285. if (callback) {
  13286. callback(data);
  13287. }
  13288. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  13289. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  13290. });
  13291. }
  13292. else {
  13293. if (callback) {
  13294. callback(buffer);
  13295. }
  13296. }
  13297. // image format processing
  13298. }
  13299. else {
  13300. var onload = function (img) {
  13301. if (fromBlob && !_this._doNotHandleContextLost) {
  13302. // We need to store the image if we need to rebuild the texture
  13303. // in case of a webgl context lost
  13304. texture._buffer = img;
  13305. }
  13306. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  13307. var gl = _this._gl;
  13308. var isPot = (img.width === potWidth && img.height === potHeight);
  13309. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  13310. if (isPot) {
  13311. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  13312. return false;
  13313. }
  13314. // Using shaders to rescale because canvas.drawImage is lossy
  13315. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  13316. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  13317. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  13318. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  13319. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  13320. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13321. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13322. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  13323. _this._releaseTexture(source);
  13324. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13325. continuationCallback();
  13326. });
  13327. return true;
  13328. }, samplingMode);
  13329. };
  13330. if (!fromData || isBase64)
  13331. if (buffer instanceof HTMLImageElement) {
  13332. onload(buffer);
  13333. }
  13334. else {
  13335. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  13336. }
  13337. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  13338. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  13339. else
  13340. onload(buffer);
  13341. }
  13342. return texture;
  13343. };
  13344. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  13345. var _this = this;
  13346. var rtt = this.createRenderTargetTexture({
  13347. width: destination.width,
  13348. height: destination.height,
  13349. }, {
  13350. generateMipMaps: false,
  13351. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  13352. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  13353. generateDepthBuffer: false,
  13354. generateStencilBuffer: false
  13355. });
  13356. if (!this._rescalePostProcess) {
  13357. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  13358. }
  13359. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  13360. _this._rescalePostProcess.onApply = function (effect) {
  13361. effect._bindTexture("textureSampler", source);
  13362. };
  13363. var hostingScene = scene;
  13364. if (!hostingScene) {
  13365. hostingScene = _this.scenes[_this.scenes.length - 1];
  13366. }
  13367. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  13368. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  13369. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  13370. _this.unBindFramebuffer(rtt);
  13371. _this._releaseTexture(rtt);
  13372. if (onComplete) {
  13373. onComplete();
  13374. }
  13375. });
  13376. };
  13377. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  13378. if (compression === void 0) { compression = null; }
  13379. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  13380. if (!texture) {
  13381. return;
  13382. }
  13383. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  13384. var internalFormat = this._getInternalFormat(format);
  13385. var textureType = this._getWebGLTextureType(type);
  13386. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13387. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13388. if (!this._doNotHandleContextLost) {
  13389. texture._bufferView = data;
  13390. texture.format = format;
  13391. texture.type = type;
  13392. texture.invertY = invertY;
  13393. texture._compression = compression;
  13394. }
  13395. if (texture.width % 4 !== 0) {
  13396. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  13397. }
  13398. if (compression && data) {
  13399. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  13400. }
  13401. else {
  13402. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  13403. }
  13404. if (texture.generateMipMaps) {
  13405. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13406. }
  13407. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13408. // this.resetTextureCache();
  13409. texture.isReady = true;
  13410. };
  13411. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  13412. if (compression === void 0) { compression = null; }
  13413. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  13414. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  13415. texture.baseWidth = width;
  13416. texture.baseHeight = height;
  13417. texture.width = width;
  13418. texture.height = height;
  13419. texture.format = format;
  13420. texture.generateMipMaps = generateMipMaps;
  13421. texture.samplingMode = samplingMode;
  13422. texture.invertY = invertY;
  13423. texture._compression = compression;
  13424. texture.type = type;
  13425. if (!this._doNotHandleContextLost) {
  13426. texture._bufferView = data;
  13427. }
  13428. this.updateRawTexture(texture, data, format, invertY, compression, type);
  13429. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13430. // Filters
  13431. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  13432. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13433. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13434. if (generateMipMaps) {
  13435. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13436. }
  13437. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13438. this._internalTexturesCache.push(texture);
  13439. return texture;
  13440. };
  13441. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  13442. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  13443. texture.baseWidth = width;
  13444. texture.baseHeight = height;
  13445. if (generateMipMaps) {
  13446. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  13447. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  13448. }
  13449. // this.resetTextureCache();
  13450. texture.width = width;
  13451. texture.height = height;
  13452. texture.isReady = false;
  13453. texture.generateMipMaps = generateMipMaps;
  13454. texture.samplingMode = samplingMode;
  13455. this.updateTextureSamplingMode(samplingMode, texture);
  13456. this._internalTexturesCache.push(texture);
  13457. return texture;
  13458. };
  13459. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  13460. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  13461. if (texture.isCube) {
  13462. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13463. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13464. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13465. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13466. }
  13467. else if (texture.is3D) {
  13468. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  13469. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13470. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13471. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13472. }
  13473. else {
  13474. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13475. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13476. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13477. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13478. }
  13479. texture.samplingMode = samplingMode;
  13480. };
  13481. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  13482. if (premulAlpha === void 0) { premulAlpha = false; }
  13483. if (!texture) {
  13484. return;
  13485. }
  13486. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13487. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  13488. if (premulAlpha) {
  13489. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  13490. }
  13491. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  13492. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  13493. if (texture.generateMipMaps) {
  13494. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13495. }
  13496. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13497. if (premulAlpha) {
  13498. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  13499. }
  13500. texture.isReady = true;
  13501. };
  13502. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  13503. if (!texture || texture._isDisabled) {
  13504. return;
  13505. }
  13506. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13507. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  13508. try {
  13509. // Testing video texture support
  13510. if (this._videoTextureSupported === undefined) {
  13511. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13512. if (this._gl.getError() !== 0) {
  13513. this._videoTextureSupported = false;
  13514. }
  13515. else {
  13516. this._videoTextureSupported = true;
  13517. }
  13518. }
  13519. // Copy video through the current working canvas if video texture is not supported
  13520. if (!this._videoTextureSupported) {
  13521. if (!texture._workingCanvas) {
  13522. texture._workingCanvas = document.createElement("canvas");
  13523. var context = texture._workingCanvas.getContext("2d");
  13524. if (!context) {
  13525. throw new Error("Unable to get 2d context");
  13526. }
  13527. texture._workingContext = context;
  13528. texture._workingCanvas.width = texture.width;
  13529. texture._workingCanvas.height = texture.height;
  13530. }
  13531. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  13532. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  13533. }
  13534. else {
  13535. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13536. }
  13537. if (texture.generateMipMaps) {
  13538. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13539. }
  13540. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13541. // this.resetTextureCache();
  13542. texture.isReady = true;
  13543. }
  13544. catch (ex) {
  13545. // Something unexpected
  13546. // Let's disable the texture
  13547. texture._isDisabled = true;
  13548. }
  13549. };
  13550. /**
  13551. * Updates a depth texture Comparison Mode and Function.
  13552. * If the comparison Function is equal to 0, the mode will be set to none.
  13553. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  13554. * @param texture The texture to set the comparison function for
  13555. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  13556. */
  13557. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  13558. if (this.webGLVersion === 1) {
  13559. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  13560. return;
  13561. }
  13562. var gl = this._gl;
  13563. if (texture.isCube) {
  13564. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13565. if (comparisonFunction === 0) {
  13566. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13567. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13568. }
  13569. else {
  13570. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13571. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13572. }
  13573. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13574. }
  13575. else {
  13576. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13577. if (comparisonFunction === 0) {
  13578. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13579. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13580. }
  13581. else {
  13582. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13583. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13584. }
  13585. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13586. }
  13587. texture._comparisonFunction = comparisonFunction;
  13588. };
  13589. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  13590. var width = size.width || size;
  13591. var height = size.height || size;
  13592. internalTexture.baseWidth = width;
  13593. internalTexture.baseHeight = height;
  13594. internalTexture.width = width;
  13595. internalTexture.height = height;
  13596. internalTexture.isReady = true;
  13597. internalTexture.samples = 1;
  13598. internalTexture.generateMipMaps = false;
  13599. internalTexture._generateDepthBuffer = true;
  13600. internalTexture._generateStencilBuffer = generateStencil;
  13601. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13602. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13603. internalTexture._comparisonFunction = comparisonFunction;
  13604. var gl = this._gl;
  13605. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  13606. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  13607. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  13608. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  13609. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13610. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13611. if (comparisonFunction === 0) {
  13612. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13613. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13614. }
  13615. else {
  13616. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13617. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13618. }
  13619. };
  13620. /**
  13621. * Creates a depth stencil texture.
  13622. * This is only available in WebGL 2 or with the depth texture extension available.
  13623. * @param size The size of face edge in the texture.
  13624. * @param options The options defining the texture.
  13625. * @returns The texture
  13626. */
  13627. Engine.prototype.createDepthStencilTexture = function (size, options) {
  13628. if (options.isCube) {
  13629. var width = size.width || size;
  13630. return this._createDepthStencilCubeTexture(width, options);
  13631. }
  13632. else {
  13633. return this._createDepthStencilTexture(size, options);
  13634. }
  13635. };
  13636. /**
  13637. * Creates a depth stencil texture.
  13638. * This is only available in WebGL 2 or with the depth texture extension available.
  13639. * @param size The size of face edge in the texture.
  13640. * @param options The options defining the texture.
  13641. * @returns The texture
  13642. */
  13643. Engine.prototype._createDepthStencilTexture = function (size, options) {
  13644. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  13645. if (!this._caps.depthTextureExtension) {
  13646. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  13647. return internalTexture;
  13648. }
  13649. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  13650. var gl = this._gl;
  13651. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  13652. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  13653. if (this.webGLVersion > 1) {
  13654. if (internalOptions.generateStencil) {
  13655. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  13656. }
  13657. else {
  13658. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13659. }
  13660. }
  13661. else {
  13662. if (internalOptions.generateStencil) {
  13663. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  13664. }
  13665. else {
  13666. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13667. }
  13668. }
  13669. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13670. return internalTexture;
  13671. };
  13672. /**
  13673. * Creates a depth stencil cube texture.
  13674. * This is only available in WebGL 2.
  13675. * @param size The size of face edge in the cube texture.
  13676. * @param options The options defining the cube texture.
  13677. * @returns The cube texture
  13678. */
  13679. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  13680. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  13681. internalTexture.isCube = true;
  13682. if (this.webGLVersion === 1) {
  13683. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  13684. return internalTexture;
  13685. }
  13686. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  13687. var gl = this._gl;
  13688. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  13689. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  13690. // Create the depth/stencil buffer
  13691. for (var face = 0; face < 6; face++) {
  13692. if (internalOptions.generateStencil) {
  13693. 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);
  13694. }
  13695. else {
  13696. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13697. }
  13698. }
  13699. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13700. return internalTexture;
  13701. };
  13702. /**
  13703. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  13704. * @param renderTarget The render target to set the frame buffer for
  13705. */
  13706. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  13707. // Create the framebuffer
  13708. var internalTexture = renderTarget.getInternalTexture();
  13709. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  13710. return;
  13711. }
  13712. var gl = this._gl;
  13713. var depthStencilTexture = renderTarget.depthStencilTexture;
  13714. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  13715. if (depthStencilTexture.isCube) {
  13716. if (depthStencilTexture._generateStencilBuffer) {
  13717. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  13718. }
  13719. else {
  13720. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  13721. }
  13722. }
  13723. else {
  13724. if (depthStencilTexture._generateStencilBuffer) {
  13725. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  13726. }
  13727. else {
  13728. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  13729. }
  13730. }
  13731. this.bindUnboundFramebuffer(null);
  13732. };
  13733. Engine.prototype.createRenderTargetTexture = function (size, options) {
  13734. var fullOptions = new RenderTargetCreationOptions();
  13735. if (options !== undefined && typeof options === "object") {
  13736. fullOptions.generateMipMaps = options.generateMipMaps;
  13737. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13738. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  13739. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  13740. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  13741. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  13742. }
  13743. else {
  13744. fullOptions.generateMipMaps = options;
  13745. fullOptions.generateDepthBuffer = true;
  13746. fullOptions.generateStencilBuffer = false;
  13747. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13748. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13749. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  13750. }
  13751. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13752. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13753. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13754. }
  13755. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13756. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13757. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13758. }
  13759. var gl = this._gl;
  13760. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13761. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13762. var width = size.width || size;
  13763. var height = size.height || size;
  13764. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  13765. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13766. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13767. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13768. }
  13769. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13770. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13771. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13772. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13773. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  13774. // Create the framebuffer
  13775. var framebuffer = gl.createFramebuffer();
  13776. this.bindUnboundFramebuffer(framebuffer);
  13777. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13778. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  13779. if (fullOptions.generateMipMaps) {
  13780. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13781. }
  13782. // Unbind
  13783. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13784. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13785. this.bindUnboundFramebuffer(null);
  13786. texture._framebuffer = framebuffer;
  13787. texture.baseWidth = width;
  13788. texture.baseHeight = height;
  13789. texture.width = width;
  13790. texture.height = height;
  13791. texture.isReady = true;
  13792. texture.samples = 1;
  13793. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  13794. texture.samplingMode = fullOptions.samplingMode;
  13795. texture.type = fullOptions.type;
  13796. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  13797. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  13798. // this.resetTextureCache();
  13799. this._internalTexturesCache.push(texture);
  13800. return texture;
  13801. };
  13802. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  13803. var generateMipMaps = false;
  13804. var generateDepthBuffer = true;
  13805. var generateStencilBuffer = false;
  13806. var generateDepthTexture = false;
  13807. var textureCount = 1;
  13808. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  13809. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13810. var types = [], samplingModes = [];
  13811. if (options !== undefined) {
  13812. generateMipMaps = options.generateMipMaps;
  13813. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13814. generateStencilBuffer = options.generateStencilBuffer;
  13815. generateDepthTexture = options.generateDepthTexture;
  13816. textureCount = options.textureCount || 1;
  13817. if (options.types) {
  13818. types = options.types;
  13819. }
  13820. if (options.samplingModes) {
  13821. samplingModes = options.samplingModes;
  13822. }
  13823. }
  13824. var gl = this._gl;
  13825. // Create the framebuffer
  13826. var framebuffer = gl.createFramebuffer();
  13827. this.bindUnboundFramebuffer(framebuffer);
  13828. var width = size.width || size;
  13829. var height = size.height || size;
  13830. var textures = [];
  13831. var attachments = [];
  13832. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  13833. for (var i = 0; i < textureCount; i++) {
  13834. var samplingMode = samplingModes[i] || defaultSamplingMode;
  13835. var type = types[i] || defaultType;
  13836. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13837. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13838. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13839. }
  13840. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13841. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13842. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13843. }
  13844. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  13845. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13846. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13847. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13848. }
  13849. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13850. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13851. textures.push(texture);
  13852. attachments.push(attachment);
  13853. gl.activeTexture(gl["TEXTURE" + i]);
  13854. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  13855. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13856. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13857. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13858. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13859. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  13860. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13861. if (generateMipMaps) {
  13862. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13863. }
  13864. // Unbind
  13865. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13866. texture._framebuffer = framebuffer;
  13867. texture._depthStencilBuffer = depthStencilBuffer;
  13868. texture.baseWidth = width;
  13869. texture.baseHeight = height;
  13870. texture.width = width;
  13871. texture.height = height;
  13872. texture.isReady = true;
  13873. texture.samples = 1;
  13874. texture.generateMipMaps = generateMipMaps;
  13875. texture.samplingMode = samplingMode;
  13876. texture.type = type;
  13877. texture._generateDepthBuffer = generateDepthBuffer;
  13878. texture._generateStencilBuffer = generateStencilBuffer;
  13879. texture._attachments = attachments;
  13880. this._internalTexturesCache.push(texture);
  13881. }
  13882. if (generateDepthTexture && this._caps.depthTextureExtension) {
  13883. // Depth texture
  13884. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13885. gl.activeTexture(gl.TEXTURE0);
  13886. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  13887. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13888. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13889. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13890. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13891. 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);
  13892. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  13893. depthTexture._framebuffer = framebuffer;
  13894. depthTexture.baseWidth = width;
  13895. depthTexture.baseHeight = height;
  13896. depthTexture.width = width;
  13897. depthTexture.height = height;
  13898. depthTexture.isReady = true;
  13899. depthTexture.samples = 1;
  13900. depthTexture.generateMipMaps = generateMipMaps;
  13901. depthTexture.samplingMode = gl.NEAREST;
  13902. depthTexture._generateDepthBuffer = generateDepthBuffer;
  13903. depthTexture._generateStencilBuffer = generateStencilBuffer;
  13904. textures.push(depthTexture);
  13905. this._internalTexturesCache.push(depthTexture);
  13906. }
  13907. gl.drawBuffers(attachments);
  13908. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13909. this.bindUnboundFramebuffer(null);
  13910. this.resetTextureCache();
  13911. return textures;
  13912. };
  13913. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  13914. if (samples === void 0) { samples = 1; }
  13915. var depthStencilBuffer = null;
  13916. var gl = this._gl;
  13917. // Create the depth/stencil buffer
  13918. if (generateStencilBuffer) {
  13919. depthStencilBuffer = gl.createRenderbuffer();
  13920. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13921. if (samples > 1) {
  13922. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  13923. }
  13924. else {
  13925. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  13926. }
  13927. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13928. }
  13929. else if (generateDepthBuffer) {
  13930. depthStencilBuffer = gl.createRenderbuffer();
  13931. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13932. if (samples > 1) {
  13933. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  13934. }
  13935. else {
  13936. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  13937. }
  13938. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13939. }
  13940. return depthStencilBuffer;
  13941. };
  13942. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  13943. if (this.webGLVersion < 2 || !texture) {
  13944. return 1;
  13945. }
  13946. if (texture.samples === samples) {
  13947. return samples;
  13948. }
  13949. var gl = this._gl;
  13950. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13951. // Dispose previous render buffers
  13952. if (texture._depthStencilBuffer) {
  13953. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  13954. texture._depthStencilBuffer = null;
  13955. }
  13956. if (texture._MSAAFramebuffer) {
  13957. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  13958. texture._MSAAFramebuffer = null;
  13959. }
  13960. if (texture._MSAARenderBuffer) {
  13961. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  13962. texture._MSAARenderBuffer = null;
  13963. }
  13964. if (samples > 1) {
  13965. var framebuffer = gl.createFramebuffer();
  13966. if (!framebuffer) {
  13967. throw new Error("Unable to create multi sampled framebuffer");
  13968. }
  13969. texture._MSAAFramebuffer = framebuffer;
  13970. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  13971. var colorRenderbuffer = gl.createRenderbuffer();
  13972. if (!colorRenderbuffer) {
  13973. throw new Error("Unable to create multi sampled framebuffer");
  13974. }
  13975. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13976. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13977. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  13978. texture._MSAARenderBuffer = colorRenderbuffer;
  13979. }
  13980. else {
  13981. this.bindUnboundFramebuffer(texture._framebuffer);
  13982. }
  13983. texture.samples = samples;
  13984. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  13985. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13986. this.bindUnboundFramebuffer(null);
  13987. return samples;
  13988. };
  13989. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  13990. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  13991. return 1;
  13992. }
  13993. if (textures[0].samples === samples) {
  13994. return samples;
  13995. }
  13996. var gl = this._gl;
  13997. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13998. // Dispose previous render buffers
  13999. if (textures[0]._depthStencilBuffer) {
  14000. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  14001. textures[0]._depthStencilBuffer = null;
  14002. }
  14003. if (textures[0]._MSAAFramebuffer) {
  14004. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  14005. textures[0]._MSAAFramebuffer = null;
  14006. }
  14007. for (var i = 0; i < textures.length; i++) {
  14008. if (textures[i]._MSAARenderBuffer) {
  14009. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  14010. textures[i]._MSAARenderBuffer = null;
  14011. }
  14012. }
  14013. if (samples > 1) {
  14014. var framebuffer = gl.createFramebuffer();
  14015. if (!framebuffer) {
  14016. throw new Error("Unable to create multi sampled framebuffer");
  14017. }
  14018. this.bindUnboundFramebuffer(framebuffer);
  14019. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  14020. var attachments = [];
  14021. for (var i = 0; i < textures.length; i++) {
  14022. var texture = textures[i];
  14023. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  14024. var colorRenderbuffer = gl.createRenderbuffer();
  14025. if (!colorRenderbuffer) {
  14026. throw new Error("Unable to create multi sampled framebuffer");
  14027. }
  14028. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  14029. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  14030. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  14031. texture._MSAAFramebuffer = framebuffer;
  14032. texture._MSAARenderBuffer = colorRenderbuffer;
  14033. texture.samples = samples;
  14034. texture._depthStencilBuffer = depthStencilBuffer;
  14035. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  14036. attachments.push(attachment);
  14037. }
  14038. gl.drawBuffers(attachments);
  14039. }
  14040. else {
  14041. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  14042. }
  14043. this.bindUnboundFramebuffer(null);
  14044. return samples;
  14045. };
  14046. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  14047. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  14048. };
  14049. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  14050. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  14051. };
  14052. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  14053. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  14054. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  14055. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  14056. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  14057. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14058. }
  14059. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  14060. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  14061. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14062. }
  14063. var gl = this._gl;
  14064. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  14065. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14066. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  14067. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  14068. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14069. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  14070. }
  14071. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  14072. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  14073. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14074. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14075. for (var face = 0; face < 6; face++) {
  14076. 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);
  14077. }
  14078. // Create the framebuffer
  14079. var framebuffer = gl.createFramebuffer();
  14080. this.bindUnboundFramebuffer(framebuffer);
  14081. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  14082. // MipMaps
  14083. if (fullOptions.generateMipMaps) {
  14084. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14085. }
  14086. // Unbind
  14087. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14088. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  14089. this.bindUnboundFramebuffer(null);
  14090. texture._framebuffer = framebuffer;
  14091. texture.width = size;
  14092. texture.height = size;
  14093. texture.isReady = true;
  14094. texture.isCube = true;
  14095. texture.samples = 1;
  14096. texture.generateMipMaps = fullOptions.generateMipMaps;
  14097. texture.samplingMode = fullOptions.samplingMode;
  14098. texture.type = fullOptions.type;
  14099. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  14100. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  14101. this._internalTexturesCache.push(texture);
  14102. return texture;
  14103. };
  14104. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  14105. var _this = this;
  14106. if (onLoad === void 0) { onLoad = null; }
  14107. if (onError === void 0) { onError = null; }
  14108. if (forcedExtension === void 0) { forcedExtension = null; }
  14109. var callback = function (loadData) {
  14110. if (!loadData) {
  14111. if (onLoad) {
  14112. onLoad(null);
  14113. }
  14114. return;
  14115. }
  14116. var texture = loadData.texture;
  14117. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  14118. texture._lodGenerationScale = scale;
  14119. texture._lodGenerationOffset = offset;
  14120. if (_this._caps.textureLOD) {
  14121. // Do not add extra process if texture lod is supported.
  14122. if (onLoad) {
  14123. onLoad(texture);
  14124. }
  14125. return;
  14126. }
  14127. var mipSlices = 3;
  14128. var gl = _this._gl;
  14129. var width = loadData.width;
  14130. if (!width) {
  14131. return;
  14132. }
  14133. var textures = [];
  14134. for (var i = 0; i < mipSlices; i++) {
  14135. //compute LOD from even spacing in smoothness (matching shader calculation)
  14136. var smoothness = i / (mipSlices - 1);
  14137. var roughness = 1 - smoothness;
  14138. var minLODIndex = offset; // roughness = 0
  14139. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  14140. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  14141. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  14142. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14143. glTextureFromLod.isCube = true;
  14144. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  14145. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14146. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14147. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14148. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14149. if (loadData.isDDS) {
  14150. var info = loadData.info;
  14151. var data = loadData.data;
  14152. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  14153. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  14154. }
  14155. else {
  14156. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  14157. }
  14158. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14159. // Wrap in a base texture for easy binding.
  14160. var lodTexture = new BABYLON.BaseTexture(scene);
  14161. lodTexture.isCube = true;
  14162. lodTexture._texture = glTextureFromLod;
  14163. glTextureFromLod.isReady = true;
  14164. textures.push(lodTexture);
  14165. }
  14166. texture._lodTextureHigh = textures[2];
  14167. texture._lodTextureMid = textures[1];
  14168. texture._lodTextureLow = textures[0];
  14169. if (onLoad) {
  14170. onLoad(texture);
  14171. }
  14172. };
  14173. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  14174. };
  14175. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  14176. var _this = this;
  14177. if (onLoad === void 0) { onLoad = null; }
  14178. if (onError === void 0) { onError = null; }
  14179. if (forcedExtension === void 0) { forcedExtension = null; }
  14180. var gl = this._gl;
  14181. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  14182. texture.isCube = true;
  14183. texture.url = rootUrl;
  14184. texture.generateMipMaps = !noMipmap;
  14185. if (!this._doNotHandleContextLost) {
  14186. texture._extension = forcedExtension;
  14187. texture._files = files;
  14188. }
  14189. var isKTX = false;
  14190. var isDDS = false;
  14191. var lastDot = rootUrl.lastIndexOf('.');
  14192. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  14193. if (this._textureFormatInUse) {
  14194. extension = this._textureFormatInUse;
  14195. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  14196. isKTX = true;
  14197. }
  14198. else {
  14199. isDDS = (extension === ".dds");
  14200. }
  14201. var onerror = function (request, exception) {
  14202. if (onError && request) {
  14203. onError(request.status + " " + request.statusText, exception);
  14204. }
  14205. };
  14206. if (isKTX) {
  14207. this._loadFile(rootUrl, function (data) {
  14208. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  14209. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  14210. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14211. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  14212. ktx.uploadLevels(_this._gl, !noMipmap);
  14213. _this.setCubeMapTextureParams(gl, loadMipmap);
  14214. texture.width = ktx.pixelWidth;
  14215. texture.height = ktx.pixelHeight;
  14216. texture.isReady = true;
  14217. }, undefined, undefined, true, onerror);
  14218. }
  14219. else if (isDDS) {
  14220. if (files && files.length === 6) {
  14221. this._cascadeLoadFiles(scene, function (imgs) {
  14222. var info;
  14223. var loadMipmap = false;
  14224. var width = 0;
  14225. for (var index = 0; index < imgs.length; index++) {
  14226. var data = imgs[index];
  14227. info = BABYLON.DDSTools.GetDDSInfo(data);
  14228. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  14229. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14230. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  14231. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  14232. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  14233. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14234. }
  14235. texture.width = info.width;
  14236. texture.height = info.height;
  14237. texture.type = info.textureType;
  14238. width = info.width;
  14239. }
  14240. _this.setCubeMapTextureParams(gl, loadMipmap);
  14241. texture.isReady = true;
  14242. if (onLoad) {
  14243. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  14244. }
  14245. }, files, onError);
  14246. }
  14247. else {
  14248. this._loadFile(rootUrl, function (data) {
  14249. var info = BABYLON.DDSTools.GetDDSInfo(data);
  14250. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  14251. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14252. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  14253. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  14254. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  14255. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14256. }
  14257. _this.setCubeMapTextureParams(gl, loadMipmap);
  14258. texture.width = info.width;
  14259. texture.height = info.height;
  14260. texture.isReady = true;
  14261. texture.type = info.textureType;
  14262. if (onLoad) {
  14263. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  14264. }
  14265. }, undefined, undefined, true, onerror);
  14266. }
  14267. }
  14268. else {
  14269. if (!files) {
  14270. throw new Error("Cannot load cubemap because files were not defined");
  14271. }
  14272. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  14273. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  14274. var height = width;
  14275. _this._prepareWorkingCanvas();
  14276. if (!_this._workingCanvas || !_this._workingContext) {
  14277. return;
  14278. }
  14279. _this._workingCanvas.width = width;
  14280. _this._workingCanvas.height = height;
  14281. var faces = [
  14282. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  14283. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  14284. ];
  14285. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14286. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  14287. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  14288. for (var index = 0; index < faces.length; index++) {
  14289. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  14290. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  14291. }
  14292. if (!noMipmap) {
  14293. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14294. }
  14295. _this.setCubeMapTextureParams(gl, !noMipmap);
  14296. texture.width = width;
  14297. texture.height = height;
  14298. texture.isReady = true;
  14299. if (format) {
  14300. texture.format = format;
  14301. }
  14302. texture.onLoadedObservable.notifyObservers(texture);
  14303. texture.onLoadedObservable.clear();
  14304. if (onLoad) {
  14305. onLoad();
  14306. }
  14307. }, files, onError);
  14308. }
  14309. this._internalTexturesCache.push(texture);
  14310. return texture;
  14311. };
  14312. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  14313. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14314. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  14315. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14316. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14317. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14318. // this.resetTextureCache();
  14319. };
  14320. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  14321. if (compression === void 0) { compression = null; }
  14322. if (level === void 0) { level = 0; }
  14323. texture._bufferViewArray = data;
  14324. texture.format = format;
  14325. texture.type = type;
  14326. texture.invertY = invertY;
  14327. texture._compression = compression;
  14328. var gl = this._gl;
  14329. var textureType = this._getWebGLTextureType(type);
  14330. var internalFormat = this._getInternalFormat(format);
  14331. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  14332. var needConversion = false;
  14333. if (internalFormat === gl.RGB) {
  14334. internalFormat = gl.RGBA;
  14335. needConversion = true;
  14336. }
  14337. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14338. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14339. if (texture.width % 4 !== 0) {
  14340. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  14341. }
  14342. // Data are known to be in +X +Y +Z -X -Y -Z
  14343. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  14344. var faceData = data[faceIndex];
  14345. if (compression) {
  14346. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  14347. }
  14348. else {
  14349. if (needConversion) {
  14350. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  14351. }
  14352. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  14353. }
  14354. }
  14355. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  14356. if (isPot && texture.generateMipMaps && level === 0) {
  14357. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  14358. }
  14359. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14360. // this.resetTextureCache();
  14361. texture.isReady = true;
  14362. };
  14363. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  14364. if (compression === void 0) { compression = null; }
  14365. var gl = this._gl;
  14366. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  14367. texture.isCube = true;
  14368. texture.generateMipMaps = generateMipMaps;
  14369. texture.format = format;
  14370. texture.type = type;
  14371. if (!this._doNotHandleContextLost) {
  14372. texture._bufferViewArray = data;
  14373. }
  14374. var textureType = this._getWebGLTextureType(type);
  14375. var internalFormat = this._getInternalFormat(format);
  14376. if (internalFormat === gl.RGB) {
  14377. internalFormat = gl.RGBA;
  14378. }
  14379. var width = size;
  14380. var height = width;
  14381. texture.width = width;
  14382. texture.height = height;
  14383. // Double check on POT to generate Mips.
  14384. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  14385. if (!isPot) {
  14386. generateMipMaps = false;
  14387. }
  14388. // Upload data if needed. The texture won't be ready until then.
  14389. if (data) {
  14390. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  14391. }
  14392. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14393. // Filters
  14394. if (data && generateMipMaps) {
  14395. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  14396. }
  14397. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  14398. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14399. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14400. }
  14401. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  14402. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14403. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14404. }
  14405. else {
  14406. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  14407. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  14408. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  14409. }
  14410. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14411. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14412. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14413. return texture;
  14414. };
  14415. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  14416. var _this = this;
  14417. if (onLoad === void 0) { onLoad = null; }
  14418. if (onError === void 0) { onError = null; }
  14419. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14420. if (invertY === void 0) { invertY = false; }
  14421. var gl = this._gl;
  14422. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  14423. scene._addPendingData(texture);
  14424. texture.url = url;
  14425. this._internalTexturesCache.push(texture);
  14426. var onerror = function (request, exception) {
  14427. scene._removePendingData(texture);
  14428. if (onError && request) {
  14429. onError(request.status + " " + request.statusText, exception);
  14430. }
  14431. };
  14432. var internalCallback = function (data) {
  14433. var width = texture.width;
  14434. var faceDataArrays = callback(data);
  14435. if (!faceDataArrays) {
  14436. return;
  14437. }
  14438. if (mipmmapGenerator) {
  14439. var textureType = _this._getWebGLTextureType(type);
  14440. var internalFormat = _this._getInternalFormat(format);
  14441. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  14442. var needConversion = false;
  14443. if (internalFormat === gl.RGB) {
  14444. internalFormat = gl.RGBA;
  14445. needConversion = true;
  14446. }
  14447. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14448. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  14449. var mipData = mipmmapGenerator(faceDataArrays);
  14450. for (var level = 0; level < mipData.length; level++) {
  14451. var mipSize = width >> level;
  14452. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  14453. var mipFaceData = mipData[level][faceIndex];
  14454. if (needConversion) {
  14455. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  14456. }
  14457. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  14458. }
  14459. }
  14460. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14461. }
  14462. else {
  14463. texture.generateMipMaps = !noMipmap;
  14464. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  14465. }
  14466. texture.isReady = true;
  14467. // this.resetTextureCache();
  14468. scene._removePendingData(texture);
  14469. if (onLoad) {
  14470. onLoad();
  14471. }
  14472. };
  14473. this._loadFile(url, function (data) {
  14474. internalCallback(data);
  14475. }, undefined, scene.database, true, onerror);
  14476. return texture;
  14477. };
  14478. ;
  14479. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  14480. if (compression === void 0) { compression = null; }
  14481. var internalFormat = this._getInternalFormat(format);
  14482. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  14483. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14484. if (!this._doNotHandleContextLost) {
  14485. texture._bufferView = data;
  14486. texture.format = format;
  14487. texture.invertY = invertY;
  14488. texture._compression = compression;
  14489. }
  14490. if (texture.width % 4 !== 0) {
  14491. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14492. }
  14493. if (compression && data) {
  14494. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  14495. }
  14496. else {
  14497. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  14498. }
  14499. if (texture.generateMipMaps) {
  14500. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  14501. }
  14502. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14503. // this.resetTextureCache();
  14504. texture.isReady = true;
  14505. };
  14506. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  14507. if (compression === void 0) { compression = null; }
  14508. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  14509. texture.baseWidth = width;
  14510. texture.baseHeight = height;
  14511. texture.baseDepth = depth;
  14512. texture.width = width;
  14513. texture.height = height;
  14514. texture.depth = depth;
  14515. texture.format = format;
  14516. texture.generateMipMaps = generateMipMaps;
  14517. texture.samplingMode = samplingMode;
  14518. texture.is3D = true;
  14519. if (!this._doNotHandleContextLost) {
  14520. texture._bufferView = data;
  14521. }
  14522. this.updateRawTexture3D(texture, data, format, invertY, compression);
  14523. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  14524. // Filters
  14525. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14526. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14527. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14528. if (generateMipMaps) {
  14529. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  14530. }
  14531. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14532. this._internalTexturesCache.push(texture);
  14533. return texture;
  14534. };
  14535. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  14536. var gl = this._gl;
  14537. if (!gl) {
  14538. return;
  14539. }
  14540. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  14541. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  14542. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  14543. if (!noMipmap && !isCompressed) {
  14544. gl.generateMipmap(gl.TEXTURE_2D);
  14545. }
  14546. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14547. // this.resetTextureCache();
  14548. if (scene) {
  14549. scene._removePendingData(texture);
  14550. }
  14551. texture.onLoadedObservable.notifyObservers(texture);
  14552. texture.onLoadedObservable.clear();
  14553. };
  14554. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  14555. var _this = this;
  14556. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14557. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  14558. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  14559. var gl = this._gl;
  14560. if (!gl) {
  14561. return;
  14562. }
  14563. if (!texture._webGLTexture) {
  14564. // this.resetTextureCache();
  14565. if (scene) {
  14566. scene._removePendingData(texture);
  14567. }
  14568. return;
  14569. }
  14570. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14571. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14572. texture.baseWidth = width;
  14573. texture.baseHeight = height;
  14574. texture.width = potWidth;
  14575. texture.height = potHeight;
  14576. texture.isReady = true;
  14577. if (processFunction(potWidth, potHeight, function () {
  14578. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  14579. })) {
  14580. // Returning as texture needs extra async steps
  14581. return;
  14582. }
  14583. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  14584. };
  14585. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  14586. // Create new RGBA data container.
  14587. var rgbaData;
  14588. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  14589. rgbaData = new Float32Array(width * height * 4);
  14590. }
  14591. else {
  14592. rgbaData = new Uint32Array(width * height * 4);
  14593. }
  14594. // Convert each pixel.
  14595. for (var x = 0; x < width; x++) {
  14596. for (var y = 0; y < height; y++) {
  14597. var index = (y * width + x) * 3;
  14598. var newIndex = (y * width + x) * 4;
  14599. // Map Old Value to new value.
  14600. rgbaData[newIndex + 0] = rgbData[index + 0];
  14601. rgbaData[newIndex + 1] = rgbData[index + 1];
  14602. rgbaData[newIndex + 2] = rgbData[index + 2];
  14603. // Add fully opaque alpha channel.
  14604. rgbaData[newIndex + 3] = 1;
  14605. }
  14606. }
  14607. return rgbaData;
  14608. };
  14609. Engine.prototype._releaseFramebufferObjects = function (texture) {
  14610. var gl = this._gl;
  14611. if (texture._framebuffer) {
  14612. gl.deleteFramebuffer(texture._framebuffer);
  14613. texture._framebuffer = null;
  14614. }
  14615. if (texture._depthStencilBuffer) {
  14616. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  14617. texture._depthStencilBuffer = null;
  14618. }
  14619. if (texture._MSAAFramebuffer) {
  14620. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  14621. texture._MSAAFramebuffer = null;
  14622. }
  14623. if (texture._MSAARenderBuffer) {
  14624. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  14625. texture._MSAARenderBuffer = null;
  14626. }
  14627. };
  14628. Engine.prototype._releaseTexture = function (texture) {
  14629. var gl = this._gl;
  14630. this._releaseFramebufferObjects(texture);
  14631. gl.deleteTexture(texture._webGLTexture);
  14632. // Unbind channels
  14633. this.unbindAllTextures();
  14634. var index = this._internalTexturesCache.indexOf(texture);
  14635. if (index !== -1) {
  14636. this._internalTexturesCache.splice(index, 1);
  14637. }
  14638. // Integrated fixed lod samplers.
  14639. if (texture._lodTextureHigh) {
  14640. texture._lodTextureHigh.dispose();
  14641. }
  14642. if (texture._lodTextureMid) {
  14643. texture._lodTextureMid.dispose();
  14644. }
  14645. if (texture._lodTextureLow) {
  14646. texture._lodTextureLow.dispose();
  14647. }
  14648. // Set output texture of post process to null if the texture has been released/disposed
  14649. this.scenes.forEach(function (scene) {
  14650. scene.postProcesses.forEach(function (postProcess) {
  14651. if (postProcess._outputTexture == texture) {
  14652. postProcess._outputTexture = null;
  14653. }
  14654. });
  14655. scene.cameras.forEach(function (camera) {
  14656. camera._postProcesses.forEach(function (postProcess) {
  14657. if (postProcess) {
  14658. if (postProcess._outputTexture == texture) {
  14659. postProcess._outputTexture = null;
  14660. }
  14661. }
  14662. });
  14663. });
  14664. });
  14665. };
  14666. Engine.prototype.setProgram = function (program) {
  14667. if (this._currentProgram !== program) {
  14668. this._gl.useProgram(program);
  14669. this._currentProgram = program;
  14670. }
  14671. };
  14672. Engine.prototype.bindSamplers = function (effect) {
  14673. this.setProgram(effect.getProgram());
  14674. var samplers = effect.getSamplers();
  14675. for (var index = 0; index < samplers.length; index++) {
  14676. var uniform = effect.getUniform(samplers[index]);
  14677. if (uniform) {
  14678. this._boundUniforms[index] = uniform;
  14679. }
  14680. }
  14681. this._currentEffect = null;
  14682. };
  14683. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  14684. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  14685. return;
  14686. }
  14687. // Remove
  14688. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14689. // Bind last to it
  14690. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  14691. // Bind to dummy
  14692. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  14693. };
  14694. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  14695. if (!internalTexture) {
  14696. return -1;
  14697. }
  14698. internalTexture._initialSlot = channel;
  14699. if (this.disableTextureBindingOptimization) {
  14700. if (channel !== internalTexture._designatedSlot) {
  14701. this._textureCollisions.addCount(1, false);
  14702. }
  14703. }
  14704. else {
  14705. if (channel !== internalTexture._designatedSlot) {
  14706. if (internalTexture._designatedSlot > -1) {
  14707. return internalTexture._designatedSlot;
  14708. }
  14709. else {
  14710. // No slot for this texture, let's pick a new one (if we find a free slot)
  14711. if (this._nextFreeTextureSlots.length) {
  14712. return this._nextFreeTextureSlots[0];
  14713. }
  14714. // We need to recycle the oldest bound texture, sorry.
  14715. this._textureCollisions.addCount(1, false);
  14716. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  14717. }
  14718. }
  14719. }
  14720. return channel;
  14721. };
  14722. Engine.prototype._linkTrackers = function (previous, next) {
  14723. previous.next = next;
  14724. next.previous = previous;
  14725. };
  14726. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  14727. var currentSlot = internalTexture._designatedSlot;
  14728. if (currentSlot === -1) {
  14729. return -1;
  14730. }
  14731. internalTexture._designatedSlot = -1;
  14732. if (this.disableTextureBindingOptimization) {
  14733. return -1;
  14734. }
  14735. // Remove from bound list
  14736. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14737. // Free the slot
  14738. this._boundTexturesCache[currentSlot] = null;
  14739. this._nextFreeTextureSlots.push(currentSlot);
  14740. return currentSlot;
  14741. };
  14742. Engine.prototype._activateCurrentTexture = function () {
  14743. if (this._currentTextureChannel !== this._activeChannel) {
  14744. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  14745. this._currentTextureChannel = this._activeChannel;
  14746. }
  14747. };
  14748. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate) {
  14749. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  14750. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  14751. this._activeChannel = texture._designatedSlot;
  14752. }
  14753. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  14754. var isTextureForRendering = texture && texture._initialSlot > -1;
  14755. if (currentTextureBound !== texture) {
  14756. if (currentTextureBound) {
  14757. this._removeDesignatedSlot(currentTextureBound);
  14758. }
  14759. this._activateCurrentTexture();
  14760. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  14761. this._boundTexturesCache[this._activeChannel] = texture;
  14762. if (texture) {
  14763. if (!this.disableTextureBindingOptimization) {
  14764. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  14765. if (slotIndex > -1) {
  14766. this._nextFreeTextureSlots.splice(slotIndex, 1);
  14767. }
  14768. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  14769. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  14770. }
  14771. texture._designatedSlot = this._activeChannel;
  14772. }
  14773. }
  14774. else if (forTextureDataUpdate) {
  14775. this._activateCurrentTexture();
  14776. }
  14777. if (isTextureForRendering && !forTextureDataUpdate) {
  14778. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  14779. }
  14780. };
  14781. Engine.prototype._bindTexture = function (channel, texture) {
  14782. if (channel < 0) {
  14783. return;
  14784. }
  14785. if (texture) {
  14786. channel = this._getCorrectTextureChannel(channel, texture);
  14787. }
  14788. this._activeChannel = channel;
  14789. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  14790. };
  14791. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  14792. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  14793. };
  14794. /**
  14795. * Binds the output of the passed in post process to the texture channel specified
  14796. * @param channel The channel the texture should be bound to
  14797. * @param postProcess The post process which's output should be bound
  14798. */
  14799. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  14800. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  14801. };
  14802. Engine.prototype.unbindAllTextures = function () {
  14803. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  14804. this._activeChannel = channel;
  14805. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14806. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14807. if (this.webGLVersion > 1) {
  14808. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14809. }
  14810. }
  14811. };
  14812. /**
  14813. * Sets a texture to the according uniform.
  14814. * @param channel The texture channel
  14815. * @param uniform The uniform to set
  14816. * @param texture The texture to apply
  14817. */
  14818. Engine.prototype.setTexture = function (channel, uniform, texture) {
  14819. if (channel < 0) {
  14820. return;
  14821. }
  14822. if (uniform) {
  14823. this._boundUniforms[channel] = uniform;
  14824. }
  14825. this._setTexture(channel, texture);
  14826. };
  14827. /**
  14828. * Sets a depth stencil texture from a render target to the according uniform.
  14829. * @param channel The texture channel
  14830. * @param uniform The uniform to set
  14831. * @param texture The render target texture containing the depth stencil texture to apply
  14832. */
  14833. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  14834. if (channel < 0) {
  14835. return;
  14836. }
  14837. if (uniform) {
  14838. this._boundUniforms[channel] = uniform;
  14839. }
  14840. if (!texture || !texture.depthStencilTexture) {
  14841. this._setTexture(channel, null);
  14842. }
  14843. else {
  14844. this._setTexture(channel, texture, false, true);
  14845. }
  14846. };
  14847. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  14848. var uniform = this._boundUniforms[sourceSlot];
  14849. if (uniform._currentState === destination) {
  14850. return;
  14851. }
  14852. this._gl.uniform1i(uniform, destination);
  14853. uniform._currentState = destination;
  14854. };
  14855. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  14856. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  14857. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  14858. // Not ready?
  14859. if (!texture) {
  14860. if (this._boundTexturesCache[channel] != null) {
  14861. this._activeChannel = channel;
  14862. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14863. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14864. if (this.webGLVersion > 1) {
  14865. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14866. }
  14867. }
  14868. return false;
  14869. }
  14870. // Video
  14871. if (texture.video) {
  14872. this._activeChannel = channel;
  14873. texture.update();
  14874. }
  14875. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  14876. texture.delayLoad();
  14877. return false;
  14878. }
  14879. var internalTexture;
  14880. if (depthStencilTexture) {
  14881. internalTexture = texture.depthStencilTexture;
  14882. }
  14883. else if (texture.isReady()) {
  14884. internalTexture = texture.getInternalTexture();
  14885. }
  14886. else if (texture.isCube) {
  14887. internalTexture = this.emptyCubeTexture;
  14888. }
  14889. else if (texture.is3D) {
  14890. internalTexture = this.emptyTexture3D;
  14891. }
  14892. else {
  14893. internalTexture = this.emptyTexture;
  14894. }
  14895. if (!isPartOfTextureArray) {
  14896. channel = this._getCorrectTextureChannel(channel, internalTexture);
  14897. }
  14898. if (this._boundTexturesCache[channel] === internalTexture) {
  14899. this._moveBoundTextureOnTop(internalTexture);
  14900. if (!isPartOfTextureArray) {
  14901. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  14902. }
  14903. return false;
  14904. }
  14905. this._activeChannel = channel;
  14906. if (internalTexture && internalTexture.is3D) {
  14907. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  14908. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14909. internalTexture._cachedWrapU = texture.wrapU;
  14910. switch (texture.wrapU) {
  14911. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14912. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14913. break;
  14914. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14915. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14916. break;
  14917. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14918. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14919. break;
  14920. }
  14921. }
  14922. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14923. internalTexture._cachedWrapV = texture.wrapV;
  14924. switch (texture.wrapV) {
  14925. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14926. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14927. break;
  14928. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14929. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14930. break;
  14931. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14932. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14933. break;
  14934. }
  14935. }
  14936. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  14937. internalTexture._cachedWrapR = texture.wrapR;
  14938. switch (texture.wrapR) {
  14939. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14940. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  14941. break;
  14942. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14943. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  14944. break;
  14945. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14946. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  14947. break;
  14948. }
  14949. }
  14950. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  14951. }
  14952. else if (internalTexture && internalTexture.isCube) {
  14953. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  14954. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  14955. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  14956. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  14957. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  14958. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  14959. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  14960. }
  14961. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  14962. }
  14963. else {
  14964. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  14965. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14966. internalTexture._cachedWrapU = texture.wrapU;
  14967. switch (texture.wrapU) {
  14968. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14969. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14970. break;
  14971. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14972. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14973. break;
  14974. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14975. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14976. break;
  14977. }
  14978. }
  14979. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14980. internalTexture._cachedWrapV = texture.wrapV;
  14981. switch (texture.wrapV) {
  14982. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14983. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14984. break;
  14985. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14986. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14987. break;
  14988. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14989. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14990. break;
  14991. }
  14992. }
  14993. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  14994. }
  14995. return true;
  14996. };
  14997. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  14998. if (channel < 0 || !uniform) {
  14999. return;
  15000. }
  15001. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  15002. this._textureUnits = new Int32Array(textures.length);
  15003. }
  15004. for (var i = 0; i < textures.length; i++) {
  15005. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  15006. }
  15007. this._gl.uniform1iv(uniform, this._textureUnits);
  15008. for (var index = 0; index < textures.length; index++) {
  15009. this._setTexture(this._textureUnits[index], textures[index], true);
  15010. }
  15011. };
  15012. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  15013. var internalTexture = texture.getInternalTexture();
  15014. if (!internalTexture) {
  15015. return;
  15016. }
  15017. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  15018. var value = texture.anisotropicFilteringLevel;
  15019. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  15020. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  15021. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  15022. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  15023. }
  15024. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  15025. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  15026. internalTexture._cachedAnisotropicFilteringLevel = value;
  15027. }
  15028. };
  15029. Engine.prototype.readPixels = function (x, y, width, height) {
  15030. var data = new Uint8Array(height * width * 4);
  15031. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  15032. return data;
  15033. };
  15034. /**
  15035. * Add an externaly attached data from its key.
  15036. * This method call will fail and return false, if such key already exists.
  15037. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  15038. * @param key the unique key that identifies the data
  15039. * @param data the data object to associate to the key for this Engine instance
  15040. * @return true if no such key were already present and the data was added successfully, false otherwise
  15041. */
  15042. Engine.prototype.addExternalData = function (key, data) {
  15043. if (!this._externalData) {
  15044. this._externalData = new BABYLON.StringDictionary();
  15045. }
  15046. return this._externalData.add(key, data);
  15047. };
  15048. /**
  15049. * Get an externaly attached data from its key
  15050. * @param key the unique key that identifies the data
  15051. * @return the associated data, if present (can be null), or undefined if not present
  15052. */
  15053. Engine.prototype.getExternalData = function (key) {
  15054. if (!this._externalData) {
  15055. this._externalData = new BABYLON.StringDictionary();
  15056. }
  15057. return this._externalData.get(key);
  15058. };
  15059. /**
  15060. * Get an externaly attached data from its key, create it using a factory if it's not already present
  15061. * @param key the unique key that identifies the data
  15062. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  15063. * @return the associated data, can be null if the factory returned null.
  15064. */
  15065. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  15066. if (!this._externalData) {
  15067. this._externalData = new BABYLON.StringDictionary();
  15068. }
  15069. return this._externalData.getOrAddWithFactory(key, factory);
  15070. };
  15071. /**
  15072. * Remove an externaly attached data from the Engine instance
  15073. * @param key the unique key that identifies the data
  15074. * @return true if the data was successfully removed, false if it doesn't exist
  15075. */
  15076. Engine.prototype.removeExternalData = function (key) {
  15077. if (!this._externalData) {
  15078. this._externalData = new BABYLON.StringDictionary();
  15079. }
  15080. return this._externalData.remove(key);
  15081. };
  15082. Engine.prototype.unbindAllAttributes = function () {
  15083. if (this._mustWipeVertexAttributes) {
  15084. this._mustWipeVertexAttributes = false;
  15085. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  15086. this._gl.disableVertexAttribArray(i);
  15087. this._vertexAttribArraysEnabled[i] = false;
  15088. this._currentBufferPointers[i].active = false;
  15089. }
  15090. return;
  15091. }
  15092. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  15093. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  15094. continue;
  15095. }
  15096. this._gl.disableVertexAttribArray(i);
  15097. this._vertexAttribArraysEnabled[i] = false;
  15098. this._currentBufferPointers[i].active = false;
  15099. }
  15100. };
  15101. Engine.prototype.releaseEffects = function () {
  15102. for (var name in this._compiledEffects) {
  15103. this._deleteProgram(this._compiledEffects[name]._program);
  15104. }
  15105. this._compiledEffects = {};
  15106. };
  15107. // Dispose
  15108. Engine.prototype.dispose = function () {
  15109. this.hideLoadingUI();
  15110. this.stopRenderLoop();
  15111. // Release postProcesses
  15112. while (this.postProcesses.length) {
  15113. this.postProcesses[0].dispose();
  15114. }
  15115. // Empty texture
  15116. if (this._emptyTexture) {
  15117. this._releaseTexture(this._emptyTexture);
  15118. this._emptyTexture = null;
  15119. }
  15120. if (this._emptyCubeTexture) {
  15121. this._releaseTexture(this._emptyCubeTexture);
  15122. this._emptyCubeTexture = null;
  15123. }
  15124. // Rescale PP
  15125. if (this._rescalePostProcess) {
  15126. this._rescalePostProcess.dispose();
  15127. }
  15128. // Release scenes
  15129. while (this.scenes.length) {
  15130. this.scenes[0].dispose();
  15131. }
  15132. // Release audio engine
  15133. if (Engine.audioEngine) {
  15134. Engine.audioEngine.dispose();
  15135. }
  15136. // Release effects
  15137. this.releaseEffects();
  15138. // Unbind
  15139. this.unbindAllAttributes();
  15140. this._boundUniforms = [];
  15141. if (this._dummyFramebuffer) {
  15142. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  15143. }
  15144. //WebVR
  15145. this.disableVR();
  15146. // Events
  15147. if (BABYLON.Tools.IsWindowObjectExist()) {
  15148. window.removeEventListener("blur", this._onBlur);
  15149. window.removeEventListener("focus", this._onFocus);
  15150. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  15151. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  15152. if (this._renderingCanvas) {
  15153. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  15154. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  15155. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  15156. if (!this._doNotHandleContextLost) {
  15157. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  15158. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  15159. }
  15160. }
  15161. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  15162. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  15163. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  15164. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  15165. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  15166. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  15167. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  15168. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  15169. if (this._onVrDisplayConnect) {
  15170. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  15171. if (this._onVrDisplayDisconnect) {
  15172. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  15173. }
  15174. if (this._onVrDisplayPresentChange) {
  15175. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  15176. }
  15177. this._onVrDisplayConnect = null;
  15178. this._onVrDisplayDisconnect = null;
  15179. }
  15180. }
  15181. // Remove from Instances
  15182. var index = Engine.Instances.indexOf(this);
  15183. if (index >= 0) {
  15184. Engine.Instances.splice(index, 1);
  15185. }
  15186. this._workingCanvas = null;
  15187. this._workingContext = null;
  15188. this._currentBufferPointers = [];
  15189. this._renderingCanvas = null;
  15190. this._currentProgram = null;
  15191. this._bindedRenderFunction = null;
  15192. this.onResizeObservable.clear();
  15193. this.onCanvasBlurObservable.clear();
  15194. this.onCanvasFocusObservable.clear();
  15195. this.onCanvasPointerOutObservable.clear();
  15196. this.onBeginFrameObservable.clear();
  15197. this.onEndFrameObservable.clear();
  15198. BABYLON.Effect.ResetCache();
  15199. // Abort active requests
  15200. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  15201. var request = _a[_i];
  15202. request.abort();
  15203. }
  15204. };
  15205. // Loading screen
  15206. Engine.prototype.displayLoadingUI = function () {
  15207. if (!BABYLON.Tools.IsWindowObjectExist()) {
  15208. return;
  15209. }
  15210. var loadingScreen = this.loadingScreen;
  15211. if (loadingScreen) {
  15212. loadingScreen.displayLoadingUI();
  15213. }
  15214. };
  15215. Engine.prototype.hideLoadingUI = function () {
  15216. if (!BABYLON.Tools.IsWindowObjectExist()) {
  15217. return;
  15218. }
  15219. var loadingScreen = this.loadingScreen;
  15220. if (loadingScreen) {
  15221. loadingScreen.hideLoadingUI();
  15222. }
  15223. };
  15224. Object.defineProperty(Engine.prototype, "loadingScreen", {
  15225. get: function () {
  15226. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  15227. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  15228. return this._loadingScreen;
  15229. },
  15230. set: function (loadingScreen) {
  15231. this._loadingScreen = loadingScreen;
  15232. },
  15233. enumerable: true,
  15234. configurable: true
  15235. });
  15236. Object.defineProperty(Engine.prototype, "loadingUIText", {
  15237. set: function (text) {
  15238. this.loadingScreen.loadingUIText = text;
  15239. },
  15240. enumerable: true,
  15241. configurable: true
  15242. });
  15243. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  15244. set: function (color) {
  15245. this.loadingScreen.loadingUIBackgroundColor = color;
  15246. },
  15247. enumerable: true,
  15248. configurable: true
  15249. });
  15250. Engine.prototype.attachContextLostEvent = function (callback) {
  15251. if (this._renderingCanvas) {
  15252. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  15253. }
  15254. };
  15255. Engine.prototype.attachContextRestoredEvent = function (callback) {
  15256. if (this._renderingCanvas) {
  15257. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  15258. }
  15259. };
  15260. Engine.prototype.getVertexShaderSource = function (program) {
  15261. var shaders = this._gl.getAttachedShaders(program);
  15262. if (!shaders) {
  15263. return null;
  15264. }
  15265. return this._gl.getShaderSource(shaders[0]);
  15266. };
  15267. Engine.prototype.getFragmentShaderSource = function (program) {
  15268. var shaders = this._gl.getAttachedShaders(program);
  15269. if (!shaders) {
  15270. return null;
  15271. }
  15272. return this._gl.getShaderSource(shaders[1]);
  15273. };
  15274. Engine.prototype.getError = function () {
  15275. return this._gl.getError();
  15276. };
  15277. // FPS
  15278. Engine.prototype.getFps = function () {
  15279. return this._fps;
  15280. };
  15281. Engine.prototype.getDeltaTime = function () {
  15282. return this._deltaTime;
  15283. };
  15284. Engine.prototype._measureFps = function () {
  15285. this._performanceMonitor.sampleFrame();
  15286. this._fps = this._performanceMonitor.averageFPS;
  15287. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  15288. };
  15289. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  15290. if (faceIndex === void 0) { faceIndex = -1; }
  15291. var gl = this._gl;
  15292. if (!this._dummyFramebuffer) {
  15293. var dummy = gl.createFramebuffer();
  15294. if (!dummy) {
  15295. throw new Error("Unable to create dummy framebuffer");
  15296. }
  15297. this._dummyFramebuffer = dummy;
  15298. }
  15299. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  15300. if (faceIndex > -1) {
  15301. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  15302. }
  15303. else {
  15304. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15305. }
  15306. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  15307. var buffer;
  15308. switch (readType) {
  15309. case gl.UNSIGNED_BYTE:
  15310. buffer = new Uint8Array(4 * width * height);
  15311. readType = gl.UNSIGNED_BYTE;
  15312. break;
  15313. default:
  15314. buffer = new Float32Array(4 * width * height);
  15315. readType = gl.FLOAT;
  15316. break;
  15317. }
  15318. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  15319. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  15320. return buffer;
  15321. };
  15322. Engine.prototype._canRenderToFloatFramebuffer = function () {
  15323. if (this._webGLVersion > 1) {
  15324. return this._caps.colorBufferFloat;
  15325. }
  15326. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  15327. };
  15328. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  15329. if (this._webGLVersion > 1) {
  15330. return this._caps.colorBufferFloat;
  15331. }
  15332. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  15333. };
  15334. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  15335. Engine.prototype._canRenderToFramebuffer = function (type) {
  15336. var gl = this._gl;
  15337. //clear existing errors
  15338. while (gl.getError() !== gl.NO_ERROR) { }
  15339. var successful = true;
  15340. var texture = gl.createTexture();
  15341. gl.bindTexture(gl.TEXTURE_2D, texture);
  15342. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15343. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15344. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15345. var fb = gl.createFramebuffer();
  15346. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  15347. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  15348. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  15349. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  15350. successful = successful && (gl.getError() === gl.NO_ERROR);
  15351. //try render by clearing frame buffer's color buffer
  15352. if (successful) {
  15353. gl.clear(gl.COLOR_BUFFER_BIT);
  15354. successful = successful && (gl.getError() === gl.NO_ERROR);
  15355. }
  15356. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  15357. if (successful) {
  15358. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  15359. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  15360. var readFormat = gl.RGBA;
  15361. var readType = gl.UNSIGNED_BYTE;
  15362. var buffer = new Uint8Array(4);
  15363. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  15364. successful = successful && (gl.getError() === gl.NO_ERROR);
  15365. }
  15366. //clean up
  15367. gl.deleteTexture(texture);
  15368. gl.deleteFramebuffer(fb);
  15369. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  15370. //clear accumulated errors
  15371. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  15372. return successful;
  15373. };
  15374. Engine.prototype._getWebGLTextureType = function (type) {
  15375. if (type === Engine.TEXTURETYPE_FLOAT) {
  15376. return this._gl.FLOAT;
  15377. }
  15378. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15379. // Add Half Float Constant.
  15380. return this._gl.HALF_FLOAT_OES;
  15381. }
  15382. return this._gl.UNSIGNED_BYTE;
  15383. };
  15384. ;
  15385. Engine.prototype._getInternalFormat = function (format) {
  15386. var internalFormat = this._gl.RGBA;
  15387. switch (format) {
  15388. case Engine.TEXTUREFORMAT_ALPHA:
  15389. internalFormat = this._gl.ALPHA;
  15390. break;
  15391. case Engine.TEXTUREFORMAT_LUMINANCE:
  15392. internalFormat = this._gl.LUMINANCE;
  15393. break;
  15394. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  15395. internalFormat = this._gl.LUMINANCE_ALPHA;
  15396. break;
  15397. case Engine.TEXTUREFORMAT_RGB:
  15398. case Engine.TEXTUREFORMAT_RGB32F:
  15399. internalFormat = this._gl.RGB;
  15400. break;
  15401. case Engine.TEXTUREFORMAT_RGBA:
  15402. case Engine.TEXTUREFORMAT_RGBA32F:
  15403. internalFormat = this._gl.RGBA;
  15404. break;
  15405. case Engine.TEXTUREFORMAT_R32F:
  15406. internalFormat = this._gl.RED;
  15407. break;
  15408. case Engine.TEXTUREFORMAT_RG32F:
  15409. internalFormat = this._gl.RG;
  15410. break;
  15411. }
  15412. return internalFormat;
  15413. };
  15414. /** @ignore */
  15415. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  15416. if (this._webGLVersion === 1) {
  15417. if (format) {
  15418. switch (format) {
  15419. case Engine.TEXTUREFORMAT_LUMINANCE:
  15420. return this._gl.LUMINANCE;
  15421. }
  15422. }
  15423. return this._gl.RGBA;
  15424. }
  15425. if (type === Engine.TEXTURETYPE_FLOAT) {
  15426. if (format) {
  15427. switch (format) {
  15428. case Engine.TEXTUREFORMAT_R32F:
  15429. return this._gl.R32F;
  15430. case Engine.TEXTUREFORMAT_RG32F:
  15431. return this._gl.RG32F;
  15432. case Engine.TEXTUREFORMAT_RGB32F:
  15433. return this._gl.RGB32F;
  15434. }
  15435. }
  15436. return this._gl.RGBA32F;
  15437. }
  15438. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15439. return this._gl.RGBA16F;
  15440. }
  15441. if (format) {
  15442. switch (format) {
  15443. case Engine.TEXTUREFORMAT_LUMINANCE:
  15444. return this._gl.LUMINANCE;
  15445. }
  15446. }
  15447. return this._gl.RGBA;
  15448. };
  15449. ;
  15450. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  15451. if (type === Engine.TEXTURETYPE_FLOAT) {
  15452. return this._gl.RGBA32F;
  15453. }
  15454. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15455. return this._gl.RGBA16F;
  15456. }
  15457. return this._gl.RGBA8;
  15458. };
  15459. ;
  15460. Engine.prototype.createQuery = function () {
  15461. return this._gl.createQuery();
  15462. };
  15463. Engine.prototype.deleteQuery = function (query) {
  15464. this._gl.deleteQuery(query);
  15465. return this;
  15466. };
  15467. Engine.prototype.isQueryResultAvailable = function (query) {
  15468. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  15469. };
  15470. Engine.prototype.getQueryResult = function (query) {
  15471. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  15472. };
  15473. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  15474. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  15475. this._gl.beginQuery(glAlgorithm, query);
  15476. return this;
  15477. };
  15478. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  15479. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  15480. this._gl.endQuery(glAlgorithm);
  15481. return this;
  15482. };
  15483. /* Time queries */
  15484. Engine.prototype._createTimeQuery = function () {
  15485. var timerQuery = this._caps.timerQuery;
  15486. if (timerQuery.createQueryEXT) {
  15487. return timerQuery.createQueryEXT();
  15488. }
  15489. return this.createQuery();
  15490. };
  15491. Engine.prototype._deleteTimeQuery = function (query) {
  15492. var timerQuery = this._caps.timerQuery;
  15493. if (timerQuery.deleteQueryEXT) {
  15494. timerQuery.deleteQueryEXT(query);
  15495. return;
  15496. }
  15497. this.deleteQuery(query);
  15498. };
  15499. Engine.prototype._getTimeQueryResult = function (query) {
  15500. var timerQuery = this._caps.timerQuery;
  15501. if (timerQuery.getQueryObjectEXT) {
  15502. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  15503. }
  15504. return this.getQueryResult(query);
  15505. };
  15506. Engine.prototype._getTimeQueryAvailability = function (query) {
  15507. var timerQuery = this._caps.timerQuery;
  15508. if (timerQuery.getQueryObjectEXT) {
  15509. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  15510. }
  15511. return this.isQueryResultAvailable(query);
  15512. };
  15513. Engine.prototype.startTimeQuery = function () {
  15514. var timerQuery = this._caps.timerQuery;
  15515. if (!timerQuery) {
  15516. return null;
  15517. }
  15518. var token = new BABYLON._TimeToken();
  15519. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  15520. if (this._caps.canUseTimestampForTimerQuery) {
  15521. token._startTimeQuery = this._createTimeQuery();
  15522. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  15523. }
  15524. else {
  15525. if (this._currentNonTimestampToken) {
  15526. return this._currentNonTimestampToken;
  15527. }
  15528. token._timeElapsedQuery = this._createTimeQuery();
  15529. if (timerQuery.beginQueryEXT) {
  15530. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  15531. }
  15532. else {
  15533. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  15534. }
  15535. this._currentNonTimestampToken = token;
  15536. }
  15537. return token;
  15538. };
  15539. Engine.prototype.endTimeQuery = function (token) {
  15540. var timerQuery = this._caps.timerQuery;
  15541. if (!timerQuery || !token) {
  15542. return -1;
  15543. }
  15544. if (this._caps.canUseTimestampForTimerQuery) {
  15545. if (!token._startTimeQuery) {
  15546. return -1;
  15547. }
  15548. if (!token._endTimeQuery) {
  15549. token._endTimeQuery = this._createTimeQuery();
  15550. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  15551. }
  15552. }
  15553. else if (!token._timeElapsedQueryEnded) {
  15554. if (!token._timeElapsedQuery) {
  15555. return -1;
  15556. }
  15557. if (timerQuery.endQueryEXT) {
  15558. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  15559. }
  15560. else {
  15561. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  15562. }
  15563. token._timeElapsedQueryEnded = true;
  15564. }
  15565. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  15566. var available = false;
  15567. if (token._endTimeQuery) {
  15568. available = this._getTimeQueryAvailability(token._endTimeQuery);
  15569. }
  15570. else if (token._timeElapsedQuery) {
  15571. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  15572. }
  15573. if (available && !disjoint) {
  15574. var result = 0;
  15575. if (this._caps.canUseTimestampForTimerQuery) {
  15576. if (!token._startTimeQuery || !token._endTimeQuery) {
  15577. return -1;
  15578. }
  15579. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  15580. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  15581. result = timeEnd - timeStart;
  15582. this._deleteTimeQuery(token._startTimeQuery);
  15583. this._deleteTimeQuery(token._endTimeQuery);
  15584. token._startTimeQuery = null;
  15585. token._endTimeQuery = null;
  15586. }
  15587. else {
  15588. if (!token._timeElapsedQuery) {
  15589. return -1;
  15590. }
  15591. result = this._getTimeQueryResult(token._timeElapsedQuery);
  15592. this._deleteTimeQuery(token._timeElapsedQuery);
  15593. token._timeElapsedQuery = null;
  15594. token._timeElapsedQueryEnded = false;
  15595. this._currentNonTimestampToken = null;
  15596. }
  15597. return result;
  15598. }
  15599. return -1;
  15600. };
  15601. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  15602. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  15603. };
  15604. // Transform feedback
  15605. Engine.prototype.createTransformFeedback = function () {
  15606. return this._gl.createTransformFeedback();
  15607. };
  15608. Engine.prototype.deleteTransformFeedback = function (value) {
  15609. this._gl.deleteTransformFeedback(value);
  15610. };
  15611. Engine.prototype.bindTransformFeedback = function (value) {
  15612. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  15613. };
  15614. Engine.prototype.beginTransformFeedback = function (usePoints) {
  15615. if (usePoints === void 0) { usePoints = true; }
  15616. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  15617. };
  15618. Engine.prototype.endTransformFeedback = function () {
  15619. this._gl.endTransformFeedback();
  15620. };
  15621. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  15622. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  15623. };
  15624. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  15625. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  15626. };
  15627. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  15628. var _this = this;
  15629. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  15630. this._activeRequests.push(request);
  15631. request.onCompleteObservable.add(function (request) {
  15632. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  15633. });
  15634. return request;
  15635. };
  15636. /** @ignore */
  15637. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  15638. var _this = this;
  15639. return new Promise(function (resolve, reject) {
  15640. _this._loadFile(url, function (data) {
  15641. resolve(data);
  15642. }, undefined, database, useArrayBuffer, function (request, exception) {
  15643. reject(exception);
  15644. });
  15645. });
  15646. };
  15647. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  15648. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  15649. var onload = function (data) {
  15650. loadedFiles[index] = data;
  15651. loadedFiles._internalCount++;
  15652. if (loadedFiles._internalCount === 6) {
  15653. onfinish(loadedFiles);
  15654. }
  15655. };
  15656. var onerror = function (request, exception) {
  15657. if (onErrorCallBack && request) {
  15658. onErrorCallBack(request.status + " " + request.statusText, exception);
  15659. }
  15660. };
  15661. this._loadFile(url, onload, undefined, undefined, true, onerror);
  15662. };
  15663. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  15664. if (onError === void 0) { onError = null; }
  15665. var loadedFiles = [];
  15666. loadedFiles._internalCount = 0;
  15667. for (var index = 0; index < 6; index++) {
  15668. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  15669. }
  15670. };
  15671. // Statics
  15672. Engine.isSupported = function () {
  15673. try {
  15674. var tempcanvas = document.createElement("canvas");
  15675. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  15676. return gl != null && !!window.WebGLRenderingContext;
  15677. }
  15678. catch (e) {
  15679. return false;
  15680. }
  15681. };
  15682. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  15683. Engine.ExceptionList = [
  15684. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  15685. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  15686. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  15687. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  15688. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  15689. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  15690. ];
  15691. Engine.Instances = new Array();
  15692. // Const statics
  15693. Engine._ALPHA_DISABLE = 0;
  15694. Engine._ALPHA_ADD = 1;
  15695. Engine._ALPHA_COMBINE = 2;
  15696. Engine._ALPHA_SUBTRACT = 3;
  15697. Engine._ALPHA_MULTIPLY = 4;
  15698. Engine._ALPHA_MAXIMIZED = 5;
  15699. Engine._ALPHA_ONEONE = 6;
  15700. Engine._ALPHA_PREMULTIPLIED = 7;
  15701. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  15702. Engine._ALPHA_INTERPOLATE = 9;
  15703. Engine._ALPHA_SCREENMODE = 10;
  15704. Engine._DELAYLOADSTATE_NONE = 0;
  15705. Engine._DELAYLOADSTATE_LOADED = 1;
  15706. Engine._DELAYLOADSTATE_LOADING = 2;
  15707. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  15708. Engine._TEXTUREFORMAT_ALPHA = 0;
  15709. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  15710. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  15711. Engine._TEXTUREFORMAT_RGB = 4;
  15712. Engine._TEXTUREFORMAT_RGBA = 5;
  15713. Engine._TEXTUREFORMAT_R32F = 6;
  15714. Engine._TEXTUREFORMAT_RG32F = 7;
  15715. Engine._TEXTUREFORMAT_RGB32F = 8;
  15716. Engine._TEXTUREFORMAT_RGBA32F = 9;
  15717. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  15718. Engine._TEXTURETYPE_FLOAT = 1;
  15719. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  15720. // Depht or Stencil test Constants.
  15721. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  15722. 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.
  15723. 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.
  15724. 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.
  15725. 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.
  15726. 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.
  15727. 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.
  15728. 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.
  15729. // Stencil Actions Constants.
  15730. Engine._KEEP = 0x1E00;
  15731. Engine._REPLACE = 0x1E01;
  15732. Engine._INCR = 0x1E02;
  15733. Engine._DECR = 0x1E03;
  15734. Engine._INVERT = 0x150A;
  15735. Engine._INCR_WRAP = 0x8507;
  15736. Engine._DECR_WRAP = 0x8508;
  15737. // Texture rescaling mode
  15738. Engine._SCALEMODE_FLOOR = 1;
  15739. Engine._SCALEMODE_NEAREST = 2;
  15740. Engine._SCALEMODE_CEILING = 3;
  15741. // Updatable statics so stick with vars here
  15742. Engine.CollisionsEpsilon = 0.001;
  15743. Engine.CodeRepository = "src/";
  15744. Engine.ShadersRepository = "src/Shaders/";
  15745. return Engine;
  15746. }());
  15747. BABYLON.Engine = Engine;
  15748. })(BABYLON || (BABYLON = {}));
  15749. //# sourceMappingURL=babylon.engine.js.map
  15750. "use strict";
  15751. var BABYLON;
  15752. (function (BABYLON) {
  15753. /**
  15754. * Node is the basic class for all scene objects (Mesh, Light Camera).
  15755. */
  15756. var Node = /** @class */ (function () {
  15757. /**
  15758. * Creates a new Node
  15759. * @param {string} name - the name and id to be given to this node
  15760. * @param {BABYLON.Scene} the scene this node will be added to
  15761. */
  15762. function Node(name, scene) {
  15763. if (scene === void 0) { scene = null; }
  15764. /**
  15765. * Gets or sets a string used to store user defined state for the node
  15766. */
  15767. this.state = "";
  15768. /**
  15769. * Gets or sets an object used to store user defined information for the node
  15770. */
  15771. this.metadata = null;
  15772. /**
  15773. * Gets or sets a boolean used to define if the node must be serialized
  15774. */
  15775. this.doNotSerialize = false;
  15776. /** @ignore */
  15777. this._isDisposed = false;
  15778. /**
  15779. * Gets a list of {BABYLON.Animation} associated with the node
  15780. */
  15781. this.animations = new Array();
  15782. this._ranges = {};
  15783. this._isEnabled = true;
  15784. this._isReady = true;
  15785. /** @ignore */
  15786. this._currentRenderId = -1;
  15787. this._parentRenderId = -1;
  15788. this._animationPropertiesOverride = null;
  15789. /**
  15790. * An event triggered when the mesh is disposed
  15791. * @type {BABYLON.Observable}
  15792. */
  15793. this.onDisposeObservable = new BABYLON.Observable();
  15794. // Behaviors
  15795. this._behaviors = new Array();
  15796. this.name = name;
  15797. this.id = name;
  15798. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  15799. this.uniqueId = this._scene.getUniqueId();
  15800. this._initCache();
  15801. }
  15802. /**
  15803. * Gets a boolean indicating if the node has been disposed
  15804. * @returns true if the node was disposed
  15805. */
  15806. Node.prototype.isDisposed = function () {
  15807. return this._isDisposed;
  15808. };
  15809. Object.defineProperty(Node.prototype, "parent", {
  15810. get: function () {
  15811. return this._parentNode;
  15812. },
  15813. /**
  15814. * Gets or sets the parent of the node
  15815. */
  15816. set: function (parent) {
  15817. if (this._parentNode === parent) {
  15818. return;
  15819. }
  15820. // Remove self from list of children of parent
  15821. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  15822. var index = this._parentNode._children.indexOf(this);
  15823. if (index !== -1) {
  15824. this._parentNode._children.splice(index, 1);
  15825. }
  15826. }
  15827. // Store new parent
  15828. this._parentNode = parent;
  15829. // Add as child to new parent
  15830. if (this._parentNode) {
  15831. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  15832. this._parentNode._children = new Array();
  15833. }
  15834. this._parentNode._children.push(this);
  15835. }
  15836. },
  15837. enumerable: true,
  15838. configurable: true
  15839. });
  15840. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  15841. /**
  15842. * Gets or sets the animation properties override
  15843. */
  15844. get: function () {
  15845. return this._animationPropertiesOverride;
  15846. },
  15847. set: function (value) {
  15848. this._animationPropertiesOverride = value;
  15849. },
  15850. enumerable: true,
  15851. configurable: true
  15852. });
  15853. /**
  15854. * Gets a string idenfifying the name of the class
  15855. * @returns "Node" string
  15856. */
  15857. Node.prototype.getClassName = function () {
  15858. return "Node";
  15859. };
  15860. Object.defineProperty(Node.prototype, "onDispose", {
  15861. /**
  15862. * Sets a callback that will be raised when the node will be disposed
  15863. */
  15864. set: function (callback) {
  15865. if (this._onDisposeObserver) {
  15866. this.onDisposeObservable.remove(this._onDisposeObserver);
  15867. }
  15868. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  15869. },
  15870. enumerable: true,
  15871. configurable: true
  15872. });
  15873. /**
  15874. * Gets the scene of the node
  15875. * @returns a {BABYLON.Scene}
  15876. */
  15877. Node.prototype.getScene = function () {
  15878. return this._scene;
  15879. };
  15880. /**
  15881. * Gets the engine of the node
  15882. * @returns a {BABYLON.Engine}
  15883. */
  15884. Node.prototype.getEngine = function () {
  15885. return this._scene.getEngine();
  15886. };
  15887. /**
  15888. * Attach a behavior to the node
  15889. * @see http://doc.babylonjs.com/features/behaviour
  15890. * @param behavior defines the behavior to attach
  15891. * @returns the current Node
  15892. */
  15893. Node.prototype.addBehavior = function (behavior) {
  15894. var _this = this;
  15895. var index = this._behaviors.indexOf(behavior);
  15896. if (index !== -1) {
  15897. return this;
  15898. }
  15899. behavior.init();
  15900. if (this._scene.isLoading) {
  15901. // We defer the attach when the scene will be loaded
  15902. var observer = this._scene.onDataLoadedObservable.add(function () {
  15903. behavior.attach(_this);
  15904. setTimeout(function () {
  15905. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  15906. _this._scene.onDataLoadedObservable.remove(observer);
  15907. }, 0);
  15908. });
  15909. }
  15910. else {
  15911. behavior.attach(this);
  15912. }
  15913. this._behaviors.push(behavior);
  15914. return this;
  15915. };
  15916. /**
  15917. * Remove an attached behavior
  15918. * @see http://doc.babylonjs.com/features/behaviour
  15919. * @param behavior defines the behavior to attach
  15920. * @returns the current Node
  15921. */
  15922. Node.prototype.removeBehavior = function (behavior) {
  15923. var index = this._behaviors.indexOf(behavior);
  15924. if (index === -1) {
  15925. return this;
  15926. }
  15927. this._behaviors[index].detach();
  15928. this._behaviors.splice(index, 1);
  15929. return this;
  15930. };
  15931. Object.defineProperty(Node.prototype, "behaviors", {
  15932. /**
  15933. * Gets the list of attached behaviors
  15934. * @see http://doc.babylonjs.com/features/behaviour
  15935. */
  15936. get: function () {
  15937. return this._behaviors;
  15938. },
  15939. enumerable: true,
  15940. configurable: true
  15941. });
  15942. /**
  15943. * Gets an attached behavior by name
  15944. * @param name defines the name of the behavior to look for
  15945. * @see http://doc.babylonjs.com/features/behaviour
  15946. * @returns null if behavior was not found else the requested behavior
  15947. */
  15948. Node.prototype.getBehaviorByName = function (name) {
  15949. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  15950. var behavior = _a[_i];
  15951. if (behavior.name === name) {
  15952. return behavior;
  15953. }
  15954. }
  15955. return null;
  15956. };
  15957. /**
  15958. * Returns the world matrix of the node
  15959. * @returns a matrix containing the node's world matrix
  15960. */
  15961. Node.prototype.getWorldMatrix = function () {
  15962. return BABYLON.Matrix.Identity();
  15963. };
  15964. // override it in derived class if you add new variables to the cache
  15965. // and call the parent class method
  15966. /** @ignore */
  15967. Node.prototype._initCache = function () {
  15968. this._cache = {};
  15969. this._cache.parent = undefined;
  15970. };
  15971. /** @ignore */
  15972. Node.prototype.updateCache = function (force) {
  15973. if (!force && this.isSynchronized())
  15974. return;
  15975. this._cache.parent = this.parent;
  15976. this._updateCache();
  15977. };
  15978. // override it in derived class if you add new variables to the cache
  15979. // and call the parent class method if !ignoreParentClass
  15980. /** @ignore */
  15981. Node.prototype._updateCache = function (ignoreParentClass) {
  15982. };
  15983. // override it in derived class if you add new variables to the cache
  15984. /** @ignore */
  15985. Node.prototype._isSynchronized = function () {
  15986. return true;
  15987. };
  15988. /** @ignore */
  15989. Node.prototype._markSyncedWithParent = function () {
  15990. if (this.parent) {
  15991. this._parentRenderId = this.parent._currentRenderId;
  15992. }
  15993. };
  15994. /** @ignore */
  15995. Node.prototype.isSynchronizedWithParent = function () {
  15996. if (!this.parent) {
  15997. return true;
  15998. }
  15999. if (this._parentRenderId !== this.parent._currentRenderId) {
  16000. return false;
  16001. }
  16002. return this.parent.isSynchronized();
  16003. };
  16004. /** @ignore */
  16005. Node.prototype.isSynchronized = function (updateCache) {
  16006. var check = this.hasNewParent();
  16007. check = check || !this.isSynchronizedWithParent();
  16008. check = check || !this._isSynchronized();
  16009. if (updateCache)
  16010. this.updateCache(true);
  16011. return !check;
  16012. };
  16013. /** @ignore */
  16014. Node.prototype.hasNewParent = function (update) {
  16015. if (this._cache.parent === this.parent)
  16016. return false;
  16017. if (update)
  16018. this._cache.parent = this.parent;
  16019. return true;
  16020. };
  16021. /**
  16022. * Is this node ready to be used/rendered
  16023. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  16024. * @return true if the node is ready
  16025. */
  16026. Node.prototype.isReady = function (completeCheck) {
  16027. if (completeCheck === void 0) { completeCheck = false; }
  16028. return this._isReady;
  16029. };
  16030. /**
  16031. * Is this node enabled?
  16032. * 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
  16033. * @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
  16034. * @return whether this node (and its parent) is enabled
  16035. * @see setEnabled
  16036. */
  16037. Node.prototype.isEnabled = function (checkAncestors) {
  16038. if (checkAncestors === void 0) { checkAncestors = true; }
  16039. if (checkAncestors === false) {
  16040. return this._isEnabled;
  16041. }
  16042. if (this._isEnabled === false) {
  16043. return false;
  16044. }
  16045. if (this.parent !== undefined && this.parent !== null) {
  16046. return this.parent.isEnabled(checkAncestors);
  16047. }
  16048. return true;
  16049. };
  16050. /**
  16051. * Set the enabled state of this node
  16052. * @param value defines the new enabled state
  16053. * @see isEnabled
  16054. */
  16055. Node.prototype.setEnabled = function (value) {
  16056. this._isEnabled = value;
  16057. };
  16058. /**
  16059. * Is this node a descendant of the given node?
  16060. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  16061. * @param ancestor defines the parent node to inspect
  16062. * @see parent
  16063. * @returns a boolean indicating if this node is a descendant of the given node
  16064. */
  16065. Node.prototype.isDescendantOf = function (ancestor) {
  16066. if (this.parent) {
  16067. if (this.parent === ancestor) {
  16068. return true;
  16069. }
  16070. return this.parent.isDescendantOf(ancestor);
  16071. }
  16072. return false;
  16073. };
  16074. /** @ignore */
  16075. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  16076. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  16077. if (!this._children) {
  16078. return;
  16079. }
  16080. for (var index = 0; index < this._children.length; index++) {
  16081. var item = this._children[index];
  16082. if (!predicate || predicate(item)) {
  16083. results.push(item);
  16084. }
  16085. if (!directDescendantsOnly) {
  16086. item._getDescendants(results, false, predicate);
  16087. }
  16088. }
  16089. };
  16090. /**
  16091. * Will return all nodes that have this node as ascendant
  16092. * @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
  16093. * @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
  16094. * @return all children nodes of all types
  16095. */
  16096. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  16097. var results = new Array();
  16098. this._getDescendants(results, directDescendantsOnly, predicate);
  16099. return results;
  16100. };
  16101. /**
  16102. * Get all child-meshes of this node
  16103. * @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
  16104. * @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
  16105. * @returns an array of {BABYLON.AbstractMesh}
  16106. */
  16107. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  16108. var results = [];
  16109. this._getDescendants(results, directDescendantsOnly, function (node) {
  16110. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  16111. });
  16112. return results;
  16113. };
  16114. /**
  16115. * Get all child-transformNodes of this node
  16116. * @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
  16117. * @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
  16118. * @returns an array of {BABYLON.TransformNode}
  16119. */
  16120. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  16121. var results = [];
  16122. this._getDescendants(results, directDescendantsOnly, function (node) {
  16123. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  16124. });
  16125. return results;
  16126. };
  16127. /**
  16128. * Get all direct children of this node
  16129. * @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
  16130. * @returns an array of {BABYLON.Node}
  16131. */
  16132. Node.prototype.getChildren = function (predicate) {
  16133. return this.getDescendants(true, predicate);
  16134. };
  16135. /** @ignore */
  16136. Node.prototype._setReady = function (state) {
  16137. if (state === this._isReady) {
  16138. return;
  16139. }
  16140. if (!state) {
  16141. this._isReady = false;
  16142. return;
  16143. }
  16144. if (this.onReady) {
  16145. this.onReady(this);
  16146. }
  16147. this._isReady = true;
  16148. };
  16149. /**
  16150. * Get an animation by name
  16151. * @param name defines the name of the animation to look for
  16152. * @returns null if not found else the requested animation
  16153. */
  16154. Node.prototype.getAnimationByName = function (name) {
  16155. for (var i = 0; i < this.animations.length; i++) {
  16156. var animation = this.animations[i];
  16157. if (animation.name === name) {
  16158. return animation;
  16159. }
  16160. }
  16161. return null;
  16162. };
  16163. /**
  16164. * Creates an animation range for this node
  16165. * @param name defines the name of the range
  16166. * @param from defines the starting key
  16167. * @param to defines the end key
  16168. */
  16169. Node.prototype.createAnimationRange = function (name, from, to) {
  16170. // check name not already in use
  16171. if (!this._ranges[name]) {
  16172. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  16173. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  16174. if (this.animations[i]) {
  16175. this.animations[i].createRange(name, from, to);
  16176. }
  16177. }
  16178. }
  16179. };
  16180. /**
  16181. * Delete a specific animation range
  16182. * @param name defines the name of the range to delete
  16183. * @param deleteFrames defines if animation frames from the range must be deleted as well
  16184. */
  16185. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  16186. if (deleteFrames === void 0) { deleteFrames = true; }
  16187. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  16188. if (this.animations[i]) {
  16189. this.animations[i].deleteRange(name, deleteFrames);
  16190. }
  16191. }
  16192. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  16193. };
  16194. /**
  16195. * Get an animation range by name
  16196. * @param name defines the name of the animation range to look for
  16197. * @returns null if not found else the requested animation range
  16198. */
  16199. Node.prototype.getAnimationRange = function (name) {
  16200. return this._ranges[name];
  16201. };
  16202. /**
  16203. * Will start the animation sequence
  16204. * @param name defines the range frames for animation sequence
  16205. * @param loop defines if the animation should loop (false by default)
  16206. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  16207. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  16208. * @returns the object created for this animation. If range does not exist, it will return null
  16209. */
  16210. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  16211. var range = this.getAnimationRange(name);
  16212. if (!range) {
  16213. return null;
  16214. }
  16215. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  16216. };
  16217. /**
  16218. * Serialize animation ranges into a JSON compatible object
  16219. * @returns serialization object
  16220. */
  16221. Node.prototype.serializeAnimationRanges = function () {
  16222. var serializationRanges = [];
  16223. for (var name in this._ranges) {
  16224. var localRange = this._ranges[name];
  16225. if (!localRange) {
  16226. continue;
  16227. }
  16228. var range = {};
  16229. range.name = name;
  16230. range.from = localRange.from;
  16231. range.to = localRange.to;
  16232. serializationRanges.push(range);
  16233. }
  16234. return serializationRanges;
  16235. };
  16236. /**
  16237. * Computes the world matrix of the node
  16238. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  16239. * @returns the world matrix
  16240. */
  16241. Node.prototype.computeWorldMatrix = function (force) {
  16242. return BABYLON.Matrix.Identity();
  16243. };
  16244. /**
  16245. * Releases resources associated with this node.
  16246. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  16247. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  16248. */
  16249. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  16250. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  16251. if (!doNotRecurse) {
  16252. var nodes = this.getDescendants(true);
  16253. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  16254. var node = nodes_1[_i];
  16255. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  16256. }
  16257. }
  16258. else {
  16259. var transformNodes = this.getChildTransformNodes(true);
  16260. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  16261. var transformNode = transformNodes_1[_a];
  16262. transformNode.parent = null;
  16263. transformNode.computeWorldMatrix(true);
  16264. }
  16265. }
  16266. this.parent = null;
  16267. // Callback
  16268. this.onDisposeObservable.notifyObservers(this);
  16269. this.onDisposeObservable.clear();
  16270. // Behaviors
  16271. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  16272. var behavior = _c[_b];
  16273. behavior.detach();
  16274. }
  16275. this._behaviors = [];
  16276. this._isDisposed = true;
  16277. };
  16278. /**
  16279. * Parse animation range data from a serialization object and store them into a given node
  16280. * @param node defines where to store the animation ranges
  16281. * @param parsedNode defines the serialization object to read data from
  16282. * @param scene defines the hosting scene
  16283. */
  16284. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  16285. if (parsedNode.ranges) {
  16286. for (var index = 0; index < parsedNode.ranges.length; index++) {
  16287. var data = parsedNode.ranges[index];
  16288. node.createAnimationRange(data.name, data.from, data.to);
  16289. }
  16290. }
  16291. };
  16292. __decorate([
  16293. BABYLON.serialize()
  16294. ], Node.prototype, "name", void 0);
  16295. __decorate([
  16296. BABYLON.serialize()
  16297. ], Node.prototype, "id", void 0);
  16298. __decorate([
  16299. BABYLON.serialize()
  16300. ], Node.prototype, "uniqueId", void 0);
  16301. __decorate([
  16302. BABYLON.serialize()
  16303. ], Node.prototype, "state", void 0);
  16304. __decorate([
  16305. BABYLON.serialize()
  16306. ], Node.prototype, "metadata", void 0);
  16307. return Node;
  16308. }());
  16309. BABYLON.Node = Node;
  16310. })(BABYLON || (BABYLON = {}));
  16311. //# sourceMappingURL=babylon.node.js.map
  16312. "use strict";
  16313. var BABYLON;
  16314. (function (BABYLON) {
  16315. var BoundingSphere = /** @class */ (function () {
  16316. function BoundingSphere(minimum, maximum) {
  16317. this.minimum = minimum;
  16318. this.maximum = maximum;
  16319. this._tempRadiusVector = BABYLON.Vector3.Zero();
  16320. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  16321. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  16322. this.radius = distance * 0.5;
  16323. this.centerWorld = BABYLON.Vector3.Zero();
  16324. this._update(BABYLON.Matrix.Identity());
  16325. }
  16326. // Methods
  16327. BoundingSphere.prototype._update = function (world) {
  16328. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  16329. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  16330. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  16331. };
  16332. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  16333. for (var i = 0; i < 6; i++) {
  16334. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  16335. return false;
  16336. }
  16337. return true;
  16338. };
  16339. BoundingSphere.prototype.intersectsPoint = function (point) {
  16340. var x = this.centerWorld.x - point.x;
  16341. var y = this.centerWorld.y - point.y;
  16342. var z = this.centerWorld.z - point.z;
  16343. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  16344. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  16345. return false;
  16346. return true;
  16347. };
  16348. // Statics
  16349. BoundingSphere.Intersects = function (sphere0, sphere1) {
  16350. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  16351. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  16352. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  16353. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  16354. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  16355. return false;
  16356. return true;
  16357. };
  16358. return BoundingSphere;
  16359. }());
  16360. BABYLON.BoundingSphere = BoundingSphere;
  16361. })(BABYLON || (BABYLON = {}));
  16362. //# sourceMappingURL=babylon.boundingSphere.js.map
  16363. "use strict";
  16364. var BABYLON;
  16365. (function (BABYLON) {
  16366. var BoundingBox = /** @class */ (function () {
  16367. function BoundingBox(minimum, maximum) {
  16368. this.minimum = minimum;
  16369. this.maximum = maximum;
  16370. this.vectors = new Array();
  16371. this.vectorsWorld = new Array();
  16372. // Bounding vectors
  16373. this.vectors.push(this.minimum.clone());
  16374. this.vectors.push(this.maximum.clone());
  16375. this.vectors.push(this.minimum.clone());
  16376. this.vectors[2].x = this.maximum.x;
  16377. this.vectors.push(this.minimum.clone());
  16378. this.vectors[3].y = this.maximum.y;
  16379. this.vectors.push(this.minimum.clone());
  16380. this.vectors[4].z = this.maximum.z;
  16381. this.vectors.push(this.maximum.clone());
  16382. this.vectors[5].z = this.minimum.z;
  16383. this.vectors.push(this.maximum.clone());
  16384. this.vectors[6].x = this.minimum.x;
  16385. this.vectors.push(this.maximum.clone());
  16386. this.vectors[7].y = this.minimum.y;
  16387. // OBB
  16388. this.center = this.maximum.add(this.minimum).scale(0.5);
  16389. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  16390. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  16391. // World
  16392. for (var index = 0; index < this.vectors.length; index++) {
  16393. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  16394. }
  16395. this.minimumWorld = BABYLON.Vector3.Zero();
  16396. this.maximumWorld = BABYLON.Vector3.Zero();
  16397. this.centerWorld = BABYLON.Vector3.Zero();
  16398. this.extendSizeWorld = BABYLON.Vector3.Zero();
  16399. this._update(BABYLON.Matrix.Identity());
  16400. }
  16401. // Methods
  16402. BoundingBox.prototype.getWorldMatrix = function () {
  16403. return this._worldMatrix;
  16404. };
  16405. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  16406. this._worldMatrix.copyFrom(matrix);
  16407. return this;
  16408. };
  16409. BoundingBox.prototype._update = function (world) {
  16410. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  16411. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  16412. for (var index = 0; index < this.vectors.length; index++) {
  16413. var v = this.vectorsWorld[index];
  16414. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  16415. if (v.x < this.minimumWorld.x)
  16416. this.minimumWorld.x = v.x;
  16417. if (v.y < this.minimumWorld.y)
  16418. this.minimumWorld.y = v.y;
  16419. if (v.z < this.minimumWorld.z)
  16420. this.minimumWorld.z = v.z;
  16421. if (v.x > this.maximumWorld.x)
  16422. this.maximumWorld.x = v.x;
  16423. if (v.y > this.maximumWorld.y)
  16424. this.maximumWorld.y = v.y;
  16425. if (v.z > this.maximumWorld.z)
  16426. this.maximumWorld.z = v.z;
  16427. }
  16428. // Extend
  16429. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  16430. this.extendSizeWorld.scaleInPlace(0.5);
  16431. // OBB
  16432. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  16433. this.centerWorld.scaleInPlace(0.5);
  16434. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  16435. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  16436. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  16437. this._worldMatrix = world;
  16438. };
  16439. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  16440. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  16441. };
  16442. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16443. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  16444. };
  16445. BoundingBox.prototype.intersectsPoint = function (point) {
  16446. var delta = -BABYLON.Epsilon;
  16447. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  16448. return false;
  16449. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  16450. return false;
  16451. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  16452. return false;
  16453. return true;
  16454. };
  16455. BoundingBox.prototype.intersectsSphere = function (sphere) {
  16456. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  16457. };
  16458. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  16459. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  16460. return false;
  16461. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  16462. return false;
  16463. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  16464. return false;
  16465. return true;
  16466. };
  16467. // Statics
  16468. BoundingBox.Intersects = function (box0, box1) {
  16469. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  16470. return false;
  16471. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  16472. return false;
  16473. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  16474. return false;
  16475. return true;
  16476. };
  16477. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  16478. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  16479. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  16480. return (num <= (sphereRadius * sphereRadius));
  16481. };
  16482. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  16483. for (var p = 0; p < 6; p++) {
  16484. for (var i = 0; i < 8; i++) {
  16485. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  16486. return false;
  16487. }
  16488. }
  16489. }
  16490. return true;
  16491. };
  16492. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  16493. for (var p = 0; p < 6; p++) {
  16494. var inCount = 8;
  16495. for (var i = 0; i < 8; i++) {
  16496. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  16497. --inCount;
  16498. }
  16499. else {
  16500. break;
  16501. }
  16502. }
  16503. if (inCount === 0)
  16504. return false;
  16505. }
  16506. return true;
  16507. };
  16508. return BoundingBox;
  16509. }());
  16510. BABYLON.BoundingBox = BoundingBox;
  16511. })(BABYLON || (BABYLON = {}));
  16512. //# sourceMappingURL=babylon.boundingBox.js.map
  16513. "use strict";
  16514. var BABYLON;
  16515. (function (BABYLON) {
  16516. var computeBoxExtents = function (axis, box) {
  16517. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  16518. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  16519. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  16520. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  16521. var r = r0 + r1 + r2;
  16522. return {
  16523. min: p - r,
  16524. max: p + r
  16525. };
  16526. };
  16527. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  16528. var axisOverlap = function (axis, box0, box1) {
  16529. var result0 = computeBoxExtents(axis, box0);
  16530. var result1 = computeBoxExtents(axis, box1);
  16531. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  16532. };
  16533. var BoundingInfo = /** @class */ (function () {
  16534. function BoundingInfo(minimum, maximum) {
  16535. this.minimum = minimum;
  16536. this.maximum = maximum;
  16537. this._isLocked = false;
  16538. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  16539. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  16540. }
  16541. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  16542. get: function () {
  16543. return this._isLocked;
  16544. },
  16545. set: function (value) {
  16546. this._isLocked = value;
  16547. },
  16548. enumerable: true,
  16549. configurable: true
  16550. });
  16551. // Methods
  16552. BoundingInfo.prototype.update = function (world) {
  16553. if (this._isLocked) {
  16554. return;
  16555. }
  16556. this.boundingBox._update(world);
  16557. this.boundingSphere._update(world);
  16558. };
  16559. /**
  16560. * Recreate the bounding info to be centered around a specific point given a specific extend.
  16561. * @param center New center of the bounding info
  16562. * @param extend New extend of the bounding info
  16563. */
  16564. BoundingInfo.prototype.centerOn = function (center, extend) {
  16565. this.minimum = center.subtract(extend);
  16566. this.maximum = center.add(extend);
  16567. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  16568. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  16569. return this;
  16570. };
  16571. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  16572. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  16573. return false;
  16574. return this.boundingBox.isInFrustum(frustumPlanes);
  16575. };
  16576. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  16577. /**
  16578. * Gets the world distance between the min and max points of the bounding box
  16579. */
  16580. get: function () {
  16581. var boundingBox = this.boundingBox;
  16582. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  16583. return size.length();
  16584. },
  16585. enumerable: true,
  16586. configurable: true
  16587. });
  16588. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16589. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  16590. };
  16591. BoundingInfo.prototype._checkCollision = function (collider) {
  16592. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  16593. };
  16594. BoundingInfo.prototype.intersectsPoint = function (point) {
  16595. if (!this.boundingSphere.centerWorld) {
  16596. return false;
  16597. }
  16598. if (!this.boundingSphere.intersectsPoint(point)) {
  16599. return false;
  16600. }
  16601. if (!this.boundingBox.intersectsPoint(point)) {
  16602. return false;
  16603. }
  16604. return true;
  16605. };
  16606. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  16607. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  16608. return false;
  16609. }
  16610. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  16611. return false;
  16612. }
  16613. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  16614. return false;
  16615. }
  16616. if (!precise) {
  16617. return true;
  16618. }
  16619. var box0 = this.boundingBox;
  16620. var box1 = boundingInfo.boundingBox;
  16621. if (!axisOverlap(box0.directions[0], box0, box1))
  16622. return false;
  16623. if (!axisOverlap(box0.directions[1], box0, box1))
  16624. return false;
  16625. if (!axisOverlap(box0.directions[2], box0, box1))
  16626. return false;
  16627. if (!axisOverlap(box1.directions[0], box0, box1))
  16628. return false;
  16629. if (!axisOverlap(box1.directions[1], box0, box1))
  16630. return false;
  16631. if (!axisOverlap(box1.directions[2], box0, box1))
  16632. return false;
  16633. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  16634. return false;
  16635. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  16636. return false;
  16637. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  16638. return false;
  16639. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  16640. return false;
  16641. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  16642. return false;
  16643. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  16644. return false;
  16645. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  16646. return false;
  16647. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  16648. return false;
  16649. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  16650. return false;
  16651. return true;
  16652. };
  16653. return BoundingInfo;
  16654. }());
  16655. BABYLON.BoundingInfo = BoundingInfo;
  16656. })(BABYLON || (BABYLON = {}));
  16657. //# sourceMappingURL=babylon.boundingInfo.js.map
  16658. "use strict";
  16659. var BABYLON;
  16660. (function (BABYLON) {
  16661. var TransformNode = /** @class */ (function (_super) {
  16662. __extends(TransformNode, _super);
  16663. function TransformNode(name, scene, isPure) {
  16664. if (scene === void 0) { scene = null; }
  16665. if (isPure === void 0) { isPure = true; }
  16666. var _this = _super.call(this, name, scene) || this;
  16667. // Properties
  16668. _this._rotation = BABYLON.Vector3.Zero();
  16669. _this._scaling = BABYLON.Vector3.One();
  16670. _this._isDirty = false;
  16671. _this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  16672. _this.scalingDeterminant = 1;
  16673. _this.infiniteDistance = false;
  16674. _this.position = BABYLON.Vector3.Zero();
  16675. _this._localWorld = BABYLON.Matrix.Zero();
  16676. _this._worldMatrix = BABYLON.Matrix.Zero();
  16677. _this._worldMatrixDeterminant = 0;
  16678. _this._absolutePosition = BABYLON.Vector3.Zero();
  16679. _this._pivotMatrix = BABYLON.Matrix.Identity();
  16680. _this._postMultiplyPivotMatrix = false;
  16681. _this._isWorldMatrixFrozen = false;
  16682. /**
  16683. * An event triggered after the world matrix is updated
  16684. * @type {BABYLON.Observable}
  16685. */
  16686. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  16687. _this._nonUniformScaling = false;
  16688. if (isPure) {
  16689. _this.getScene().addTransformNode(_this);
  16690. }
  16691. return _this;
  16692. }
  16693. /**
  16694. * Gets a string idenfifying the name of the class
  16695. * @returns "TransformNode" string
  16696. */
  16697. TransformNode.prototype.getClassName = function () {
  16698. return "TransformNode";
  16699. };
  16700. Object.defineProperty(TransformNode.prototype, "rotation", {
  16701. /**
  16702. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  16703. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  16704. * Default : (0.0, 0.0, 0.0)
  16705. */
  16706. get: function () {
  16707. return this._rotation;
  16708. },
  16709. set: function (newRotation) {
  16710. this._rotation = newRotation;
  16711. },
  16712. enumerable: true,
  16713. configurable: true
  16714. });
  16715. Object.defineProperty(TransformNode.prototype, "scaling", {
  16716. /**
  16717. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16718. * Default : (1.0, 1.0, 1.0)
  16719. */
  16720. get: function () {
  16721. return this._scaling;
  16722. },
  16723. /**
  16724. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16725. * Default : (1.0, 1.0, 1.0)
  16726. */
  16727. set: function (newScaling) {
  16728. this._scaling = newScaling;
  16729. },
  16730. enumerable: true,
  16731. configurable: true
  16732. });
  16733. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  16734. /**
  16735. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  16736. * It's null by default.
  16737. * 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)
  16738. */
  16739. get: function () {
  16740. return this._rotationQuaternion;
  16741. },
  16742. set: function (quaternion) {
  16743. this._rotationQuaternion = quaternion;
  16744. //reset the rotation vector.
  16745. if (quaternion && this.rotation.length()) {
  16746. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  16747. }
  16748. },
  16749. enumerable: true,
  16750. configurable: true
  16751. });
  16752. /**
  16753. * Returns the latest update of the World matrix
  16754. * Returns a Matrix.
  16755. */
  16756. TransformNode.prototype.getWorldMatrix = function () {
  16757. if (this._currentRenderId !== this.getScene().getRenderId()) {
  16758. this.computeWorldMatrix();
  16759. }
  16760. return this._worldMatrix;
  16761. };
  16762. /**
  16763. * Returns the latest update of the World matrix determinant.
  16764. */
  16765. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  16766. return this._worldMatrixDeterminant;
  16767. };
  16768. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  16769. /**
  16770. * Returns directly the latest state of the mesh World matrix.
  16771. * A Matrix is returned.
  16772. */
  16773. get: function () {
  16774. return this._worldMatrix;
  16775. },
  16776. enumerable: true,
  16777. configurable: true
  16778. });
  16779. /**
  16780. * Copies the paramater passed Matrix into the mesh Pose matrix.
  16781. * Returns the AbstractMesh.
  16782. */
  16783. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  16784. this._poseMatrix.copyFrom(matrix);
  16785. return this;
  16786. };
  16787. /**
  16788. * Returns the mesh Pose matrix.
  16789. * Returned object : Matrix
  16790. */
  16791. TransformNode.prototype.getPoseMatrix = function () {
  16792. return this._poseMatrix;
  16793. };
  16794. TransformNode.prototype._isSynchronized = function () {
  16795. if (this._isDirty) {
  16796. return false;
  16797. }
  16798. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE)
  16799. return false;
  16800. if (this._cache.pivotMatrixUpdated) {
  16801. return false;
  16802. }
  16803. if (this.infiniteDistance) {
  16804. return false;
  16805. }
  16806. if (!this._cache.position.equals(this.position))
  16807. return false;
  16808. if (this.rotationQuaternion) {
  16809. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  16810. return false;
  16811. }
  16812. if (!this._cache.rotation.equals(this.rotation))
  16813. return false;
  16814. if (!this._cache.scaling.equals(this.scaling))
  16815. return false;
  16816. return true;
  16817. };
  16818. TransformNode.prototype._initCache = function () {
  16819. _super.prototype._initCache.call(this);
  16820. this._cache.localMatrixUpdated = false;
  16821. this._cache.position = BABYLON.Vector3.Zero();
  16822. this._cache.scaling = BABYLON.Vector3.Zero();
  16823. this._cache.rotation = BABYLON.Vector3.Zero();
  16824. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  16825. this._cache.billboardMode = -1;
  16826. };
  16827. TransformNode.prototype.markAsDirty = function (property) {
  16828. if (property === "rotation") {
  16829. this.rotationQuaternion = null;
  16830. }
  16831. this._currentRenderId = Number.MAX_VALUE;
  16832. this._isDirty = true;
  16833. return this;
  16834. };
  16835. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  16836. /**
  16837. * Returns the current mesh absolute position.
  16838. * Retuns a Vector3.
  16839. */
  16840. get: function () {
  16841. return this._absolutePosition;
  16842. },
  16843. enumerable: true,
  16844. configurable: true
  16845. });
  16846. /**
  16847. * Sets a new matrix to apply before all other transformation
  16848. * @param matrix defines the transform matrix
  16849. * @returns the current TransformNode
  16850. */
  16851. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  16852. return this.setPivotMatrix(matrix, false);
  16853. };
  16854. /**
  16855. * Sets a new pivot matrix to the current node
  16856. * @param matrix defines the new pivot matrix to use
  16857. * @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
  16858. * @returns the current TransformNode
  16859. */
  16860. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  16861. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  16862. this._pivotMatrix = matrix.clone();
  16863. this._cache.pivotMatrixUpdated = true;
  16864. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  16865. if (this._postMultiplyPivotMatrix) {
  16866. if (!this._pivotMatrixInverse) {
  16867. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  16868. }
  16869. else {
  16870. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  16871. }
  16872. }
  16873. return this;
  16874. };
  16875. /**
  16876. * Returns the mesh pivot matrix.
  16877. * Default : Identity.
  16878. * A Matrix is returned.
  16879. */
  16880. TransformNode.prototype.getPivotMatrix = function () {
  16881. return this._pivotMatrix;
  16882. };
  16883. /**
  16884. * Prevents the World matrix to be computed any longer.
  16885. * Returns the AbstractMesh.
  16886. */
  16887. TransformNode.prototype.freezeWorldMatrix = function () {
  16888. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  16889. this.computeWorldMatrix(true);
  16890. this._isWorldMatrixFrozen = true;
  16891. return this;
  16892. };
  16893. /**
  16894. * Allows back the World matrix computation.
  16895. * Returns the AbstractMesh.
  16896. */
  16897. TransformNode.prototype.unfreezeWorldMatrix = function () {
  16898. this._isWorldMatrixFrozen = false;
  16899. this.computeWorldMatrix(true);
  16900. return this;
  16901. };
  16902. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  16903. /**
  16904. * True if the World matrix has been frozen.
  16905. * Returns a boolean.
  16906. */
  16907. get: function () {
  16908. return this._isWorldMatrixFrozen;
  16909. },
  16910. enumerable: true,
  16911. configurable: true
  16912. });
  16913. /**
  16914. * Retuns the mesh absolute position in the World.
  16915. * Returns a Vector3.
  16916. */
  16917. TransformNode.prototype.getAbsolutePosition = function () {
  16918. this.computeWorldMatrix();
  16919. return this._absolutePosition;
  16920. };
  16921. /**
  16922. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  16923. * Returns the AbstractMesh.
  16924. */
  16925. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  16926. if (!absolutePosition) {
  16927. return this;
  16928. }
  16929. var absolutePositionX;
  16930. var absolutePositionY;
  16931. var absolutePositionZ;
  16932. if (absolutePosition.x === undefined) {
  16933. if (arguments.length < 3) {
  16934. return this;
  16935. }
  16936. absolutePositionX = arguments[0];
  16937. absolutePositionY = arguments[1];
  16938. absolutePositionZ = arguments[2];
  16939. }
  16940. else {
  16941. absolutePositionX = absolutePosition.x;
  16942. absolutePositionY = absolutePosition.y;
  16943. absolutePositionZ = absolutePosition.z;
  16944. }
  16945. if (this.parent) {
  16946. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  16947. invertParentWorldMatrix.invert();
  16948. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  16949. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  16950. }
  16951. else {
  16952. this.position.x = absolutePositionX;
  16953. this.position.y = absolutePositionY;
  16954. this.position.z = absolutePositionZ;
  16955. }
  16956. return this;
  16957. };
  16958. /**
  16959. * Sets the mesh position in its local space.
  16960. * Returns the AbstractMesh.
  16961. */
  16962. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  16963. this.computeWorldMatrix();
  16964. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  16965. return this;
  16966. };
  16967. /**
  16968. * Returns the mesh position in the local space from the current World matrix values.
  16969. * Returns a new Vector3.
  16970. */
  16971. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  16972. this.computeWorldMatrix();
  16973. var invLocalWorldMatrix = this._localWorld.clone();
  16974. invLocalWorldMatrix.invert();
  16975. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  16976. };
  16977. /**
  16978. * Translates the mesh along the passed Vector3 in its local space.
  16979. * Returns the AbstractMesh.
  16980. */
  16981. TransformNode.prototype.locallyTranslate = function (vector3) {
  16982. this.computeWorldMatrix(true);
  16983. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  16984. return this;
  16985. };
  16986. /**
  16987. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  16988. * @param targetPoint the position (must be in same space as current mesh) to look at
  16989. * @param yawCor optional yaw (y-axis) correction in radians
  16990. * @param pitchCor optional pitch (x-axis) correction in radians
  16991. * @param rollCor optional roll (z-axis) correction in radians
  16992. * @param space the choosen space of the target
  16993. * @returns the TransformNode.
  16994. */
  16995. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  16996. if (yawCor === void 0) { yawCor = 0; }
  16997. if (pitchCor === void 0) { pitchCor = 0; }
  16998. if (rollCor === void 0) { rollCor = 0; }
  16999. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  17000. var dv = BABYLON.AbstractMesh._lookAtVectorCache;
  17001. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  17002. targetPoint.subtractToRef(pos, dv);
  17003. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  17004. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  17005. var pitch = Math.atan2(dv.y, len);
  17006. if (this.rotationQuaternion) {
  17007. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  17008. }
  17009. else {
  17010. this.rotation.x = pitch + pitchCor;
  17011. this.rotation.y = yaw + yawCor;
  17012. this.rotation.z = rollCor;
  17013. }
  17014. return this;
  17015. };
  17016. /**
  17017. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  17018. * This Vector3 is expressed in the World space.
  17019. */
  17020. TransformNode.prototype.getDirection = function (localAxis) {
  17021. var result = BABYLON.Vector3.Zero();
  17022. this.getDirectionToRef(localAxis, result);
  17023. return result;
  17024. };
  17025. /**
  17026. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  17027. * localAxis is expressed in the mesh local space.
  17028. * result is computed in the Wordl space from the mesh World matrix.
  17029. * Returns the AbstractMesh.
  17030. */
  17031. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  17032. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  17033. return this;
  17034. };
  17035. /**
  17036. * Sets a new pivot point to the current node
  17037. * @param point defines the new pivot point to use
  17038. * @param space defines if the point is in world or local space (local by default)
  17039. * @returns the current TransformNode
  17040. */
  17041. TransformNode.prototype.setPivotPoint = function (point, space) {
  17042. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  17043. if (this.getScene().getRenderId() == 0) {
  17044. this.computeWorldMatrix(true);
  17045. }
  17046. var wm = this.getWorldMatrix();
  17047. if (space == BABYLON.Space.WORLD) {
  17048. var tmat = BABYLON.Tmp.Matrix[0];
  17049. wm.invertToRef(tmat);
  17050. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  17051. }
  17052. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  17053. };
  17054. /**
  17055. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  17056. */
  17057. TransformNode.prototype.getPivotPoint = function () {
  17058. var point = BABYLON.Vector3.Zero();
  17059. this.getPivotPointToRef(point);
  17060. return point;
  17061. };
  17062. /**
  17063. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  17064. * Returns the AbstractMesh.
  17065. */
  17066. TransformNode.prototype.getPivotPointToRef = function (result) {
  17067. result.x = -this._pivotMatrix.m[12];
  17068. result.y = -this._pivotMatrix.m[13];
  17069. result.z = -this._pivotMatrix.m[14];
  17070. return this;
  17071. };
  17072. /**
  17073. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  17074. */
  17075. TransformNode.prototype.getAbsolutePivotPoint = function () {
  17076. var point = BABYLON.Vector3.Zero();
  17077. this.getAbsolutePivotPointToRef(point);
  17078. return point;
  17079. };
  17080. /**
  17081. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  17082. * Returns the AbstractMesh.
  17083. */
  17084. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  17085. result.x = this._pivotMatrix.m[12];
  17086. result.y = this._pivotMatrix.m[13];
  17087. result.z = this._pivotMatrix.m[14];
  17088. this.getPivotPointToRef(result);
  17089. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  17090. return this;
  17091. };
  17092. /**
  17093. * Defines the passed node as the parent of the current node.
  17094. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  17095. * Returns the TransformNode.
  17096. */
  17097. TransformNode.prototype.setParent = function (node) {
  17098. if (node === null) {
  17099. var rotation = BABYLON.Tmp.Quaternion[0];
  17100. var position = BABYLON.Tmp.Vector3[0];
  17101. var scale = BABYLON.Tmp.Vector3[1];
  17102. if (this.parent && this.parent.computeWorldMatrix) {
  17103. this.parent.computeWorldMatrix(true);
  17104. }
  17105. this.computeWorldMatrix(true);
  17106. this.getWorldMatrix().decompose(scale, rotation, position);
  17107. if (this.rotationQuaternion) {
  17108. this.rotationQuaternion.copyFrom(rotation);
  17109. }
  17110. else {
  17111. rotation.toEulerAnglesToRef(this.rotation);
  17112. }
  17113. this.scaling.x = scale.x;
  17114. this.scaling.y = scale.y;
  17115. this.scaling.z = scale.z;
  17116. this.position.x = position.x;
  17117. this.position.y = position.y;
  17118. this.position.z = position.z;
  17119. }
  17120. else {
  17121. var rotation = BABYLON.Tmp.Quaternion[0];
  17122. var position = BABYLON.Tmp.Vector3[0];
  17123. var scale = BABYLON.Tmp.Vector3[1];
  17124. var diffMatrix = BABYLON.Tmp.Matrix[0];
  17125. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  17126. this.computeWorldMatrix(true);
  17127. node.computeWorldMatrix(true);
  17128. node.getWorldMatrix().invertToRef(invParentMatrix);
  17129. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  17130. diffMatrix.decompose(scale, rotation, position);
  17131. if (this.rotationQuaternion) {
  17132. this.rotationQuaternion.copyFrom(rotation);
  17133. }
  17134. else {
  17135. rotation.toEulerAnglesToRef(this.rotation);
  17136. }
  17137. this.position.x = position.x;
  17138. this.position.y = position.y;
  17139. this.position.z = position.z;
  17140. this.scaling.x = scale.x;
  17141. this.scaling.y = scale.y;
  17142. this.scaling.z = scale.z;
  17143. }
  17144. this.parent = node;
  17145. return this;
  17146. };
  17147. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  17148. get: function () {
  17149. return this._nonUniformScaling;
  17150. },
  17151. enumerable: true,
  17152. configurable: true
  17153. });
  17154. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  17155. if (this._nonUniformScaling === value) {
  17156. return false;
  17157. }
  17158. this._nonUniformScaling = true;
  17159. return true;
  17160. };
  17161. /**
  17162. * Attach the current TransformNode to another TransformNode associated with a bone
  17163. * @param bone Bone affecting the TransformNode
  17164. * @param affectedTransformNode TransformNode associated with the bone
  17165. */
  17166. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  17167. this._transformToBoneReferal = affectedTransformNode;
  17168. this.parent = bone;
  17169. if (bone.getWorldMatrix().determinant() < 0) {
  17170. this.scalingDeterminant *= -1;
  17171. }
  17172. return this;
  17173. };
  17174. TransformNode.prototype.detachFromBone = function () {
  17175. if (!this.parent) {
  17176. return this;
  17177. }
  17178. if (this.parent.getWorldMatrix().determinant() < 0) {
  17179. this.scalingDeterminant *= -1;
  17180. }
  17181. this._transformToBoneReferal = null;
  17182. this.parent = null;
  17183. return this;
  17184. };
  17185. /**
  17186. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  17187. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  17188. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  17189. * The passed axis is also normalized.
  17190. * Returns the AbstractMesh.
  17191. */
  17192. TransformNode.prototype.rotate = function (axis, amount, space) {
  17193. axis.normalize();
  17194. if (!this.rotationQuaternion) {
  17195. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  17196. this.rotation = BABYLON.Vector3.Zero();
  17197. }
  17198. var rotationQuaternion;
  17199. if (!space || space === BABYLON.Space.LOCAL) {
  17200. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  17201. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  17202. }
  17203. else {
  17204. if (this.parent) {
  17205. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  17206. invertParentWorldMatrix.invert();
  17207. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  17208. }
  17209. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  17210. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  17211. }
  17212. return this;
  17213. };
  17214. /**
  17215. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  17216. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  17217. * The passed axis is also normalized.
  17218. * Returns the AbstractMesh.
  17219. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  17220. */
  17221. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  17222. axis.normalize();
  17223. if (!this.rotationQuaternion) {
  17224. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  17225. this.rotation.copyFromFloats(0, 0, 0);
  17226. }
  17227. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  17228. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  17229. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  17230. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  17231. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  17232. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  17233. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  17234. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  17235. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  17236. return this;
  17237. };
  17238. /**
  17239. * Translates the mesh along the axis vector for the passed distance in the given space.
  17240. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  17241. * Returns the AbstractMesh.
  17242. */
  17243. TransformNode.prototype.translate = function (axis, distance, space) {
  17244. var displacementVector = axis.scale(distance);
  17245. if (!space || space === BABYLON.Space.LOCAL) {
  17246. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  17247. this.setPositionWithLocalVector(tempV3);
  17248. }
  17249. else {
  17250. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  17251. }
  17252. return this;
  17253. };
  17254. /**
  17255. * Adds a rotation step to the mesh current rotation.
  17256. * x, y, z are Euler angles expressed in radians.
  17257. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  17258. * This means this rotation is made in the mesh local space only.
  17259. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  17260. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  17261. * ```javascript
  17262. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  17263. * ```
  17264. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  17265. * 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.
  17266. * Returns the AbstractMesh.
  17267. */
  17268. TransformNode.prototype.addRotation = function (x, y, z) {
  17269. var rotationQuaternion;
  17270. if (this.rotationQuaternion) {
  17271. rotationQuaternion = this.rotationQuaternion;
  17272. }
  17273. else {
  17274. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  17275. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  17276. }
  17277. var accumulation = BABYLON.Tmp.Quaternion[0];
  17278. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  17279. rotationQuaternion.multiplyInPlace(accumulation);
  17280. if (!this.rotationQuaternion) {
  17281. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  17282. }
  17283. return this;
  17284. };
  17285. /**
  17286. * Computes the mesh World matrix and returns it.
  17287. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  17288. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  17289. * If the parameter `force`is set to `true`, the actual computation is done.
  17290. * Returns the mesh World Matrix.
  17291. */
  17292. TransformNode.prototype.computeWorldMatrix = function (force) {
  17293. if (this._isWorldMatrixFrozen) {
  17294. return this._worldMatrix;
  17295. }
  17296. if (!force && this.isSynchronized(true)) {
  17297. return this._worldMatrix;
  17298. }
  17299. this._cache.position.copyFrom(this.position);
  17300. this._cache.scaling.copyFrom(this.scaling);
  17301. this._cache.pivotMatrixUpdated = false;
  17302. this._cache.billboardMode = this.billboardMode;
  17303. this._currentRenderId = this.getScene().getRenderId();
  17304. this._isDirty = false;
  17305. // Scaling
  17306. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  17307. // Rotation
  17308. //rotate, if quaternion is set and rotation was used
  17309. if (this.rotationQuaternion) {
  17310. var len = this.rotation.length();
  17311. if (len) {
  17312. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  17313. this.rotation.copyFromFloats(0, 0, 0);
  17314. }
  17315. }
  17316. if (this.rotationQuaternion) {
  17317. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  17318. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  17319. }
  17320. else {
  17321. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  17322. this._cache.rotation.copyFrom(this.rotation);
  17323. }
  17324. // Translation
  17325. var camera = this.getScene().activeCamera;
  17326. if (this.infiniteDistance && !this.parent && camera) {
  17327. var cameraWorldMatrix = camera.getWorldMatrix();
  17328. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  17329. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  17330. }
  17331. else {
  17332. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  17333. }
  17334. // Composing transformations
  17335. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  17336. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  17337. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  17338. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE && camera) {
  17339. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_ALL) !== BABYLON.AbstractMesh.BILLBOARDMODE_ALL) {
  17340. // Need to decompose each rotation here
  17341. var currentPosition = BABYLON.Tmp.Vector3[3];
  17342. if (this.parent && this.parent.getWorldMatrix) {
  17343. if (this._transformToBoneReferal) {
  17344. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  17345. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  17346. }
  17347. else {
  17348. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  17349. }
  17350. }
  17351. else {
  17352. currentPosition.copyFrom(this.position);
  17353. }
  17354. currentPosition.subtractInPlace(camera.globalPosition);
  17355. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  17356. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X) === BABYLON.AbstractMesh.BILLBOARDMODE_X) {
  17357. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  17358. }
  17359. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y) === BABYLON.AbstractMesh.BILLBOARDMODE_Y) {
  17360. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  17361. }
  17362. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z) === BABYLON.AbstractMesh.BILLBOARDMODE_Z) {
  17363. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  17364. }
  17365. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  17366. }
  17367. else {
  17368. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  17369. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  17370. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  17371. }
  17372. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  17373. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  17374. }
  17375. // Local world
  17376. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  17377. // Parent
  17378. if (this.parent && this.parent.getWorldMatrix) {
  17379. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  17380. if (this._transformToBoneReferal) {
  17381. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  17382. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  17383. }
  17384. else {
  17385. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  17386. }
  17387. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  17388. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  17389. this._worldMatrix.copyFrom(this._localWorld);
  17390. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  17391. }
  17392. else {
  17393. if (this._transformToBoneReferal) {
  17394. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  17395. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  17396. }
  17397. else {
  17398. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  17399. }
  17400. }
  17401. this._markSyncedWithParent();
  17402. }
  17403. else {
  17404. this._worldMatrix.copyFrom(this._localWorld);
  17405. }
  17406. // Post multiply inverse of pivotMatrix
  17407. if (this._postMultiplyPivotMatrix) {
  17408. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  17409. }
  17410. // Normal matrix
  17411. if (this.scaling.isNonUniform) {
  17412. this._updateNonUniformScalingState(true);
  17413. }
  17414. else if (this.parent && this.parent._nonUniformScaling) {
  17415. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  17416. }
  17417. else {
  17418. this._updateNonUniformScalingState(false);
  17419. }
  17420. this._afterComputeWorldMatrix();
  17421. // Absolute position
  17422. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  17423. // Callbacks
  17424. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  17425. if (!this._poseMatrix) {
  17426. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  17427. }
  17428. // Cache the determinant
  17429. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  17430. return this._worldMatrix;
  17431. };
  17432. TransformNode.prototype._afterComputeWorldMatrix = function () {
  17433. };
  17434. /**
  17435. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  17436. * @param func: callback function to add
  17437. *
  17438. * Returns the TransformNode.
  17439. */
  17440. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  17441. this.onAfterWorldMatrixUpdateObservable.add(func);
  17442. return this;
  17443. };
  17444. /**
  17445. * Removes a registered callback function.
  17446. * Returns the TransformNode.
  17447. */
  17448. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  17449. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  17450. return this;
  17451. };
  17452. /**
  17453. * Clone the current transform node
  17454. * Returns the new transform node
  17455. * @param name Name of the new clone
  17456. * @param newParent New parent for the clone
  17457. * @param doNotCloneChildren Do not clone children hierarchy
  17458. */
  17459. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  17460. var _this = this;
  17461. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  17462. result.name = name;
  17463. result.id = name;
  17464. if (newParent) {
  17465. result.parent = newParent;
  17466. }
  17467. if (!doNotCloneChildren) {
  17468. // Children
  17469. var directDescendants = this.getDescendants(true);
  17470. for (var index = 0; index < directDescendants.length; index++) {
  17471. var child = directDescendants[index];
  17472. if (child.clone) {
  17473. child.clone(name + "." + child.name, result);
  17474. }
  17475. }
  17476. }
  17477. return result;
  17478. };
  17479. TransformNode.prototype.serialize = function (currentSerializationObject) {
  17480. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  17481. serializationObject.type = this.getClassName();
  17482. // Parent
  17483. if (this.parent) {
  17484. serializationObject.parentId = this.parent.id;
  17485. }
  17486. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  17487. serializationObject.tags = BABYLON.Tags.GetTags(this);
  17488. }
  17489. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  17490. serializationObject.isEnabled = this.isEnabled();
  17491. // Parent
  17492. if (this.parent) {
  17493. serializationObject.parentId = this.parent.id;
  17494. }
  17495. return serializationObject;
  17496. };
  17497. // Statics
  17498. /**
  17499. * Returns a new TransformNode object parsed from the source provided.
  17500. * The parameter `parsedMesh` is the source.
  17501. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  17502. */
  17503. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  17504. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  17505. if (BABYLON.Tags) {
  17506. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  17507. }
  17508. if (parsedTransformNode.localMatrix) {
  17509. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  17510. }
  17511. else if (parsedTransformNode.pivotMatrix) {
  17512. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  17513. }
  17514. transformNode.setEnabled(parsedTransformNode.isEnabled);
  17515. // Parent
  17516. if (parsedTransformNode.parentId) {
  17517. transformNode._waitingParentId = parsedTransformNode.parentId;
  17518. }
  17519. return transformNode;
  17520. };
  17521. /**
  17522. * Releases resources associated with this transform node.
  17523. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  17524. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  17525. */
  17526. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17527. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17528. // Animations
  17529. this.getScene().stopAnimation(this);
  17530. // Remove from scene
  17531. this.getScene().removeTransformNode(this);
  17532. this.onAfterWorldMatrixUpdateObservable.clear();
  17533. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  17534. };
  17535. // Statics
  17536. TransformNode.BILLBOARDMODE_NONE = 0;
  17537. TransformNode.BILLBOARDMODE_X = 1;
  17538. TransformNode.BILLBOARDMODE_Y = 2;
  17539. TransformNode.BILLBOARDMODE_Z = 4;
  17540. TransformNode.BILLBOARDMODE_ALL = 7;
  17541. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  17542. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  17543. __decorate([
  17544. BABYLON.serializeAsVector3()
  17545. ], TransformNode.prototype, "_rotation", void 0);
  17546. __decorate([
  17547. BABYLON.serializeAsQuaternion()
  17548. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  17549. __decorate([
  17550. BABYLON.serializeAsVector3()
  17551. ], TransformNode.prototype, "_scaling", void 0);
  17552. __decorate([
  17553. BABYLON.serialize()
  17554. ], TransformNode.prototype, "billboardMode", void 0);
  17555. __decorate([
  17556. BABYLON.serialize()
  17557. ], TransformNode.prototype, "scalingDeterminant", void 0);
  17558. __decorate([
  17559. BABYLON.serialize()
  17560. ], TransformNode.prototype, "infiniteDistance", void 0);
  17561. __decorate([
  17562. BABYLON.serializeAsVector3()
  17563. ], TransformNode.prototype, "position", void 0);
  17564. return TransformNode;
  17565. }(BABYLON.Node));
  17566. BABYLON.TransformNode = TransformNode;
  17567. })(BABYLON || (BABYLON = {}));
  17568. //# sourceMappingURL=babylon.transformNode.js.map
  17569. "use strict";
  17570. var BABYLON;
  17571. (function (BABYLON) {
  17572. var AbstractMesh = /** @class */ (function (_super) {
  17573. __extends(AbstractMesh, _super);
  17574. // Constructor
  17575. function AbstractMesh(name, scene) {
  17576. if (scene === void 0) { scene = null; }
  17577. var _this = _super.call(this, name, scene, false) || this;
  17578. _this._facetNb = 0; // facet number
  17579. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  17580. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  17581. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  17582. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  17583. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  17584. _this._subDiv = {
  17585. max: 1,
  17586. X: 1,
  17587. Y: 1,
  17588. Z: 1
  17589. };
  17590. _this._facetDepthSort = false; // is the facet depth sort to be computed
  17591. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  17592. // Events
  17593. /**
  17594. * An event triggered when this mesh collides with another one
  17595. * @type {BABYLON.Observable}
  17596. */
  17597. _this.onCollideObservable = new BABYLON.Observable();
  17598. /**
  17599. * An event triggered when the collision's position changes
  17600. * @type {BABYLON.Observable}
  17601. */
  17602. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  17603. /**
  17604. * An event triggered when material is changed
  17605. * @type {BABYLON.Observable}
  17606. */
  17607. _this.onMaterialChangedObservable = new BABYLON.Observable();
  17608. // Properties
  17609. _this.definedFacingForward = true; // orientation for POV movement & rotation
  17610. /**
  17611. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  17612. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  17613. * or
  17614. * 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.
  17615. * for more info check WebGl documentations
  17616. */
  17617. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  17618. /**
  17619. * 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:
  17620. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  17621. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  17622. * 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.
  17623. */
  17624. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  17625. /**
  17626. * 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.
  17627. * The default value is -1 which means don't break the query and wait till the result.
  17628. */
  17629. _this.occlusionRetryCount = -1;
  17630. _this._occlusionInternalRetryCounter = 0;
  17631. _this._isOccluded = false;
  17632. _this._isOcclusionQueryInProgress = false;
  17633. _this._visibility = 1.0;
  17634. _this.alphaIndex = Number.MAX_VALUE;
  17635. _this.isVisible = true;
  17636. _this.isPickable = true;
  17637. _this.showBoundingBox = false;
  17638. _this.showSubMeshesBoundingBox = false;
  17639. _this.isBlocker = false;
  17640. _this.enablePointerMoveEvents = false;
  17641. _this.renderingGroupId = 0;
  17642. _this._receiveShadows = false;
  17643. _this.renderOutline = false;
  17644. _this.outlineColor = BABYLON.Color3.Red();
  17645. _this.outlineWidth = 0.02;
  17646. _this.renderOverlay = false;
  17647. _this.overlayColor = BABYLON.Color3.Red();
  17648. _this.overlayAlpha = 0.5;
  17649. _this._hasVertexAlpha = false;
  17650. _this._useVertexColors = true;
  17651. _this._computeBonesUsingShaders = true;
  17652. _this._numBoneInfluencers = 4;
  17653. _this._applyFog = true;
  17654. _this.useOctreeForRenderingSelection = true;
  17655. _this.useOctreeForPicking = true;
  17656. _this.useOctreeForCollisions = true;
  17657. _this._layerMask = 0x0FFFFFFF;
  17658. /**
  17659. * True if the mesh must be rendered in any case.
  17660. */
  17661. _this.alwaysSelectAsActiveMesh = false;
  17662. /**
  17663. * This scene's action manager
  17664. * @type {BABYLON.ActionManager}
  17665. */
  17666. _this.actionManager = null;
  17667. // Physics
  17668. _this.physicsImpostor = null;
  17669. // Collisions
  17670. _this._checkCollisions = false;
  17671. _this._collisionMask = -1;
  17672. _this._collisionGroup = -1;
  17673. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  17674. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  17675. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  17676. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  17677. // Edges
  17678. _this.edgesWidth = 1;
  17679. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  17680. // Cache
  17681. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  17682. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  17683. _this._renderId = 0;
  17684. _this._intersectionsInProgress = new Array();
  17685. _this._unIndexed = false;
  17686. _this._lightSources = new Array();
  17687. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  17688. if (collidedMesh === void 0) { collidedMesh = null; }
  17689. //TODO move this to the collision coordinator!
  17690. if (_this.getScene().workerCollisions)
  17691. newPosition.multiplyInPlace(_this._collider._radius);
  17692. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  17693. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  17694. _this.position.addInPlace(_this._diffPositionForCollisions);
  17695. }
  17696. if (collidedMesh) {
  17697. _this.onCollideObservable.notifyObservers(collidedMesh);
  17698. }
  17699. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  17700. };
  17701. _this.getScene().addMesh(_this);
  17702. _this._resyncLightSources();
  17703. return _this;
  17704. }
  17705. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  17706. get: function () {
  17707. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  17708. },
  17709. enumerable: true,
  17710. configurable: true
  17711. });
  17712. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  17713. get: function () {
  17714. return BABYLON.TransformNode.BILLBOARDMODE_X;
  17715. },
  17716. enumerable: true,
  17717. configurable: true
  17718. });
  17719. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  17720. get: function () {
  17721. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  17722. },
  17723. enumerable: true,
  17724. configurable: true
  17725. });
  17726. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  17727. get: function () {
  17728. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  17729. },
  17730. enumerable: true,
  17731. configurable: true
  17732. });
  17733. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  17734. get: function () {
  17735. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  17736. },
  17737. enumerable: true,
  17738. configurable: true
  17739. });
  17740. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  17741. /**
  17742. * Read-only : the number of facets in the mesh
  17743. */
  17744. get: function () {
  17745. return this._facetNb;
  17746. },
  17747. enumerable: true,
  17748. configurable: true
  17749. });
  17750. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  17751. /**
  17752. * The number (integer) of subdivisions per axis in the partioning space
  17753. */
  17754. get: function () {
  17755. return this._partitioningSubdivisions;
  17756. },
  17757. set: function (nb) {
  17758. this._partitioningSubdivisions = nb;
  17759. },
  17760. enumerable: true,
  17761. configurable: true
  17762. });
  17763. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  17764. /**
  17765. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  17766. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  17767. */
  17768. get: function () {
  17769. return this._partitioningBBoxRatio;
  17770. },
  17771. set: function (ratio) {
  17772. this._partitioningBBoxRatio = ratio;
  17773. },
  17774. enumerable: true,
  17775. configurable: true
  17776. });
  17777. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  17778. /**
  17779. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  17780. * Works only for updatable meshes.
  17781. * Doesn't work with multi-materials.
  17782. */
  17783. get: function () {
  17784. return this._facetDepthSort;
  17785. },
  17786. set: function (sort) {
  17787. this._facetDepthSort = sort;
  17788. },
  17789. enumerable: true,
  17790. configurable: true
  17791. });
  17792. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  17793. /**
  17794. * The location (Vector3) where the facet depth sort must be computed from.
  17795. * By default, the active camera position.
  17796. * Used only when facet depth sort is enabled.
  17797. */
  17798. get: function () {
  17799. return this._facetDepthSortFrom;
  17800. },
  17801. set: function (location) {
  17802. this._facetDepthSortFrom = location;
  17803. },
  17804. enumerable: true,
  17805. configurable: true
  17806. });
  17807. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  17808. /**
  17809. * Read-only boolean : is the feature facetData enabled ?
  17810. */
  17811. get: function () {
  17812. return this._facetDataEnabled;
  17813. },
  17814. enumerable: true,
  17815. configurable: true
  17816. });
  17817. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  17818. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  17819. return false;
  17820. }
  17821. this._markSubMeshesAsMiscDirty();
  17822. return true;
  17823. };
  17824. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  17825. set: function (callback) {
  17826. if (this._onCollideObserver) {
  17827. this.onCollideObservable.remove(this._onCollideObserver);
  17828. }
  17829. this._onCollideObserver = this.onCollideObservable.add(callback);
  17830. },
  17831. enumerable: true,
  17832. configurable: true
  17833. });
  17834. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  17835. set: function (callback) {
  17836. if (this._onCollisionPositionChangeObserver) {
  17837. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  17838. }
  17839. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  17840. },
  17841. enumerable: true,
  17842. configurable: true
  17843. });
  17844. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  17845. /**
  17846. * 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.
  17847. */
  17848. get: function () {
  17849. return this._isOccluded;
  17850. },
  17851. set: function (value) {
  17852. this._isOccluded = value;
  17853. },
  17854. enumerable: true,
  17855. configurable: true
  17856. });
  17857. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  17858. /**
  17859. * Flag to check the progress status of the query
  17860. */
  17861. get: function () {
  17862. return this._isOcclusionQueryInProgress;
  17863. },
  17864. enumerable: true,
  17865. configurable: true
  17866. });
  17867. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  17868. /**
  17869. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17870. */
  17871. get: function () {
  17872. return this._visibility;
  17873. },
  17874. /**
  17875. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17876. */
  17877. set: function (value) {
  17878. if (this._visibility === value) {
  17879. return;
  17880. }
  17881. this._visibility = value;
  17882. this._markSubMeshesAsMiscDirty();
  17883. },
  17884. enumerable: true,
  17885. configurable: true
  17886. });
  17887. Object.defineProperty(AbstractMesh.prototype, "material", {
  17888. get: function () {
  17889. return this._material;
  17890. },
  17891. set: function (value) {
  17892. if (this._material === value) {
  17893. return;
  17894. }
  17895. this._material = value;
  17896. if (this.onMaterialChangedObservable.hasObservers) {
  17897. this.onMaterialChangedObservable.notifyObservers(this);
  17898. }
  17899. if (!this.subMeshes) {
  17900. return;
  17901. }
  17902. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17903. var subMesh = _a[_i];
  17904. subMesh.setEffect(null);
  17905. }
  17906. },
  17907. enumerable: true,
  17908. configurable: true
  17909. });
  17910. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  17911. get: function () {
  17912. return this._receiveShadows;
  17913. },
  17914. set: function (value) {
  17915. if (this._receiveShadows === value) {
  17916. return;
  17917. }
  17918. this._receiveShadows = value;
  17919. this._markSubMeshesAsLightDirty();
  17920. },
  17921. enumerable: true,
  17922. configurable: true
  17923. });
  17924. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  17925. get: function () {
  17926. return this._hasVertexAlpha;
  17927. },
  17928. set: function (value) {
  17929. if (this._hasVertexAlpha === value) {
  17930. return;
  17931. }
  17932. this._hasVertexAlpha = value;
  17933. this._markSubMeshesAsAttributesDirty();
  17934. this._markSubMeshesAsMiscDirty();
  17935. },
  17936. enumerable: true,
  17937. configurable: true
  17938. });
  17939. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  17940. get: function () {
  17941. return this._useVertexColors;
  17942. },
  17943. set: function (value) {
  17944. if (this._useVertexColors === value) {
  17945. return;
  17946. }
  17947. this._useVertexColors = value;
  17948. this._markSubMeshesAsAttributesDirty();
  17949. },
  17950. enumerable: true,
  17951. configurable: true
  17952. });
  17953. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  17954. get: function () {
  17955. return this._computeBonesUsingShaders;
  17956. },
  17957. set: function (value) {
  17958. if (this._computeBonesUsingShaders === value) {
  17959. return;
  17960. }
  17961. this._computeBonesUsingShaders = value;
  17962. this._markSubMeshesAsAttributesDirty();
  17963. },
  17964. enumerable: true,
  17965. configurable: true
  17966. });
  17967. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  17968. get: function () {
  17969. return this._numBoneInfluencers;
  17970. },
  17971. set: function (value) {
  17972. if (this._numBoneInfluencers === value) {
  17973. return;
  17974. }
  17975. this._numBoneInfluencers = value;
  17976. this._markSubMeshesAsAttributesDirty();
  17977. },
  17978. enumerable: true,
  17979. configurable: true
  17980. });
  17981. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  17982. get: function () {
  17983. return this._applyFog;
  17984. },
  17985. set: function (value) {
  17986. if (this._applyFog === value) {
  17987. return;
  17988. }
  17989. this._applyFog = value;
  17990. this._markSubMeshesAsMiscDirty();
  17991. },
  17992. enumerable: true,
  17993. configurable: true
  17994. });
  17995. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  17996. get: function () {
  17997. return this._layerMask;
  17998. },
  17999. set: function (value) {
  18000. if (value === this._layerMask) {
  18001. return;
  18002. }
  18003. this._layerMask = value;
  18004. this._resyncLightSources();
  18005. },
  18006. enumerable: true,
  18007. configurable: true
  18008. });
  18009. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  18010. get: function () {
  18011. return this._collisionMask;
  18012. },
  18013. set: function (mask) {
  18014. this._collisionMask = !isNaN(mask) ? mask : -1;
  18015. },
  18016. enumerable: true,
  18017. configurable: true
  18018. });
  18019. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  18020. get: function () {
  18021. return this._collisionGroup;
  18022. },
  18023. set: function (mask) {
  18024. this._collisionGroup = !isNaN(mask) ? mask : -1;
  18025. },
  18026. enumerable: true,
  18027. configurable: true
  18028. });
  18029. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  18030. get: function () {
  18031. return null;
  18032. },
  18033. enumerable: true,
  18034. configurable: true
  18035. });
  18036. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  18037. get: function () {
  18038. return this._skeleton;
  18039. },
  18040. set: function (value) {
  18041. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  18042. this._skeleton._unregisterMeshWithPoseMatrix(this);
  18043. }
  18044. if (value && value.needInitialSkinMatrix) {
  18045. value._registerMeshWithPoseMatrix(this);
  18046. }
  18047. this._skeleton = value;
  18048. if (!this._skeleton) {
  18049. this._bonesTransformMatrices = null;
  18050. }
  18051. this._markSubMeshesAsAttributesDirty();
  18052. },
  18053. enumerable: true,
  18054. configurable: true
  18055. });
  18056. /**
  18057. * Returns the string "AbstractMesh"
  18058. */
  18059. AbstractMesh.prototype.getClassName = function () {
  18060. return "AbstractMesh";
  18061. };
  18062. /**
  18063. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  18064. */
  18065. AbstractMesh.prototype.toString = function (fullDetails) {
  18066. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  18067. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  18068. if (this._skeleton) {
  18069. ret += ", skeleton: " + this._skeleton.name;
  18070. }
  18071. if (fullDetails) {
  18072. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  18073. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  18074. }
  18075. return ret;
  18076. };
  18077. AbstractMesh.prototype._rebuild = function () {
  18078. if (this._occlusionQuery) {
  18079. this._occlusionQuery = null;
  18080. }
  18081. if (this._edgesRenderer) {
  18082. this._edgesRenderer._rebuild();
  18083. }
  18084. if (!this.subMeshes) {
  18085. return;
  18086. }
  18087. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  18088. var subMesh = _a[_i];
  18089. subMesh._rebuild();
  18090. }
  18091. };
  18092. AbstractMesh.prototype._resyncLightSources = function () {
  18093. this._lightSources.length = 0;
  18094. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  18095. var light = _a[_i];
  18096. if (!light.isEnabled()) {
  18097. continue;
  18098. }
  18099. if (light.canAffectMesh(this)) {
  18100. this._lightSources.push(light);
  18101. }
  18102. }
  18103. this._markSubMeshesAsLightDirty();
  18104. };
  18105. AbstractMesh.prototype._resyncLighSource = function (light) {
  18106. var isIn = light.isEnabled() && light.canAffectMesh(this);
  18107. var index = this._lightSources.indexOf(light);
  18108. if (index === -1) {
  18109. if (!isIn) {
  18110. return;
  18111. }
  18112. this._lightSources.push(light);
  18113. }
  18114. else {
  18115. if (isIn) {
  18116. return;
  18117. }
  18118. this._lightSources.splice(index, 1);
  18119. }
  18120. this._markSubMeshesAsLightDirty();
  18121. };
  18122. AbstractMesh.prototype._removeLightSource = function (light) {
  18123. var index = this._lightSources.indexOf(light);
  18124. if (index === -1) {
  18125. return;
  18126. }
  18127. this._lightSources.splice(index, 1);
  18128. this._markSubMeshesAsLightDirty();
  18129. };
  18130. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  18131. if (!this.subMeshes) {
  18132. return;
  18133. }
  18134. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  18135. var subMesh = _a[_i];
  18136. if (subMesh._materialDefines) {
  18137. func(subMesh._materialDefines);
  18138. }
  18139. }
  18140. };
  18141. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  18142. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  18143. };
  18144. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  18145. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  18146. };
  18147. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  18148. if (!this.subMeshes) {
  18149. return;
  18150. }
  18151. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  18152. var subMesh = _a[_i];
  18153. var material = subMesh.getMaterial();
  18154. if (material) {
  18155. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  18156. }
  18157. }
  18158. };
  18159. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  18160. /**
  18161. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18162. * Default : (1.0, 1.0, 1.0)
  18163. */
  18164. get: function () {
  18165. return this._scaling;
  18166. },
  18167. /**
  18168. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18169. * Default : (1.0, 1.0, 1.0)
  18170. */
  18171. set: function (newScaling) {
  18172. this._scaling = newScaling;
  18173. if (this.physicsImpostor) {
  18174. this.physicsImpostor.forceUpdate();
  18175. }
  18176. },
  18177. enumerable: true,
  18178. configurable: true
  18179. });
  18180. // Methods
  18181. /**
  18182. * Disables the mesh edger rendering mode.
  18183. * Returns the AbstractMesh.
  18184. */
  18185. AbstractMesh.prototype.disableEdgesRendering = function () {
  18186. if (this._edgesRenderer) {
  18187. this._edgesRenderer.dispose();
  18188. this._edgesRenderer = null;
  18189. }
  18190. return this;
  18191. };
  18192. /**
  18193. * Enables the edge rendering mode on the mesh.
  18194. * This mode makes the mesh edges visible.
  18195. * Returns the AbstractMesh.
  18196. */
  18197. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  18198. if (epsilon === void 0) { epsilon = 0.95; }
  18199. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  18200. this.disableEdgesRendering();
  18201. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  18202. return this;
  18203. };
  18204. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  18205. /**
  18206. * Returns true if the mesh is blocked. Used by the class Mesh.
  18207. * Returns the boolean `false` by default.
  18208. */
  18209. get: function () {
  18210. return false;
  18211. },
  18212. enumerable: true,
  18213. configurable: true
  18214. });
  18215. /**
  18216. * Returns the mesh itself by default, used by the class Mesh.
  18217. * Returned type : AbstractMesh
  18218. */
  18219. AbstractMesh.prototype.getLOD = function (camera) {
  18220. return this;
  18221. };
  18222. /**
  18223. * Returns 0 by default, used by the class Mesh.
  18224. * Returns an integer.
  18225. */
  18226. AbstractMesh.prototype.getTotalVertices = function () {
  18227. return 0;
  18228. };
  18229. /**
  18230. * Returns null by default, used by the class Mesh.
  18231. * Returned type : integer array
  18232. */
  18233. AbstractMesh.prototype.getIndices = function () {
  18234. return null;
  18235. };
  18236. /**
  18237. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  18238. * Returned type : float array or Float32Array
  18239. */
  18240. AbstractMesh.prototype.getVerticesData = function (kind) {
  18241. return null;
  18242. };
  18243. /**
  18244. * Sets the vertex data of the mesh geometry for the requested `kind`.
  18245. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  18246. * The `data` are either a numeric array either a Float32Array.
  18247. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  18248. * 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).
  18249. * Note that a new underlying VertexBuffer object is created each call.
  18250. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  18251. *
  18252. * Possible `kind` values :
  18253. * - BABYLON.VertexBuffer.PositionKind
  18254. * - BABYLON.VertexBuffer.UVKind
  18255. * - BABYLON.VertexBuffer.UV2Kind
  18256. * - BABYLON.VertexBuffer.UV3Kind
  18257. * - BABYLON.VertexBuffer.UV4Kind
  18258. * - BABYLON.VertexBuffer.UV5Kind
  18259. * - BABYLON.VertexBuffer.UV6Kind
  18260. * - BABYLON.VertexBuffer.ColorKind
  18261. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18262. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18263. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18264. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18265. *
  18266. * Returns the Mesh.
  18267. */
  18268. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  18269. return this;
  18270. };
  18271. /**
  18272. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  18273. * If the mesh has no geometry, it is simply returned as it is.
  18274. * The `data` are either a numeric array either a Float32Array.
  18275. * No new underlying VertexBuffer object is created.
  18276. * 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.
  18277. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  18278. *
  18279. * Possible `kind` values :
  18280. * - BABYLON.VertexBuffer.PositionKind
  18281. * - BABYLON.VertexBuffer.UVKind
  18282. * - BABYLON.VertexBuffer.UV2Kind
  18283. * - BABYLON.VertexBuffer.UV3Kind
  18284. * - BABYLON.VertexBuffer.UV4Kind
  18285. * - BABYLON.VertexBuffer.UV5Kind
  18286. * - BABYLON.VertexBuffer.UV6Kind
  18287. * - BABYLON.VertexBuffer.ColorKind
  18288. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18289. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18290. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18291. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18292. *
  18293. * Returns the Mesh.
  18294. */
  18295. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  18296. return this;
  18297. };
  18298. /**
  18299. * Sets the mesh indices.
  18300. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  18301. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  18302. * This method creates a new index buffer each call.
  18303. * Returns the Mesh.
  18304. */
  18305. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  18306. return this;
  18307. };
  18308. /** Returns false by default, used by the class Mesh.
  18309. * Returns a boolean
  18310. */
  18311. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  18312. return false;
  18313. };
  18314. /**
  18315. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  18316. * Returns a BoundingInfo
  18317. */
  18318. AbstractMesh.prototype.getBoundingInfo = function () {
  18319. if (this._masterMesh) {
  18320. return this._masterMesh.getBoundingInfo();
  18321. }
  18322. if (!this._boundingInfo) {
  18323. // this._boundingInfo is being created here
  18324. this._updateBoundingInfo();
  18325. }
  18326. // cannot be null.
  18327. return this._boundingInfo;
  18328. };
  18329. /**
  18330. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  18331. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  18332. */
  18333. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  18334. if (includeDescendants === void 0) { includeDescendants = true; }
  18335. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  18336. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  18337. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  18338. if (maxDimension === 0) {
  18339. return this;
  18340. }
  18341. var scale = 1 / maxDimension;
  18342. this.scaling.scaleInPlace(scale);
  18343. return this;
  18344. };
  18345. /**
  18346. * Sets a mesh new object BoundingInfo.
  18347. * Returns the AbstractMesh.
  18348. */
  18349. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  18350. this._boundingInfo = boundingInfo;
  18351. return this;
  18352. };
  18353. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  18354. get: function () {
  18355. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  18356. },
  18357. enumerable: true,
  18358. configurable: true
  18359. });
  18360. AbstractMesh.prototype._preActivate = function () {
  18361. };
  18362. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  18363. };
  18364. AbstractMesh.prototype._activate = function (renderId) {
  18365. this._renderId = renderId;
  18366. };
  18367. /**
  18368. * Returns the latest update of the World matrix
  18369. * Returns a Matrix.
  18370. */
  18371. AbstractMesh.prototype.getWorldMatrix = function () {
  18372. if (this._masterMesh) {
  18373. return this._masterMesh.getWorldMatrix();
  18374. }
  18375. return _super.prototype.getWorldMatrix.call(this);
  18376. };
  18377. /**
  18378. * Returns the latest update of the World matrix determinant.
  18379. */
  18380. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  18381. if (this._masterMesh) {
  18382. return this._masterMesh._getWorldMatrixDeterminant();
  18383. }
  18384. return _super.prototype._getWorldMatrixDeterminant.call(this);
  18385. };
  18386. // ================================== Point of View Movement =================================
  18387. /**
  18388. * Perform relative position change from the point of view of behind the front of the mesh.
  18389. * This is performed taking into account the meshes current rotation, so you do not have to care.
  18390. * Supports definition of mesh facing forward or backward.
  18391. * @param {number} amountRight
  18392. * @param {number} amountUp
  18393. * @param {number} amountForward
  18394. *
  18395. * Returns the AbstractMesh.
  18396. */
  18397. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  18398. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  18399. return this;
  18400. };
  18401. /**
  18402. * Calculate relative position change from the point of view of behind the front of the mesh.
  18403. * This is performed taking into account the meshes current rotation, so you do not have to care.
  18404. * Supports definition of mesh facing forward or backward.
  18405. * @param {number} amountRight
  18406. * @param {number} amountUp
  18407. * @param {number} amountForward
  18408. *
  18409. * Returns a new Vector3.
  18410. */
  18411. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  18412. var rotMatrix = new BABYLON.Matrix();
  18413. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18414. rotQuaternion.toRotationMatrix(rotMatrix);
  18415. var translationDelta = BABYLON.Vector3.Zero();
  18416. var defForwardMult = this.definedFacingForward ? -1 : 1;
  18417. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  18418. return translationDelta;
  18419. };
  18420. // ================================== Point of View Rotation =================================
  18421. /**
  18422. * Perform relative rotation change from the point of view of behind the front of the mesh.
  18423. * Supports definition of mesh facing forward or backward.
  18424. * @param {number} flipBack
  18425. * @param {number} twirlClockwise
  18426. * @param {number} tiltRight
  18427. *
  18428. * Returns the AbstractMesh.
  18429. */
  18430. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  18431. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  18432. return this;
  18433. };
  18434. /**
  18435. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  18436. * Supports definition of mesh facing forward or backward.
  18437. * @param {number} flipBack
  18438. * @param {number} twirlClockwise
  18439. * @param {number} tiltRight
  18440. *
  18441. * Returns a new Vector3.
  18442. */
  18443. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  18444. var defForwardMult = this.definedFacingForward ? 1 : -1;
  18445. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  18446. };
  18447. /**
  18448. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  18449. * @param includeDescendants Include bounding info from descendants as well (true by default).
  18450. */
  18451. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  18452. if (includeDescendants === void 0) { includeDescendants = true; }
  18453. this.computeWorldMatrix(true);
  18454. var min;
  18455. var max;
  18456. var boundingInfo = this.getBoundingInfo();
  18457. if (!this.subMeshes) {
  18458. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18459. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  18460. }
  18461. else {
  18462. min = boundingInfo.boundingBox.minimumWorld;
  18463. max = boundingInfo.boundingBox.maximumWorld;
  18464. }
  18465. if (includeDescendants) {
  18466. var descendants = this.getDescendants(false);
  18467. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  18468. var descendant = descendants_1[_i];
  18469. var childMesh = descendant;
  18470. childMesh.computeWorldMatrix(true);
  18471. //make sure we have the needed params to get mix and max
  18472. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  18473. continue;
  18474. }
  18475. var childBoundingInfo = childMesh.getBoundingInfo();
  18476. var boundingBox = childBoundingInfo.boundingBox;
  18477. var minBox = boundingBox.minimumWorld;
  18478. var maxBox = boundingBox.maximumWorld;
  18479. BABYLON.Tools.CheckExtends(minBox, min, max);
  18480. BABYLON.Tools.CheckExtends(maxBox, min, max);
  18481. }
  18482. }
  18483. return {
  18484. min: min,
  18485. max: max
  18486. };
  18487. };
  18488. /**
  18489. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  18490. * Returns the AbstractMesh.
  18491. */
  18492. AbstractMesh.prototype._updateBoundingInfo = function () {
  18493. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  18494. this._boundingInfo.update(this.worldMatrixFromCache);
  18495. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  18496. return this;
  18497. };
  18498. /**
  18499. * Update a mesh's children BoundingInfo objects only.
  18500. * Returns the AbstractMesh.
  18501. */
  18502. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  18503. if (!this.subMeshes) {
  18504. return this;
  18505. }
  18506. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  18507. var subMesh = this.subMeshes[subIndex];
  18508. if (!subMesh.IsGlobal) {
  18509. subMesh.updateBoundingInfo(matrix);
  18510. }
  18511. }
  18512. return this;
  18513. };
  18514. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  18515. // Bounding info
  18516. this._updateBoundingInfo();
  18517. };
  18518. /**
  18519. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  18520. * A mesh is in the frustum if its bounding box intersects the frustum.
  18521. * Boolean returned.
  18522. */
  18523. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  18524. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  18525. };
  18526. /**
  18527. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  18528. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  18529. * Boolean returned.
  18530. */
  18531. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18532. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  18533. ;
  18534. };
  18535. /**
  18536. * True if the mesh intersects another mesh or a SolidParticle object.
  18537. * 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)
  18538. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  18539. * Returns a boolean.
  18540. */
  18541. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  18542. if (precise === void 0) { precise = false; }
  18543. if (!this._boundingInfo || !mesh._boundingInfo) {
  18544. return false;
  18545. }
  18546. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  18547. return true;
  18548. }
  18549. if (includeDescendants) {
  18550. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  18551. var child = _a[_i];
  18552. if (child.intersectsMesh(mesh, precise, true)) {
  18553. return true;
  18554. }
  18555. }
  18556. }
  18557. return false;
  18558. };
  18559. /**
  18560. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  18561. * Returns a boolean.
  18562. */
  18563. AbstractMesh.prototype.intersectsPoint = function (point) {
  18564. if (!this._boundingInfo) {
  18565. return false;
  18566. }
  18567. return this._boundingInfo.intersectsPoint(point);
  18568. };
  18569. AbstractMesh.prototype.getPhysicsImpostor = function () {
  18570. return this.physicsImpostor;
  18571. };
  18572. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  18573. if (camera === void 0) { camera = null; }
  18574. if (!camera) {
  18575. camera = this.getScene().activeCamera;
  18576. }
  18577. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  18578. };
  18579. /**
  18580. * Returns the distance from the mesh to the active camera.
  18581. * Returns a float.
  18582. */
  18583. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  18584. if (camera === void 0) { camera = null; }
  18585. if (!camera) {
  18586. camera = this.getScene().activeCamera;
  18587. }
  18588. return this.absolutePosition.subtract(camera.position).length();
  18589. };
  18590. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  18591. if (!this.physicsImpostor) {
  18592. return this;
  18593. }
  18594. this.physicsImpostor.applyImpulse(force, contactPoint);
  18595. return this;
  18596. };
  18597. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  18598. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  18599. return this;
  18600. }
  18601. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  18602. mainPivot: pivot1,
  18603. connectedPivot: pivot2,
  18604. nativeParams: options
  18605. });
  18606. return this;
  18607. };
  18608. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  18609. // Collisions
  18610. /**
  18611. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  18612. * Default `false`.
  18613. */
  18614. get: function () {
  18615. return this._checkCollisions;
  18616. },
  18617. set: function (collisionEnabled) {
  18618. this._checkCollisions = collisionEnabled;
  18619. if (this.getScene().workerCollisions) {
  18620. this.getScene().collisionCoordinator.onMeshUpdated(this);
  18621. }
  18622. },
  18623. enumerable: true,
  18624. configurable: true
  18625. });
  18626. Object.defineProperty(AbstractMesh.prototype, "collider", {
  18627. /**
  18628. * Gets Collider object used to compute collisions (not physics)
  18629. */
  18630. get: function () {
  18631. return this._collider;
  18632. },
  18633. enumerable: true,
  18634. configurable: true
  18635. });
  18636. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  18637. var globalPosition = this.getAbsolutePosition();
  18638. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  18639. if (!this._collider) {
  18640. this._collider = new BABYLON.Collider();
  18641. }
  18642. this._collider._radius = this.ellipsoid;
  18643. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  18644. return this;
  18645. };
  18646. // Submeshes octree
  18647. /**
  18648. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  18649. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  18650. * Returns an Octree of submeshes.
  18651. */
  18652. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  18653. if (maxCapacity === void 0) { maxCapacity = 64; }
  18654. if (maxDepth === void 0) { maxDepth = 2; }
  18655. if (!this._submeshesOctree) {
  18656. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  18657. }
  18658. this.computeWorldMatrix(true);
  18659. var boundingInfo = this.getBoundingInfo();
  18660. // Update octree
  18661. var bbox = boundingInfo.boundingBox;
  18662. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  18663. return this._submeshesOctree;
  18664. };
  18665. // Collisions
  18666. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  18667. this._generatePointsArray();
  18668. if (!this._positions) {
  18669. return this;
  18670. }
  18671. // Transformation
  18672. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  18673. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  18674. subMesh._lastColliderWorldVertices = [];
  18675. subMesh._trianglePlanes = [];
  18676. var start = subMesh.verticesStart;
  18677. var end = (subMesh.verticesStart + subMesh.verticesCount);
  18678. for (var i = start; i < end; i++) {
  18679. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  18680. }
  18681. }
  18682. // Collide
  18683. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  18684. if (collider.collisionFound) {
  18685. collider.collidedMesh = this;
  18686. }
  18687. return this;
  18688. };
  18689. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  18690. var subMeshes;
  18691. var len;
  18692. // Octrees
  18693. if (this._submeshesOctree && this.useOctreeForCollisions) {
  18694. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  18695. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  18696. len = intersections.length;
  18697. subMeshes = intersections.data;
  18698. }
  18699. else {
  18700. subMeshes = this.subMeshes;
  18701. len = subMeshes.length;
  18702. }
  18703. for (var index = 0; index < len; index++) {
  18704. var subMesh = subMeshes[index];
  18705. // Bounding test
  18706. if (len > 1 && !subMesh._checkCollision(collider))
  18707. continue;
  18708. this._collideForSubMesh(subMesh, transformMatrix, collider);
  18709. }
  18710. return this;
  18711. };
  18712. AbstractMesh.prototype._checkCollision = function (collider) {
  18713. // Bounding box test
  18714. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  18715. return this;
  18716. // Transformation matrix
  18717. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  18718. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  18719. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  18720. return this;
  18721. };
  18722. // Picking
  18723. AbstractMesh.prototype._generatePointsArray = function () {
  18724. return false;
  18725. };
  18726. /**
  18727. * Checks if the passed Ray intersects with the mesh.
  18728. * Returns an object PickingInfo.
  18729. */
  18730. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  18731. var pickingInfo = new BABYLON.PickingInfo();
  18732. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  18733. return pickingInfo;
  18734. }
  18735. if (!this._generatePointsArray()) {
  18736. return pickingInfo;
  18737. }
  18738. var intersectInfo = null;
  18739. // Octrees
  18740. var subMeshes;
  18741. var len;
  18742. if (this._submeshesOctree && this.useOctreeForPicking) {
  18743. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  18744. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  18745. len = intersections.length;
  18746. subMeshes = intersections.data;
  18747. }
  18748. else {
  18749. subMeshes = this.subMeshes;
  18750. len = subMeshes.length;
  18751. }
  18752. for (var index = 0; index < len; index++) {
  18753. var subMesh = subMeshes[index];
  18754. // Bounding test
  18755. if (len > 1 && !subMesh.canIntersects(ray))
  18756. continue;
  18757. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  18758. if (currentIntersectInfo) {
  18759. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  18760. intersectInfo = currentIntersectInfo;
  18761. intersectInfo.subMeshId = index;
  18762. if (fastCheck) {
  18763. break;
  18764. }
  18765. }
  18766. }
  18767. }
  18768. if (intersectInfo) {
  18769. // Get picked point
  18770. var world = this.getWorldMatrix();
  18771. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  18772. var direction = ray.direction.clone();
  18773. direction = direction.scale(intersectInfo.distance);
  18774. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  18775. var pickedPoint = worldOrigin.add(worldDirection);
  18776. // Return result
  18777. pickingInfo.hit = true;
  18778. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  18779. pickingInfo.pickedPoint = pickedPoint;
  18780. pickingInfo.pickedMesh = this;
  18781. pickingInfo.bu = intersectInfo.bu || 0;
  18782. pickingInfo.bv = intersectInfo.bv || 0;
  18783. pickingInfo.faceId = intersectInfo.faceId;
  18784. pickingInfo.subMeshId = intersectInfo.subMeshId;
  18785. return pickingInfo;
  18786. }
  18787. return pickingInfo;
  18788. };
  18789. /**
  18790. * Clones the mesh, used by the class Mesh.
  18791. * Just returns `null` for an AbstractMesh.
  18792. */
  18793. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  18794. return null;
  18795. };
  18796. /**
  18797. * Disposes all the mesh submeshes.
  18798. * Returns the AbstractMesh.
  18799. */
  18800. AbstractMesh.prototype.releaseSubMeshes = function () {
  18801. if (this.subMeshes) {
  18802. while (this.subMeshes.length) {
  18803. this.subMeshes[0].dispose();
  18804. }
  18805. }
  18806. else {
  18807. this.subMeshes = new Array();
  18808. }
  18809. return this;
  18810. };
  18811. /**
  18812. * Releases resources associated with this abstract mesh.
  18813. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18814. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18815. */
  18816. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18817. var _this = this;
  18818. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18819. var index;
  18820. // Smart Array Retainers.
  18821. this.getScene().freeActiveMeshes();
  18822. this.getScene().freeRenderingGroups();
  18823. // Action manager
  18824. if (this.actionManager !== undefined && this.actionManager !== null) {
  18825. this.actionManager.dispose();
  18826. this.actionManager = null;
  18827. }
  18828. // Skeleton
  18829. this._skeleton = null;
  18830. // Physics
  18831. if (this.physicsImpostor) {
  18832. this.physicsImpostor.dispose();
  18833. }
  18834. // Intersections in progress
  18835. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  18836. var other = this._intersectionsInProgress[index];
  18837. var pos = other._intersectionsInProgress.indexOf(this);
  18838. other._intersectionsInProgress.splice(pos, 1);
  18839. }
  18840. this._intersectionsInProgress = [];
  18841. // Lights
  18842. var lights = this.getScene().lights;
  18843. lights.forEach(function (light) {
  18844. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  18845. if (meshIndex !== -1) {
  18846. light.includedOnlyMeshes.splice(meshIndex, 1);
  18847. }
  18848. meshIndex = light.excludedMeshes.indexOf(_this);
  18849. if (meshIndex !== -1) {
  18850. light.excludedMeshes.splice(meshIndex, 1);
  18851. }
  18852. // Shadow generators
  18853. var generator = light.getShadowGenerator();
  18854. if (generator) {
  18855. var shadowMap = generator.getShadowMap();
  18856. if (shadowMap && shadowMap.renderList) {
  18857. meshIndex = shadowMap.renderList.indexOf(_this);
  18858. if (meshIndex !== -1) {
  18859. shadowMap.renderList.splice(meshIndex, 1);
  18860. }
  18861. }
  18862. }
  18863. });
  18864. // Edges
  18865. if (this._edgesRenderer) {
  18866. this._edgesRenderer.dispose();
  18867. this._edgesRenderer = null;
  18868. }
  18869. // SubMeshes
  18870. if (this.getClassName() !== "InstancedMesh") {
  18871. this.releaseSubMeshes();
  18872. }
  18873. // Octree
  18874. var sceneOctree = this.getScene().selectionOctree;
  18875. if (sceneOctree !== undefined && sceneOctree !== null) {
  18876. var index = sceneOctree.dynamicContent.indexOf(this);
  18877. if (index !== -1) {
  18878. sceneOctree.dynamicContent.splice(index, 1);
  18879. }
  18880. }
  18881. // Query
  18882. var engine = this.getScene().getEngine();
  18883. if (this._occlusionQuery) {
  18884. this._isOcclusionQueryInProgress = false;
  18885. engine.deleteQuery(this._occlusionQuery);
  18886. this._occlusionQuery = null;
  18887. }
  18888. // Engine
  18889. engine.wipeCaches();
  18890. // Remove from scene
  18891. this.getScene().removeMesh(this);
  18892. if (disposeMaterialAndTextures) {
  18893. if (this.material) {
  18894. this.material.dispose(false, true);
  18895. }
  18896. }
  18897. if (!doNotRecurse) {
  18898. // Particles
  18899. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  18900. if (this.getScene().particleSystems[index].emitter === this) {
  18901. this.getScene().particleSystems[index].dispose();
  18902. index--;
  18903. }
  18904. }
  18905. }
  18906. // facet data
  18907. if (this._facetDataEnabled) {
  18908. this.disableFacetData();
  18909. }
  18910. this.onAfterWorldMatrixUpdateObservable.clear();
  18911. this.onCollideObservable.clear();
  18912. this.onCollisionPositionChangeObservable.clear();
  18913. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  18914. };
  18915. /**
  18916. * Adds the passed mesh as a child to the current mesh.
  18917. * Returns the AbstractMesh.
  18918. */
  18919. AbstractMesh.prototype.addChild = function (mesh) {
  18920. mesh.setParent(this);
  18921. return this;
  18922. };
  18923. /**
  18924. * Removes the passed mesh from the current mesh children list.
  18925. * Returns the AbstractMesh.
  18926. */
  18927. AbstractMesh.prototype.removeChild = function (mesh) {
  18928. mesh.setParent(null);
  18929. return this;
  18930. };
  18931. // Facet data
  18932. /**
  18933. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  18934. * Returns the AbstractMesh.
  18935. */
  18936. AbstractMesh.prototype._initFacetData = function () {
  18937. if (!this._facetNormals) {
  18938. this._facetNormals = new Array();
  18939. }
  18940. if (!this._facetPositions) {
  18941. this._facetPositions = new Array();
  18942. }
  18943. if (!this._facetPartitioning) {
  18944. this._facetPartitioning = new Array();
  18945. }
  18946. this._facetNb = (this.getIndices().length / 3) | 0;
  18947. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  18948. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  18949. for (var f = 0; f < this._facetNb; f++) {
  18950. this._facetNormals[f] = BABYLON.Vector3.Zero();
  18951. this._facetPositions[f] = BABYLON.Vector3.Zero();
  18952. }
  18953. this._facetDataEnabled = true;
  18954. return this;
  18955. };
  18956. /**
  18957. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  18958. * This method can be called within the render loop.
  18959. * 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.
  18960. * Returns the AbstractMesh.
  18961. */
  18962. AbstractMesh.prototype.updateFacetData = function () {
  18963. if (!this._facetDataEnabled) {
  18964. this._initFacetData();
  18965. }
  18966. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18967. var indices = this.getIndices();
  18968. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18969. var bInfo = this.getBoundingInfo();
  18970. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  18971. // init arrays, matrix and sort function on first call
  18972. this._facetDepthSortEnabled = true;
  18973. if (indices instanceof Uint16Array) {
  18974. this._depthSortedIndices = new Uint16Array(indices);
  18975. }
  18976. else if (indices instanceof Uint32Array) {
  18977. this._depthSortedIndices = new Uint32Array(indices);
  18978. }
  18979. else {
  18980. var needs32bits = false;
  18981. for (var i = 0; i < indices.length; i++) {
  18982. if (indices[i] > 65535) {
  18983. needs32bits = true;
  18984. break;
  18985. }
  18986. }
  18987. if (needs32bits) {
  18988. this._depthSortedIndices = new Uint32Array(indices);
  18989. }
  18990. else {
  18991. this._depthSortedIndices = new Uint16Array(indices);
  18992. }
  18993. }
  18994. this._facetDepthSortFunction = function (f1, f2) {
  18995. return (f2.sqDistance - f1.sqDistance);
  18996. };
  18997. if (!this._facetDepthSortFrom) {
  18998. var camera = this.getScene().activeCamera;
  18999. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  19000. }
  19001. this._depthSortedFacets = [];
  19002. for (var f = 0; f < this._facetNb; f++) {
  19003. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  19004. this._depthSortedFacets.push(depthSortedFacet);
  19005. }
  19006. this._invertedMatrix = BABYLON.Matrix.Identity();
  19007. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  19008. }
  19009. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  19010. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  19011. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  19012. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  19013. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  19014. this._subDiv.max = this._partitioningSubdivisions;
  19015. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  19016. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  19017. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  19018. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  19019. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  19020. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  19021. // set the parameters for ComputeNormals()
  19022. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  19023. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  19024. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  19025. this._facetParameters.bInfo = bInfo;
  19026. this._facetParameters.bbSize = this._bbSize;
  19027. this._facetParameters.subDiv = this._subDiv;
  19028. this._facetParameters.ratio = this.partitioningBBoxRatio;
  19029. this._facetParameters.depthSort = this._facetDepthSort;
  19030. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  19031. this.computeWorldMatrix(true);
  19032. this._worldMatrix.invertToRef(this._invertedMatrix);
  19033. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  19034. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  19035. }
  19036. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  19037. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  19038. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  19039. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  19040. var l = (this._depthSortedIndices.length / 3) | 0;
  19041. for (var f = 0; f < l; f++) {
  19042. var sind = this._depthSortedFacets[f].ind;
  19043. this._depthSortedIndices[f * 3] = indices[sind];
  19044. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  19045. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  19046. }
  19047. this.updateIndices(this._depthSortedIndices);
  19048. }
  19049. return this;
  19050. };
  19051. /**
  19052. * Returns the facetLocalNormals array.
  19053. * The normals are expressed in the mesh local space.
  19054. */
  19055. AbstractMesh.prototype.getFacetLocalNormals = function () {
  19056. if (!this._facetNormals) {
  19057. this.updateFacetData();
  19058. }
  19059. return this._facetNormals;
  19060. };
  19061. /**
  19062. * Returns the facetLocalPositions array.
  19063. * The facet positions are expressed in the mesh local space.
  19064. */
  19065. AbstractMesh.prototype.getFacetLocalPositions = function () {
  19066. if (!this._facetPositions) {
  19067. this.updateFacetData();
  19068. }
  19069. return this._facetPositions;
  19070. };
  19071. /**
  19072. * Returns the facetLocalPartioning array.
  19073. */
  19074. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  19075. if (!this._facetPartitioning) {
  19076. this.updateFacetData();
  19077. }
  19078. return this._facetPartitioning;
  19079. };
  19080. /**
  19081. * Returns the i-th facet position in the world system.
  19082. * This method allocates a new Vector3 per call.
  19083. */
  19084. AbstractMesh.prototype.getFacetPosition = function (i) {
  19085. var pos = BABYLON.Vector3.Zero();
  19086. this.getFacetPositionToRef(i, pos);
  19087. return pos;
  19088. };
  19089. /**
  19090. * Sets the reference Vector3 with the i-th facet position in the world system.
  19091. * Returns the AbstractMesh.
  19092. */
  19093. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  19094. var localPos = (this.getFacetLocalPositions())[i];
  19095. var world = this.getWorldMatrix();
  19096. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  19097. return this;
  19098. };
  19099. /**
  19100. * Returns the i-th facet normal in the world system.
  19101. * This method allocates a new Vector3 per call.
  19102. */
  19103. AbstractMesh.prototype.getFacetNormal = function (i) {
  19104. var norm = BABYLON.Vector3.Zero();
  19105. this.getFacetNormalToRef(i, norm);
  19106. return norm;
  19107. };
  19108. /**
  19109. * Sets the reference Vector3 with the i-th facet normal in the world system.
  19110. * Returns the AbstractMesh.
  19111. */
  19112. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  19113. var localNorm = (this.getFacetLocalNormals())[i];
  19114. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  19115. return this;
  19116. };
  19117. /**
  19118. * 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).
  19119. */
  19120. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  19121. var bInfo = this.getBoundingInfo();
  19122. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  19123. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  19124. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  19125. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  19126. return null;
  19127. }
  19128. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  19129. };
  19130. /**
  19131. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  19132. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  19133. * 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.
  19134. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  19135. * 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.
  19136. */
  19137. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  19138. if (checkFace === void 0) { checkFace = false; }
  19139. if (facing === void 0) { facing = true; }
  19140. var world = this.getWorldMatrix();
  19141. var invMat = BABYLON.Tmp.Matrix[5];
  19142. world.invertToRef(invMat);
  19143. var invVect = BABYLON.Tmp.Vector3[8];
  19144. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  19145. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  19146. if (projected) {
  19147. // tranform the local computed projected vector to world coordinates
  19148. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  19149. }
  19150. return closest;
  19151. };
  19152. /**
  19153. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  19154. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  19155. * 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.
  19156. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  19157. * 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.
  19158. */
  19159. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  19160. if (checkFace === void 0) { checkFace = false; }
  19161. if (facing === void 0) { facing = true; }
  19162. var closest = null;
  19163. var tmpx = 0.0;
  19164. var tmpy = 0.0;
  19165. var tmpz = 0.0;
  19166. var d = 0.0; // tmp dot facet normal * facet position
  19167. var t0 = 0.0;
  19168. var projx = 0.0;
  19169. var projy = 0.0;
  19170. var projz = 0.0;
  19171. // Get all the facets in the same partitioning block than (x, y, z)
  19172. var facetPositions = this.getFacetLocalPositions();
  19173. var facetNormals = this.getFacetLocalNormals();
  19174. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  19175. if (!facetsInBlock) {
  19176. return null;
  19177. }
  19178. // Get the closest facet to (x, y, z)
  19179. var shortest = Number.MAX_VALUE; // init distance vars
  19180. var tmpDistance = shortest;
  19181. var fib; // current facet in the block
  19182. var norm; // current facet normal
  19183. var p0; // current facet barycenter position
  19184. // loop on all the facets in the current partitioning block
  19185. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  19186. fib = facetsInBlock[idx];
  19187. norm = facetNormals[fib];
  19188. p0 = facetPositions[fib];
  19189. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  19190. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  19191. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  19192. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  19193. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  19194. projx = x + norm.x * t0;
  19195. projy = y + norm.y * t0;
  19196. projz = z + norm.z * t0;
  19197. tmpx = projx - x;
  19198. tmpy = projy - y;
  19199. tmpz = projz - z;
  19200. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  19201. if (tmpDistance < shortest) {
  19202. shortest = tmpDistance;
  19203. closest = fib;
  19204. if (projected) {
  19205. projected.x = projx;
  19206. projected.y = projy;
  19207. projected.z = projz;
  19208. }
  19209. }
  19210. }
  19211. }
  19212. return closest;
  19213. };
  19214. /**
  19215. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  19216. */
  19217. AbstractMesh.prototype.getFacetDataParameters = function () {
  19218. return this._facetParameters;
  19219. };
  19220. /**
  19221. * Disables the feature FacetData and frees the related memory.
  19222. * Returns the AbstractMesh.
  19223. */
  19224. AbstractMesh.prototype.disableFacetData = function () {
  19225. if (this._facetDataEnabled) {
  19226. this._facetDataEnabled = false;
  19227. this._facetPositions = new Array();
  19228. this._facetNormals = new Array();
  19229. this._facetPartitioning = new Array();
  19230. this._facetParameters = null;
  19231. this._depthSortedIndices = new Uint32Array(0);
  19232. }
  19233. return this;
  19234. };
  19235. /**
  19236. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  19237. * Returns the mesh.
  19238. */
  19239. AbstractMesh.prototype.updateIndices = function (indices) {
  19240. return this;
  19241. };
  19242. /**
  19243. * The mesh Geometry. Actually used by the Mesh object.
  19244. * Returns a blank geometry object.
  19245. */
  19246. /**
  19247. * Creates new normals data for the mesh.
  19248. * @param updatable.
  19249. */
  19250. AbstractMesh.prototype.createNormals = function (updatable) {
  19251. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19252. var indices = this.getIndices();
  19253. var normals;
  19254. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  19255. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19256. }
  19257. else {
  19258. normals = [];
  19259. }
  19260. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  19261. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  19262. };
  19263. /**
  19264. * Align the mesh with a normal.
  19265. * Returns the mesh.
  19266. */
  19267. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  19268. if (!upDirection) {
  19269. upDirection = BABYLON.Axis.Y;
  19270. }
  19271. var axisX = BABYLON.Tmp.Vector3[0];
  19272. var axisZ = BABYLON.Tmp.Vector3[1];
  19273. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  19274. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  19275. if (this.rotationQuaternion) {
  19276. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  19277. }
  19278. else {
  19279. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  19280. }
  19281. return this;
  19282. };
  19283. AbstractMesh.prototype.checkOcclusionQuery = function () {
  19284. var engine = this.getEngine();
  19285. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  19286. this._isOccluded = false;
  19287. return;
  19288. }
  19289. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  19290. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  19291. if (isOcclusionQueryAvailable) {
  19292. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  19293. this._isOcclusionQueryInProgress = false;
  19294. this._occlusionInternalRetryCounter = 0;
  19295. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  19296. }
  19297. else {
  19298. this._occlusionInternalRetryCounter++;
  19299. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  19300. this._isOcclusionQueryInProgress = false;
  19301. this._occlusionInternalRetryCounter = 0;
  19302. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  19303. // if strict continue the last state of the object.
  19304. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  19305. }
  19306. else {
  19307. return;
  19308. }
  19309. }
  19310. }
  19311. var scene = this.getScene();
  19312. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  19313. if (!this._occlusionQuery) {
  19314. this._occlusionQuery = engine.createQuery();
  19315. }
  19316. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  19317. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  19318. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  19319. this._isOcclusionQueryInProgress = true;
  19320. };
  19321. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  19322. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  19323. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  19324. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  19325. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  19326. return AbstractMesh;
  19327. }(BABYLON.TransformNode));
  19328. BABYLON.AbstractMesh = AbstractMesh;
  19329. })(BABYLON || (BABYLON = {}));
  19330. //# sourceMappingURL=babylon.abstractMesh.js.map
  19331. "use strict";
  19332. var BABYLON;
  19333. (function (BABYLON) {
  19334. /**
  19335. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  19336. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  19337. * 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.
  19338. */
  19339. var Light = /** @class */ (function (_super) {
  19340. __extends(Light, _super);
  19341. /**
  19342. * Creates a Light object in the scene.
  19343. * Documentation : http://doc.babylonjs.com/tutorials/lights
  19344. * @param name The firendly name of the light
  19345. * @param scene The scene the light belongs too
  19346. */
  19347. function Light(name, scene) {
  19348. var _this = _super.call(this, name, scene) || this;
  19349. /**
  19350. * Diffuse gives the basic color to an object.
  19351. */
  19352. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  19353. /**
  19354. * Specular produces a highlight color on an object.
  19355. * Note: This is note affecting PBR materials.
  19356. */
  19357. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  19358. /**
  19359. * Strength of the light.
  19360. * Note: By default it is define in the framework own unit.
  19361. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  19362. */
  19363. _this.intensity = 1.0;
  19364. /**
  19365. * Defines how far from the source the light is impacting in scene units.
  19366. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  19367. */
  19368. _this.range = Number.MAX_VALUE;
  19369. /**
  19370. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  19371. * of light.
  19372. */
  19373. _this._photometricScale = 1.0;
  19374. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  19375. _this._radius = 0.00001;
  19376. /**
  19377. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  19378. * exceeding the number allowed of the materials.
  19379. */
  19380. _this.renderPriority = 0;
  19381. /**
  19382. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  19383. * the current shadow generator.
  19384. */
  19385. _this.shadowEnabled = true;
  19386. _this._excludeWithLayerMask = 0;
  19387. _this._includeOnlyWithLayerMask = 0;
  19388. _this._lightmapMode = 0;
  19389. /**
  19390. * @ignore Internal use only.
  19391. */
  19392. _this._excludedMeshesIds = new Array();
  19393. /**
  19394. * @ignore Internal use only.
  19395. */
  19396. _this._includedOnlyMeshesIds = new Array();
  19397. _this.getScene().addLight(_this);
  19398. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  19399. _this._buildUniformLayout();
  19400. _this.includedOnlyMeshes = new Array();
  19401. _this.excludedMeshes = new Array();
  19402. _this._resyncMeshes();
  19403. return _this;
  19404. }
  19405. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  19406. /**
  19407. * If every light affecting the material is in this lightmapMode,
  19408. * material.lightmapTexture adds or multiplies
  19409. * (depends on material.useLightmapAsShadowmap)
  19410. * after every other light calculations.
  19411. */
  19412. get: function () {
  19413. return Light._LIGHTMAP_DEFAULT;
  19414. },
  19415. enumerable: true,
  19416. configurable: true
  19417. });
  19418. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  19419. /**
  19420. * material.lightmapTexture as only diffuse lighting from this light
  19421. * adds only specular lighting from this light
  19422. * adds dynamic shadows
  19423. */
  19424. get: function () {
  19425. return Light._LIGHTMAP_SPECULAR;
  19426. },
  19427. enumerable: true,
  19428. configurable: true
  19429. });
  19430. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  19431. /**
  19432. * material.lightmapTexture as only lighting
  19433. * no light calculation from this light
  19434. * only adds dynamic shadows from this light
  19435. */
  19436. get: function () {
  19437. return Light._LIGHTMAP_SHADOWSONLY;
  19438. },
  19439. enumerable: true,
  19440. configurable: true
  19441. });
  19442. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  19443. /**
  19444. * Each light type uses the default quantity according to its type:
  19445. * point/spot lights use luminous intensity
  19446. * directional lights use illuminance
  19447. */
  19448. get: function () {
  19449. return Light._INTENSITYMODE_AUTOMATIC;
  19450. },
  19451. enumerable: true,
  19452. configurable: true
  19453. });
  19454. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  19455. /**
  19456. * lumen (lm)
  19457. */
  19458. get: function () {
  19459. return Light._INTENSITYMODE_LUMINOUSPOWER;
  19460. },
  19461. enumerable: true,
  19462. configurable: true
  19463. });
  19464. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  19465. /**
  19466. * candela (lm/sr)
  19467. */
  19468. get: function () {
  19469. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  19470. },
  19471. enumerable: true,
  19472. configurable: true
  19473. });
  19474. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  19475. /**
  19476. * lux (lm/m^2)
  19477. */
  19478. get: function () {
  19479. return Light._INTENSITYMODE_ILLUMINANCE;
  19480. },
  19481. enumerable: true,
  19482. configurable: true
  19483. });
  19484. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  19485. /**
  19486. * nit (cd/m^2)
  19487. */
  19488. get: function () {
  19489. return Light._INTENSITYMODE_LUMINANCE;
  19490. },
  19491. enumerable: true,
  19492. configurable: true
  19493. });
  19494. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  19495. /**
  19496. * Light type const id of the point light.
  19497. */
  19498. get: function () {
  19499. return Light._LIGHTTYPEID_POINTLIGHT;
  19500. },
  19501. enumerable: true,
  19502. configurable: true
  19503. });
  19504. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  19505. /**
  19506. * Light type const id of the directional light.
  19507. */
  19508. get: function () {
  19509. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  19510. },
  19511. enumerable: true,
  19512. configurable: true
  19513. });
  19514. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  19515. /**
  19516. * Light type const id of the spot light.
  19517. */
  19518. get: function () {
  19519. return Light._LIGHTTYPEID_SPOTLIGHT;
  19520. },
  19521. enumerable: true,
  19522. configurable: true
  19523. });
  19524. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  19525. /**
  19526. * Light type const id of the hemispheric light.
  19527. */
  19528. get: function () {
  19529. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  19530. },
  19531. enumerable: true,
  19532. configurable: true
  19533. });
  19534. Object.defineProperty(Light.prototype, "intensityMode", {
  19535. /**
  19536. * Gets the photometric scale used to interpret the intensity.
  19537. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  19538. */
  19539. get: function () {
  19540. return this._intensityMode;
  19541. },
  19542. /**
  19543. * Sets the photometric scale used to interpret the intensity.
  19544. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  19545. */
  19546. set: function (value) {
  19547. this._intensityMode = value;
  19548. this._computePhotometricScale();
  19549. },
  19550. enumerable: true,
  19551. configurable: true
  19552. });
  19553. ;
  19554. ;
  19555. Object.defineProperty(Light.prototype, "radius", {
  19556. /**
  19557. * Gets the light radius used by PBR Materials to simulate soft area lights.
  19558. */
  19559. get: function () {
  19560. return this._radius;
  19561. },
  19562. /**
  19563. * sets the light radius used by PBR Materials to simulate soft area lights.
  19564. */
  19565. set: function (value) {
  19566. this._radius = value;
  19567. this._computePhotometricScale();
  19568. },
  19569. enumerable: true,
  19570. configurable: true
  19571. });
  19572. ;
  19573. ;
  19574. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  19575. /**
  19576. * Gets the only meshes impacted by this light.
  19577. */
  19578. get: function () {
  19579. return this._includedOnlyMeshes;
  19580. },
  19581. /**
  19582. * Sets the only meshes impacted by this light.
  19583. */
  19584. set: function (value) {
  19585. this._includedOnlyMeshes = value;
  19586. this._hookArrayForIncludedOnly(value);
  19587. },
  19588. enumerable: true,
  19589. configurable: true
  19590. });
  19591. Object.defineProperty(Light.prototype, "excludedMeshes", {
  19592. /**
  19593. * Gets the meshes not impacted by this light.
  19594. */
  19595. get: function () {
  19596. return this._excludedMeshes;
  19597. },
  19598. /**
  19599. * Sets the meshes not impacted by this light.
  19600. */
  19601. set: function (value) {
  19602. this._excludedMeshes = value;
  19603. this._hookArrayForExcluded(value);
  19604. },
  19605. enumerable: true,
  19606. configurable: true
  19607. });
  19608. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  19609. /**
  19610. * Gets the layer id use to find what meshes are not impacted by the light.
  19611. * Inactive if 0
  19612. */
  19613. get: function () {
  19614. return this._excludeWithLayerMask;
  19615. },
  19616. /**
  19617. * Sets the layer id use to find what meshes are not impacted by the light.
  19618. * Inactive if 0
  19619. */
  19620. set: function (value) {
  19621. this._excludeWithLayerMask = value;
  19622. this._resyncMeshes();
  19623. },
  19624. enumerable: true,
  19625. configurable: true
  19626. });
  19627. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  19628. /**
  19629. * Gets the layer id use to find what meshes are impacted by the light.
  19630. * Inactive if 0
  19631. */
  19632. get: function () {
  19633. return this._includeOnlyWithLayerMask;
  19634. },
  19635. /**
  19636. * Sets the layer id use to find what meshes are impacted by the light.
  19637. * Inactive if 0
  19638. */
  19639. set: function (value) {
  19640. this._includeOnlyWithLayerMask = value;
  19641. this._resyncMeshes();
  19642. },
  19643. enumerable: true,
  19644. configurable: true
  19645. });
  19646. Object.defineProperty(Light.prototype, "lightmapMode", {
  19647. /**
  19648. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  19649. */
  19650. get: function () {
  19651. return this._lightmapMode;
  19652. },
  19653. /**
  19654. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  19655. */
  19656. set: function (value) {
  19657. if (this._lightmapMode === value) {
  19658. return;
  19659. }
  19660. this._lightmapMode = value;
  19661. this._markMeshesAsLightDirty();
  19662. },
  19663. enumerable: true,
  19664. configurable: true
  19665. });
  19666. /**
  19667. * Returns the string "Light".
  19668. * @returns the class name
  19669. */
  19670. Light.prototype.getClassName = function () {
  19671. return "Light";
  19672. };
  19673. /**
  19674. * Converts the light information to a readable string for debug purpose.
  19675. * @param fullDetails Supports for multiple levels of logging within scene loading
  19676. * @returns the human readable light info
  19677. */
  19678. Light.prototype.toString = function (fullDetails) {
  19679. var ret = "Name: " + this.name;
  19680. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  19681. if (this.animations) {
  19682. for (var i = 0; i < this.animations.length; i++) {
  19683. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19684. }
  19685. }
  19686. if (fullDetails) {
  19687. }
  19688. return ret;
  19689. };
  19690. /**
  19691. * Set the enabled state of this node.
  19692. * @param value - the new enabled state
  19693. * @see isEnabled
  19694. */
  19695. Light.prototype.setEnabled = function (value) {
  19696. _super.prototype.setEnabled.call(this, value);
  19697. this._resyncMeshes();
  19698. };
  19699. /**
  19700. * Returns the Light associated shadow generator if any.
  19701. * @return the associated shadow generator.
  19702. */
  19703. Light.prototype.getShadowGenerator = function () {
  19704. return this._shadowGenerator;
  19705. };
  19706. /**
  19707. * Returns a Vector3, the absolute light position in the World.
  19708. * @returns the world space position of the light
  19709. */
  19710. Light.prototype.getAbsolutePosition = function () {
  19711. return BABYLON.Vector3.Zero();
  19712. };
  19713. /**
  19714. * Specifies if the light will affect the passed mesh.
  19715. * @param mesh The mesh to test against the light
  19716. * @return true the mesh is affected otherwise, false.
  19717. */
  19718. Light.prototype.canAffectMesh = function (mesh) {
  19719. if (!mesh) {
  19720. return true;
  19721. }
  19722. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  19723. return false;
  19724. }
  19725. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  19726. return false;
  19727. }
  19728. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  19729. return false;
  19730. }
  19731. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  19732. return false;
  19733. }
  19734. return true;
  19735. };
  19736. /**
  19737. * Computes and Returns the light World matrix.
  19738. * @returns the world matrix
  19739. */
  19740. Light.prototype.getWorldMatrix = function () {
  19741. this._currentRenderId = this.getScene().getRenderId();
  19742. var worldMatrix = this._getWorldMatrix();
  19743. if (this.parent && this.parent.getWorldMatrix) {
  19744. if (!this._parentedWorldMatrix) {
  19745. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  19746. }
  19747. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  19748. this._markSyncedWithParent();
  19749. return this._parentedWorldMatrix;
  19750. }
  19751. return worldMatrix;
  19752. };
  19753. /**
  19754. * Sort function to order lights for rendering.
  19755. * @param a First Light object to compare to second.
  19756. * @param b Second Light object to compare first.
  19757. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  19758. */
  19759. Light.CompareLightsPriority = function (a, b) {
  19760. //shadow-casting lights have priority over non-shadow-casting lights
  19761. //the renderPrioirty is a secondary sort criterion
  19762. if (a.shadowEnabled !== b.shadowEnabled) {
  19763. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  19764. }
  19765. return b.renderPriority - a.renderPriority;
  19766. };
  19767. /**
  19768. * Releases resources associated with this node.
  19769. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19770. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19771. */
  19772. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19773. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19774. if (this._shadowGenerator) {
  19775. this._shadowGenerator.dispose();
  19776. this._shadowGenerator = null;
  19777. }
  19778. // Animations
  19779. this.getScene().stopAnimation(this);
  19780. // Remove from meshes
  19781. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19782. var mesh = _a[_i];
  19783. mesh._removeLightSource(this);
  19784. }
  19785. this._uniformBuffer.dispose();
  19786. // Remove from scene
  19787. this.getScene().removeLight(this);
  19788. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19789. };
  19790. /**
  19791. * Returns the light type ID (integer).
  19792. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  19793. */
  19794. Light.prototype.getTypeID = function () {
  19795. return 0;
  19796. };
  19797. /**
  19798. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  19799. * @returns the scaled intensity in intensity mode unit
  19800. */
  19801. Light.prototype.getScaledIntensity = function () {
  19802. return this._photometricScale * this.intensity;
  19803. };
  19804. /**
  19805. * Returns a new Light object, named "name", from the current one.
  19806. * @param name The name of the cloned light
  19807. * @returns the new created light
  19808. */
  19809. Light.prototype.clone = function (name) {
  19810. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  19811. if (!constructor) {
  19812. return null;
  19813. }
  19814. return BABYLON.SerializationHelper.Clone(constructor, this);
  19815. };
  19816. /**
  19817. * Serializes the current light into a Serialization object.
  19818. * @returns the serialized object.
  19819. */
  19820. Light.prototype.serialize = function () {
  19821. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  19822. // Type
  19823. serializationObject.type = this.getTypeID();
  19824. // Parent
  19825. if (this.parent) {
  19826. serializationObject.parentId = this.parent.id;
  19827. }
  19828. // Inclusion / exclusions
  19829. if (this.excludedMeshes.length > 0) {
  19830. serializationObject.excludedMeshesIds = [];
  19831. this.excludedMeshes.forEach(function (mesh) {
  19832. serializationObject.excludedMeshesIds.push(mesh.id);
  19833. });
  19834. }
  19835. if (this.includedOnlyMeshes.length > 0) {
  19836. serializationObject.includedOnlyMeshesIds = [];
  19837. this.includedOnlyMeshes.forEach(function (mesh) {
  19838. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  19839. });
  19840. }
  19841. // Animations
  19842. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  19843. serializationObject.ranges = this.serializeAnimationRanges();
  19844. return serializationObject;
  19845. };
  19846. /**
  19847. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  19848. * This new light is named "name" and added to the passed scene.
  19849. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  19850. * @param name The friendly name of the light
  19851. * @param scene The scene the new light will belong to
  19852. * @returns the constructor function
  19853. */
  19854. Light.GetConstructorFromName = function (type, name, scene) {
  19855. switch (type) {
  19856. case 0:
  19857. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  19858. case 1:
  19859. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  19860. case 2:
  19861. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  19862. case 3:
  19863. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  19864. }
  19865. return null;
  19866. };
  19867. /**
  19868. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  19869. * @param parsedLight The JSON representation of the light
  19870. * @param scene The scene to create the parsed light in
  19871. * @returns the created light after parsing
  19872. */
  19873. Light.Parse = function (parsedLight, scene) {
  19874. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  19875. if (!constructor) {
  19876. return null;
  19877. }
  19878. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  19879. // Inclusion / exclusions
  19880. if (parsedLight.excludedMeshesIds) {
  19881. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  19882. }
  19883. if (parsedLight.includedOnlyMeshesIds) {
  19884. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  19885. }
  19886. // Parent
  19887. if (parsedLight.parentId) {
  19888. light._waitingParentId = parsedLight.parentId;
  19889. }
  19890. // Animations
  19891. if (parsedLight.animations) {
  19892. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  19893. var parsedAnimation = parsedLight.animations[animationIndex];
  19894. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19895. }
  19896. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  19897. }
  19898. if (parsedLight.autoAnimate) {
  19899. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  19900. }
  19901. return light;
  19902. };
  19903. Light.prototype._hookArrayForExcluded = function (array) {
  19904. var _this = this;
  19905. var oldPush = array.push;
  19906. array.push = function () {
  19907. var items = [];
  19908. for (var _i = 0; _i < arguments.length; _i++) {
  19909. items[_i] = arguments[_i];
  19910. }
  19911. var result = oldPush.apply(array, items);
  19912. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  19913. var item = items_1[_a];
  19914. item._resyncLighSource(_this);
  19915. }
  19916. return result;
  19917. };
  19918. var oldSplice = array.splice;
  19919. array.splice = function (index, deleteCount) {
  19920. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19921. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  19922. var item = deleted_1[_i];
  19923. item._resyncLighSource(_this);
  19924. }
  19925. return deleted;
  19926. };
  19927. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  19928. var item = array_1[_i];
  19929. item._resyncLighSource(this);
  19930. }
  19931. };
  19932. Light.prototype._hookArrayForIncludedOnly = function (array) {
  19933. var _this = this;
  19934. var oldPush = array.push;
  19935. array.push = function () {
  19936. var items = [];
  19937. for (var _i = 0; _i < arguments.length; _i++) {
  19938. items[_i] = arguments[_i];
  19939. }
  19940. var result = oldPush.apply(array, items);
  19941. _this._resyncMeshes();
  19942. return result;
  19943. };
  19944. var oldSplice = array.splice;
  19945. array.splice = function (index, deleteCount) {
  19946. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19947. _this._resyncMeshes();
  19948. return deleted;
  19949. };
  19950. this._resyncMeshes();
  19951. };
  19952. Light.prototype._resyncMeshes = function () {
  19953. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19954. var mesh = _a[_i];
  19955. mesh._resyncLighSource(this);
  19956. }
  19957. };
  19958. /**
  19959. * Forces the meshes to update their light related information in their rendering used effects
  19960. * @ignore Internal Use Only
  19961. */
  19962. Light.prototype._markMeshesAsLightDirty = function () {
  19963. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19964. var mesh = _a[_i];
  19965. if (mesh._lightSources.indexOf(this) !== -1) {
  19966. mesh._markSubMeshesAsLightDirty();
  19967. }
  19968. }
  19969. };
  19970. /**
  19971. * Recomputes the cached photometric scale if needed.
  19972. */
  19973. Light.prototype._computePhotometricScale = function () {
  19974. this._photometricScale = this._getPhotometricScale();
  19975. this.getScene().resetCachedMaterial();
  19976. };
  19977. /**
  19978. * Returns the Photometric Scale according to the light type and intensity mode.
  19979. */
  19980. Light.prototype._getPhotometricScale = function () {
  19981. var photometricScale = 0.0;
  19982. var lightTypeID = this.getTypeID();
  19983. //get photometric mode
  19984. var photometricMode = this.intensityMode;
  19985. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  19986. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  19987. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  19988. }
  19989. else {
  19990. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  19991. }
  19992. }
  19993. //compute photometric scale
  19994. switch (lightTypeID) {
  19995. case Light.LIGHTTYPEID_POINTLIGHT:
  19996. case Light.LIGHTTYPEID_SPOTLIGHT:
  19997. switch (photometricMode) {
  19998. case Light.INTENSITYMODE_LUMINOUSPOWER:
  19999. photometricScale = 1.0 / (4.0 * Math.PI);
  20000. break;
  20001. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  20002. photometricScale = 1.0;
  20003. break;
  20004. case Light.INTENSITYMODE_LUMINANCE:
  20005. photometricScale = this.radius * this.radius;
  20006. break;
  20007. }
  20008. break;
  20009. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  20010. switch (photometricMode) {
  20011. case Light.INTENSITYMODE_ILLUMINANCE:
  20012. photometricScale = 1.0;
  20013. break;
  20014. case Light.INTENSITYMODE_LUMINANCE:
  20015. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  20016. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  20017. var apexAngleRadians = this.radius;
  20018. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  20019. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  20020. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  20021. photometricScale = solidAngle;
  20022. break;
  20023. }
  20024. break;
  20025. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  20026. // No fall off in hemisperic light.
  20027. photometricScale = 1.0;
  20028. break;
  20029. }
  20030. return photometricScale;
  20031. };
  20032. /**
  20033. * Reorder the light in the scene according to their defined priority.
  20034. * @ignore Internal Use Only
  20035. */
  20036. Light.prototype._reorderLightsInScene = function () {
  20037. var scene = this.getScene();
  20038. if (this._renderPriority != 0) {
  20039. scene.requireLightSorting = true;
  20040. }
  20041. this.getScene().sortLightsByPriority();
  20042. };
  20043. //lightmapMode Consts
  20044. Light._LIGHTMAP_DEFAULT = 0;
  20045. Light._LIGHTMAP_SPECULAR = 1;
  20046. Light._LIGHTMAP_SHADOWSONLY = 2;
  20047. // Intensity Mode Consts
  20048. Light._INTENSITYMODE_AUTOMATIC = 0;
  20049. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  20050. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  20051. Light._INTENSITYMODE_ILLUMINANCE = 3;
  20052. Light._INTENSITYMODE_LUMINANCE = 4;
  20053. // Light types ids const.
  20054. Light._LIGHTTYPEID_POINTLIGHT = 0;
  20055. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  20056. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  20057. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  20058. __decorate([
  20059. BABYLON.serializeAsColor3()
  20060. ], Light.prototype, "diffuse", void 0);
  20061. __decorate([
  20062. BABYLON.serializeAsColor3()
  20063. ], Light.prototype, "specular", void 0);
  20064. __decorate([
  20065. BABYLON.serialize()
  20066. ], Light.prototype, "intensity", void 0);
  20067. __decorate([
  20068. BABYLON.serialize()
  20069. ], Light.prototype, "range", void 0);
  20070. __decorate([
  20071. BABYLON.serialize()
  20072. ], Light.prototype, "intensityMode", null);
  20073. __decorate([
  20074. BABYLON.serialize()
  20075. ], Light.prototype, "radius", null);
  20076. __decorate([
  20077. BABYLON.serialize()
  20078. ], Light.prototype, "_renderPriority", void 0);
  20079. __decorate([
  20080. BABYLON.expandToProperty("_reorderLightsInScene")
  20081. ], Light.prototype, "renderPriority", void 0);
  20082. __decorate([
  20083. BABYLON.serialize()
  20084. ], Light.prototype, "shadowEnabled", void 0);
  20085. __decorate([
  20086. BABYLON.serialize("excludeWithLayerMask")
  20087. ], Light.prototype, "_excludeWithLayerMask", void 0);
  20088. __decorate([
  20089. BABYLON.serialize("includeOnlyWithLayerMask")
  20090. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  20091. __decorate([
  20092. BABYLON.serialize("lightmapMode")
  20093. ], Light.prototype, "_lightmapMode", void 0);
  20094. return Light;
  20095. }(BABYLON.Node));
  20096. BABYLON.Light = Light;
  20097. })(BABYLON || (BABYLON = {}));
  20098. //# sourceMappingURL=babylon.light.js.map
  20099. "use strict";
  20100. var BABYLON;
  20101. (function (BABYLON) {
  20102. var Camera = /** @class */ (function (_super) {
  20103. __extends(Camera, _super);
  20104. function Camera(name, position, scene) {
  20105. var _this = _super.call(this, name, scene) || this;
  20106. /**
  20107. * The vector the camera should consider as up.
  20108. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  20109. */
  20110. _this.upVector = BABYLON.Vector3.Up();
  20111. _this.orthoLeft = null;
  20112. _this.orthoRight = null;
  20113. _this.orthoBottom = null;
  20114. _this.orthoTop = null;
  20115. /**
  20116. * FOV is set in Radians. (default is 0.8)
  20117. */
  20118. _this.fov = 0.8;
  20119. _this.minZ = 1;
  20120. _this.maxZ = 10000.0;
  20121. _this.inertia = 0.9;
  20122. _this.mode = Camera.PERSPECTIVE_CAMERA;
  20123. _this.isIntermediate = false;
  20124. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  20125. /**
  20126. * Restricts the camera to viewing objects with the same layerMask.
  20127. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  20128. */
  20129. _this.layerMask = 0x0FFFFFFF;
  20130. /**
  20131. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  20132. */
  20133. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  20134. // Camera rig members
  20135. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  20136. _this._rigCameras = new Array();
  20137. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  20138. _this._skipRendering = false;
  20139. _this.customRenderTargets = new Array();
  20140. // Observables
  20141. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  20142. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  20143. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  20144. _this.onRestoreStateObservable = new BABYLON.Observable();
  20145. // Cache
  20146. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  20147. _this._projectionMatrix = new BABYLON.Matrix();
  20148. _this._doNotComputeProjectionMatrix = false;
  20149. _this._postProcesses = new Array();
  20150. _this._transformMatrix = BABYLON.Matrix.Zero();
  20151. _this._activeMeshes = new BABYLON.SmartArray(256);
  20152. _this._globalPosition = BABYLON.Vector3.Zero();
  20153. _this._refreshFrustumPlanes = true;
  20154. _this.getScene().addCamera(_this);
  20155. if (!_this.getScene().activeCamera) {
  20156. _this.getScene().activeCamera = _this;
  20157. }
  20158. _this.position = position;
  20159. return _this;
  20160. }
  20161. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  20162. get: function () {
  20163. return Camera._PERSPECTIVE_CAMERA;
  20164. },
  20165. enumerable: true,
  20166. configurable: true
  20167. });
  20168. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  20169. get: function () {
  20170. return Camera._ORTHOGRAPHIC_CAMERA;
  20171. },
  20172. enumerable: true,
  20173. configurable: true
  20174. });
  20175. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  20176. /**
  20177. * This is the default FOV mode for perspective cameras.
  20178. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  20179. *
  20180. */
  20181. get: function () {
  20182. return Camera._FOVMODE_VERTICAL_FIXED;
  20183. },
  20184. enumerable: true,
  20185. configurable: true
  20186. });
  20187. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  20188. /**
  20189. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  20190. *
  20191. */
  20192. get: function () {
  20193. return Camera._FOVMODE_HORIZONTAL_FIXED;
  20194. },
  20195. enumerable: true,
  20196. configurable: true
  20197. });
  20198. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  20199. get: function () {
  20200. return Camera._RIG_MODE_NONE;
  20201. },
  20202. enumerable: true,
  20203. configurable: true
  20204. });
  20205. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  20206. get: function () {
  20207. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  20208. },
  20209. enumerable: true,
  20210. configurable: true
  20211. });
  20212. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  20213. get: function () {
  20214. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  20215. },
  20216. enumerable: true,
  20217. configurable: true
  20218. });
  20219. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  20220. get: function () {
  20221. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  20222. },
  20223. enumerable: true,
  20224. configurable: true
  20225. });
  20226. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  20227. get: function () {
  20228. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  20229. },
  20230. enumerable: true,
  20231. configurable: true
  20232. });
  20233. Object.defineProperty(Camera, "RIG_MODE_VR", {
  20234. get: function () {
  20235. return Camera._RIG_MODE_VR;
  20236. },
  20237. enumerable: true,
  20238. configurable: true
  20239. });
  20240. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  20241. get: function () {
  20242. return Camera._RIG_MODE_WEBVR;
  20243. },
  20244. enumerable: true,
  20245. configurable: true
  20246. });
  20247. /**
  20248. * Store current camera state (fov, position, etc..)
  20249. */
  20250. Camera.prototype.storeState = function () {
  20251. this._stateStored = true;
  20252. this._storedFov = this.fov;
  20253. return this;
  20254. };
  20255. /**
  20256. * Restores the camera state values if it has been stored. You must call storeState() first
  20257. */
  20258. Camera.prototype._restoreStateValues = function () {
  20259. if (!this._stateStored) {
  20260. return false;
  20261. }
  20262. this.fov = this._storedFov;
  20263. return true;
  20264. };
  20265. /**
  20266. * Restored camera state. You must call storeState() first
  20267. */
  20268. Camera.prototype.restoreState = function () {
  20269. if (this._restoreStateValues()) {
  20270. this.onRestoreStateObservable.notifyObservers(this);
  20271. return true;
  20272. }
  20273. return false;
  20274. };
  20275. Camera.prototype.getClassName = function () {
  20276. return "Camera";
  20277. };
  20278. /**
  20279. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  20280. */
  20281. Camera.prototype.toString = function (fullDetails) {
  20282. var ret = "Name: " + this.name;
  20283. ret += ", type: " + this.getClassName();
  20284. if (this.animations) {
  20285. for (var i = 0; i < this.animations.length; i++) {
  20286. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  20287. }
  20288. }
  20289. if (fullDetails) {
  20290. }
  20291. return ret;
  20292. };
  20293. Object.defineProperty(Camera.prototype, "globalPosition", {
  20294. get: function () {
  20295. return this._globalPosition;
  20296. },
  20297. enumerable: true,
  20298. configurable: true
  20299. });
  20300. Camera.prototype.getActiveMeshes = function () {
  20301. return this._activeMeshes;
  20302. };
  20303. Camera.prototype.isActiveMesh = function (mesh) {
  20304. return (this._activeMeshes.indexOf(mesh) !== -1);
  20305. };
  20306. //Cache
  20307. Camera.prototype._initCache = function () {
  20308. _super.prototype._initCache.call(this);
  20309. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20310. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20311. this._cache.mode = undefined;
  20312. this._cache.minZ = undefined;
  20313. this._cache.maxZ = undefined;
  20314. this._cache.fov = undefined;
  20315. this._cache.fovMode = undefined;
  20316. this._cache.aspectRatio = undefined;
  20317. this._cache.orthoLeft = undefined;
  20318. this._cache.orthoRight = undefined;
  20319. this._cache.orthoBottom = undefined;
  20320. this._cache.orthoTop = undefined;
  20321. this._cache.renderWidth = undefined;
  20322. this._cache.renderHeight = undefined;
  20323. };
  20324. Camera.prototype._updateCache = function (ignoreParentClass) {
  20325. if (!ignoreParentClass) {
  20326. _super.prototype._updateCache.call(this);
  20327. }
  20328. this._cache.position.copyFrom(this.position);
  20329. this._cache.upVector.copyFrom(this.upVector);
  20330. };
  20331. // Synchronized
  20332. Camera.prototype._isSynchronized = function () {
  20333. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  20334. };
  20335. Camera.prototype._isSynchronizedViewMatrix = function () {
  20336. if (!_super.prototype._isSynchronized.call(this))
  20337. return false;
  20338. return this._cache.position.equals(this.position)
  20339. && this._cache.upVector.equals(this.upVector)
  20340. && this.isSynchronizedWithParent();
  20341. };
  20342. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  20343. var check = this._cache.mode === this.mode
  20344. && this._cache.minZ === this.minZ
  20345. && this._cache.maxZ === this.maxZ;
  20346. if (!check) {
  20347. return false;
  20348. }
  20349. var engine = this.getEngine();
  20350. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  20351. check = this._cache.fov === this.fov
  20352. && this._cache.fovMode === this.fovMode
  20353. && this._cache.aspectRatio === engine.getAspectRatio(this);
  20354. }
  20355. else {
  20356. check = this._cache.orthoLeft === this.orthoLeft
  20357. && this._cache.orthoRight === this.orthoRight
  20358. && this._cache.orthoBottom === this.orthoBottom
  20359. && this._cache.orthoTop === this.orthoTop
  20360. && this._cache.renderWidth === engine.getRenderWidth()
  20361. && this._cache.renderHeight === engine.getRenderHeight();
  20362. }
  20363. return check;
  20364. };
  20365. // Controls
  20366. Camera.prototype.attachControl = function (element, noPreventDefault) {
  20367. };
  20368. Camera.prototype.detachControl = function (element) {
  20369. };
  20370. Camera.prototype.update = function () {
  20371. this._checkInputs();
  20372. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20373. this._updateRigCameras();
  20374. }
  20375. };
  20376. Camera.prototype._checkInputs = function () {
  20377. this.onAfterCheckInputsObservable.notifyObservers(this);
  20378. };
  20379. Object.defineProperty(Camera.prototype, "rigCameras", {
  20380. get: function () {
  20381. return this._rigCameras;
  20382. },
  20383. enumerable: true,
  20384. configurable: true
  20385. });
  20386. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  20387. get: function () {
  20388. return this._rigPostProcess;
  20389. },
  20390. enumerable: true,
  20391. configurable: true
  20392. });
  20393. /**
  20394. * Internal, gets the first post proces.
  20395. * @returns the first post process to be run on this camera.
  20396. */
  20397. Camera.prototype._getFirstPostProcess = function () {
  20398. for (var pp in this._postProcesses) {
  20399. if (this._postProcesses[pp] !== null) {
  20400. return this._postProcesses[pp];
  20401. }
  20402. }
  20403. return null;
  20404. };
  20405. Camera.prototype._cascadePostProcessesToRigCams = function () {
  20406. // invalidate framebuffer
  20407. var firstPostProcess = this._getFirstPostProcess();
  20408. if (firstPostProcess) {
  20409. firstPostProcess.markTextureDirty();
  20410. }
  20411. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  20412. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  20413. var cam = this._rigCameras[i];
  20414. var rigPostProcess = cam._rigPostProcess;
  20415. // for VR rig, there does not have to be a post process
  20416. if (rigPostProcess) {
  20417. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  20418. if (isPass) {
  20419. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  20420. cam.isIntermediate = this._postProcesses.length === 0;
  20421. }
  20422. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  20423. rigPostProcess.markTextureDirty();
  20424. }
  20425. else {
  20426. cam._postProcesses = this._postProcesses.slice(0);
  20427. }
  20428. }
  20429. };
  20430. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  20431. if (insertAt === void 0) { insertAt = null; }
  20432. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  20433. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  20434. return 0;
  20435. }
  20436. if (insertAt == null || insertAt < 0) {
  20437. this._postProcesses.push(postProcess);
  20438. }
  20439. else if (this._postProcesses[insertAt] === null) {
  20440. this._postProcesses[insertAt] = postProcess;
  20441. }
  20442. else {
  20443. this._postProcesses.splice(insertAt, 0, postProcess);
  20444. }
  20445. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  20446. return this._postProcesses.indexOf(postProcess);
  20447. };
  20448. Camera.prototype.detachPostProcess = function (postProcess) {
  20449. var idx = this._postProcesses.indexOf(postProcess);
  20450. if (idx !== -1) {
  20451. this._postProcesses[idx] = null;
  20452. }
  20453. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  20454. };
  20455. Camera.prototype.getWorldMatrix = function () {
  20456. if (!this._worldMatrix) {
  20457. this._worldMatrix = BABYLON.Matrix.Identity();
  20458. }
  20459. var viewMatrix = this.getViewMatrix();
  20460. viewMatrix.invertToRef(this._worldMatrix);
  20461. return this._worldMatrix;
  20462. };
  20463. Camera.prototype._getViewMatrix = function () {
  20464. return BABYLON.Matrix.Identity();
  20465. };
  20466. Camera.prototype.getViewMatrix = function (force) {
  20467. if (!force && this._isSynchronizedViewMatrix()) {
  20468. return this._computedViewMatrix;
  20469. }
  20470. this.updateCache();
  20471. this._computedViewMatrix = this._getViewMatrix();
  20472. this._currentRenderId = this.getScene().getRenderId();
  20473. this._refreshFrustumPlanes = true;
  20474. if (!this.parent || !this.parent.getWorldMatrix) {
  20475. this._globalPosition.copyFrom(this.position);
  20476. }
  20477. else {
  20478. if (!this._worldMatrix) {
  20479. this._worldMatrix = BABYLON.Matrix.Identity();
  20480. }
  20481. this._computedViewMatrix.invertToRef(this._worldMatrix);
  20482. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  20483. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  20484. this._computedViewMatrix.invert();
  20485. this._markSyncedWithParent();
  20486. }
  20487. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  20488. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  20489. }
  20490. this.onViewMatrixChangedObservable.notifyObservers(this);
  20491. return this._computedViewMatrix;
  20492. };
  20493. Camera.prototype.freezeProjectionMatrix = function (projection) {
  20494. this._doNotComputeProjectionMatrix = true;
  20495. if (projection !== undefined) {
  20496. this._projectionMatrix = projection;
  20497. }
  20498. };
  20499. ;
  20500. Camera.prototype.unfreezeProjectionMatrix = function () {
  20501. this._doNotComputeProjectionMatrix = false;
  20502. };
  20503. ;
  20504. Camera.prototype.getProjectionMatrix = function (force) {
  20505. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  20506. return this._projectionMatrix;
  20507. }
  20508. // Cache
  20509. this._cache.mode = this.mode;
  20510. this._cache.minZ = this.minZ;
  20511. this._cache.maxZ = this.maxZ;
  20512. // Matrix
  20513. this._refreshFrustumPlanes = true;
  20514. var engine = this.getEngine();
  20515. var scene = this.getScene();
  20516. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  20517. this._cache.fov = this.fov;
  20518. this._cache.fovMode = this.fovMode;
  20519. this._cache.aspectRatio = engine.getAspectRatio(this);
  20520. if (this.minZ <= 0) {
  20521. this.minZ = 0.1;
  20522. }
  20523. if (scene.useRightHandedSystem) {
  20524. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  20525. }
  20526. else {
  20527. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  20528. }
  20529. }
  20530. else {
  20531. var halfWidth = engine.getRenderWidth() / 2.0;
  20532. var halfHeight = engine.getRenderHeight() / 2.0;
  20533. if (scene.useRightHandedSystem) {
  20534. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  20535. }
  20536. else {
  20537. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  20538. }
  20539. this._cache.orthoLeft = this.orthoLeft;
  20540. this._cache.orthoRight = this.orthoRight;
  20541. this._cache.orthoBottom = this.orthoBottom;
  20542. this._cache.orthoTop = this.orthoTop;
  20543. this._cache.renderWidth = engine.getRenderWidth();
  20544. this._cache.renderHeight = engine.getRenderHeight();
  20545. }
  20546. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  20547. return this._projectionMatrix;
  20548. };
  20549. Camera.prototype.getTranformationMatrix = function () {
  20550. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  20551. return this._transformMatrix;
  20552. };
  20553. Camera.prototype.updateFrustumPlanes = function () {
  20554. if (!this._refreshFrustumPlanes) {
  20555. return;
  20556. }
  20557. this.getTranformationMatrix();
  20558. if (!this._frustumPlanes) {
  20559. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  20560. }
  20561. else {
  20562. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  20563. }
  20564. this._refreshFrustumPlanes = false;
  20565. };
  20566. Camera.prototype.isInFrustum = function (target) {
  20567. this.updateFrustumPlanes();
  20568. return target.isInFrustum(this._frustumPlanes);
  20569. };
  20570. Camera.prototype.isCompletelyInFrustum = function (target) {
  20571. this.updateFrustumPlanes();
  20572. return target.isCompletelyInFrustum(this._frustumPlanes);
  20573. };
  20574. Camera.prototype.getForwardRay = function (length, transform, origin) {
  20575. if (length === void 0) { length = 100; }
  20576. if (!transform) {
  20577. transform = this.getWorldMatrix();
  20578. }
  20579. if (!origin) {
  20580. origin = this.position;
  20581. }
  20582. var forward = new BABYLON.Vector3(0, 0, 1);
  20583. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  20584. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  20585. return new BABYLON.Ray(origin, direction, length);
  20586. };
  20587. /**
  20588. * Releases resources associated with this node.
  20589. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20590. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20591. */
  20592. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20593. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20594. // Observables
  20595. this.onViewMatrixChangedObservable.clear();
  20596. this.onProjectionMatrixChangedObservable.clear();
  20597. this.onAfterCheckInputsObservable.clear();
  20598. this.onRestoreStateObservable.clear();
  20599. // Inputs
  20600. if (this.inputs) {
  20601. this.inputs.clear();
  20602. }
  20603. // Animations
  20604. this.getScene().stopAnimation(this);
  20605. // Remove from scene
  20606. this.getScene().removeCamera(this);
  20607. while (this._rigCameras.length > 0) {
  20608. var camera = this._rigCameras.pop();
  20609. if (camera) {
  20610. camera.dispose();
  20611. }
  20612. }
  20613. // Postprocesses
  20614. if (this._rigPostProcess) {
  20615. this._rigPostProcess.dispose(this);
  20616. this._rigPostProcess = null;
  20617. this._postProcesses = [];
  20618. }
  20619. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20620. this._rigPostProcess = null;
  20621. this._postProcesses = [];
  20622. }
  20623. else {
  20624. var i = this._postProcesses.length;
  20625. while (--i >= 0) {
  20626. var postProcess = this._postProcesses[i];
  20627. if (postProcess) {
  20628. postProcess.dispose(this);
  20629. }
  20630. }
  20631. }
  20632. // Render targets
  20633. var i = this.customRenderTargets.length;
  20634. while (--i >= 0) {
  20635. this.customRenderTargets[i].dispose();
  20636. }
  20637. this.customRenderTargets = [];
  20638. // Active Meshes
  20639. this._activeMeshes.dispose();
  20640. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20641. };
  20642. Object.defineProperty(Camera.prototype, "leftCamera", {
  20643. // ---- Camera rigs section ----
  20644. get: function () {
  20645. if (this._rigCameras.length < 1) {
  20646. return null;
  20647. }
  20648. return this._rigCameras[0];
  20649. },
  20650. enumerable: true,
  20651. configurable: true
  20652. });
  20653. Object.defineProperty(Camera.prototype, "rightCamera", {
  20654. get: function () {
  20655. if (this._rigCameras.length < 2) {
  20656. return null;
  20657. }
  20658. return this._rigCameras[1];
  20659. },
  20660. enumerable: true,
  20661. configurable: true
  20662. });
  20663. Camera.prototype.getLeftTarget = function () {
  20664. if (this._rigCameras.length < 1) {
  20665. return null;
  20666. }
  20667. return this._rigCameras[0].getTarget();
  20668. };
  20669. Camera.prototype.getRightTarget = function () {
  20670. if (this._rigCameras.length < 2) {
  20671. return null;
  20672. }
  20673. return this._rigCameras[1].getTarget();
  20674. };
  20675. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  20676. if (this.cameraRigMode === mode) {
  20677. return;
  20678. }
  20679. while (this._rigCameras.length > 0) {
  20680. var camera = this._rigCameras.pop();
  20681. if (camera) {
  20682. camera.dispose();
  20683. }
  20684. }
  20685. this.cameraRigMode = mode;
  20686. this._cameraRigParams = {};
  20687. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  20688. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  20689. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  20690. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  20691. // create the rig cameras, unless none
  20692. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20693. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  20694. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  20695. if (leftCamera && rightCamera) {
  20696. this._rigCameras.push(leftCamera);
  20697. this._rigCameras.push(rightCamera);
  20698. }
  20699. }
  20700. switch (this.cameraRigMode) {
  20701. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  20702. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  20703. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  20704. break;
  20705. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  20706. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  20707. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  20708. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  20709. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  20710. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  20711. break;
  20712. case Camera.RIG_MODE_VR:
  20713. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  20714. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  20715. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  20716. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20717. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  20718. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  20719. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  20720. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  20721. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  20722. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20723. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  20724. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  20725. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  20726. if (metrics.compensateDistortion) {
  20727. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  20728. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  20729. }
  20730. break;
  20731. case Camera.RIG_MODE_WEBVR:
  20732. if (rigParams.vrDisplay) {
  20733. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  20734. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  20735. //Left eye
  20736. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  20737. this._rigCameras[0].setCameraRigParameter("left", true);
  20738. //leaving this for future reference
  20739. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  20740. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  20741. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  20742. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  20743. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20744. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  20745. this._rigCameras[0].parent = this;
  20746. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  20747. //Right eye
  20748. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  20749. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  20750. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  20751. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  20752. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  20753. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20754. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  20755. this._rigCameras[1].parent = this;
  20756. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  20757. if (Camera.UseAlternateWebVRRendering) {
  20758. this._rigCameras[1]._skipRendering = true;
  20759. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  20760. }
  20761. }
  20762. break;
  20763. }
  20764. this._cascadePostProcessesToRigCams();
  20765. this.update();
  20766. };
  20767. Camera.prototype._getVRProjectionMatrix = function () {
  20768. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  20769. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  20770. return this._projectionMatrix;
  20771. };
  20772. Camera.prototype._updateCameraRotationMatrix = function () {
  20773. //Here for WebVR
  20774. };
  20775. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  20776. //Here for WebVR
  20777. };
  20778. /**
  20779. * This function MUST be overwritten by the different WebVR cameras available.
  20780. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  20781. */
  20782. Camera.prototype._getWebVRProjectionMatrix = function () {
  20783. return BABYLON.Matrix.Identity();
  20784. };
  20785. /**
  20786. * This function MUST be overwritten by the different WebVR cameras available.
  20787. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  20788. */
  20789. Camera.prototype._getWebVRViewMatrix = function () {
  20790. return BABYLON.Matrix.Identity();
  20791. };
  20792. Camera.prototype.setCameraRigParameter = function (name, value) {
  20793. if (!this._cameraRigParams) {
  20794. this._cameraRigParams = {};
  20795. }
  20796. this._cameraRigParams[name] = value;
  20797. //provisionnally:
  20798. if (name === "interaxialDistance") {
  20799. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  20800. }
  20801. };
  20802. /**
  20803. * needs to be overridden by children so sub has required properties to be copied
  20804. */
  20805. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  20806. return null;
  20807. };
  20808. /**
  20809. * May need to be overridden by children
  20810. */
  20811. Camera.prototype._updateRigCameras = function () {
  20812. for (var i = 0; i < this._rigCameras.length; i++) {
  20813. this._rigCameras[i].minZ = this.minZ;
  20814. this._rigCameras[i].maxZ = this.maxZ;
  20815. this._rigCameras[i].fov = this.fov;
  20816. }
  20817. // only update viewport when ANAGLYPH
  20818. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  20819. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  20820. }
  20821. };
  20822. Camera.prototype._setupInputs = function () {
  20823. };
  20824. Camera.prototype.serialize = function () {
  20825. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  20826. // Type
  20827. serializationObject.type = this.getClassName();
  20828. // Parent
  20829. if (this.parent) {
  20830. serializationObject.parentId = this.parent.id;
  20831. }
  20832. if (this.inputs) {
  20833. this.inputs.serialize(serializationObject);
  20834. }
  20835. // Animations
  20836. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  20837. serializationObject.ranges = this.serializeAnimationRanges();
  20838. return serializationObject;
  20839. };
  20840. Camera.prototype.clone = function (name) {
  20841. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  20842. };
  20843. Camera.prototype.getDirection = function (localAxis) {
  20844. var result = BABYLON.Vector3.Zero();
  20845. this.getDirectionToRef(localAxis, result);
  20846. return result;
  20847. };
  20848. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  20849. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  20850. };
  20851. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  20852. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  20853. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  20854. switch (type) {
  20855. case "ArcRotateCamera":
  20856. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  20857. case "DeviceOrientationCamera":
  20858. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  20859. case "FollowCamera":
  20860. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  20861. case "ArcFollowCamera":
  20862. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  20863. case "GamepadCamera":
  20864. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  20865. case "TouchCamera":
  20866. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  20867. case "VirtualJoysticksCamera":
  20868. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  20869. case "WebVRFreeCamera":
  20870. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20871. case "WebVRGamepadCamera":
  20872. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20873. case "VRDeviceOrientationFreeCamera":
  20874. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20875. case "VRDeviceOrientationGamepadCamera":
  20876. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  20877. case "AnaglyphArcRotateCamera":
  20878. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20879. case "AnaglyphFreeCamera":
  20880. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20881. case "AnaglyphGamepadCamera":
  20882. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20883. case "AnaglyphUniversalCamera":
  20884. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20885. case "StereoscopicArcRotateCamera":
  20886. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20887. case "StereoscopicFreeCamera":
  20888. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20889. case "StereoscopicGamepadCamera":
  20890. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20891. case "StereoscopicUniversalCamera":
  20892. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20893. case "FreeCamera":// Forcing Universal here
  20894. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20895. default:// Universal Camera is the default value
  20896. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20897. }
  20898. };
  20899. Camera.prototype.computeWorldMatrix = function () {
  20900. return this.getWorldMatrix();
  20901. };
  20902. Camera.Parse = function (parsedCamera, scene) {
  20903. var type = parsedCamera.type;
  20904. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  20905. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  20906. // Parent
  20907. if (parsedCamera.parentId) {
  20908. camera._waitingParentId = parsedCamera.parentId;
  20909. }
  20910. //If camera has an input manager, let it parse inputs settings
  20911. if (camera.inputs) {
  20912. camera.inputs.parse(parsedCamera);
  20913. camera._setupInputs();
  20914. }
  20915. if (camera.setPosition) {
  20916. camera.position.copyFromFloats(0, 0, 0);
  20917. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  20918. }
  20919. // Target
  20920. if (parsedCamera.target) {
  20921. if (camera.setTarget) {
  20922. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  20923. }
  20924. }
  20925. // Apply 3d rig, when found
  20926. if (parsedCamera.cameraRigMode) {
  20927. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  20928. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  20929. }
  20930. // Animations
  20931. if (parsedCamera.animations) {
  20932. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  20933. var parsedAnimation = parsedCamera.animations[animationIndex];
  20934. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20935. }
  20936. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  20937. }
  20938. if (parsedCamera.autoAnimate) {
  20939. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  20940. }
  20941. return camera;
  20942. };
  20943. // Statics
  20944. Camera._PERSPECTIVE_CAMERA = 0;
  20945. Camera._ORTHOGRAPHIC_CAMERA = 1;
  20946. Camera._FOVMODE_VERTICAL_FIXED = 0;
  20947. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  20948. Camera._RIG_MODE_NONE = 0;
  20949. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  20950. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  20951. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  20952. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  20953. Camera._RIG_MODE_VR = 20;
  20954. Camera._RIG_MODE_WEBVR = 21;
  20955. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  20956. Camera.UseAlternateWebVRRendering = false;
  20957. __decorate([
  20958. BABYLON.serializeAsVector3()
  20959. ], Camera.prototype, "position", void 0);
  20960. __decorate([
  20961. BABYLON.serializeAsVector3()
  20962. ], Camera.prototype, "upVector", void 0);
  20963. __decorate([
  20964. BABYLON.serialize()
  20965. ], Camera.prototype, "orthoLeft", void 0);
  20966. __decorate([
  20967. BABYLON.serialize()
  20968. ], Camera.prototype, "orthoRight", void 0);
  20969. __decorate([
  20970. BABYLON.serialize()
  20971. ], Camera.prototype, "orthoBottom", void 0);
  20972. __decorate([
  20973. BABYLON.serialize()
  20974. ], Camera.prototype, "orthoTop", void 0);
  20975. __decorate([
  20976. BABYLON.serialize()
  20977. ], Camera.prototype, "fov", void 0);
  20978. __decorate([
  20979. BABYLON.serialize()
  20980. ], Camera.prototype, "minZ", void 0);
  20981. __decorate([
  20982. BABYLON.serialize()
  20983. ], Camera.prototype, "maxZ", void 0);
  20984. __decorate([
  20985. BABYLON.serialize()
  20986. ], Camera.prototype, "inertia", void 0);
  20987. __decorate([
  20988. BABYLON.serialize()
  20989. ], Camera.prototype, "mode", void 0);
  20990. __decorate([
  20991. BABYLON.serialize()
  20992. ], Camera.prototype, "layerMask", void 0);
  20993. __decorate([
  20994. BABYLON.serialize()
  20995. ], Camera.prototype, "fovMode", void 0);
  20996. __decorate([
  20997. BABYLON.serialize()
  20998. ], Camera.prototype, "cameraRigMode", void 0);
  20999. __decorate([
  21000. BABYLON.serialize()
  21001. ], Camera.prototype, "interaxialDistance", void 0);
  21002. __decorate([
  21003. BABYLON.serialize()
  21004. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  21005. return Camera;
  21006. }(BABYLON.Node));
  21007. BABYLON.Camera = Camera;
  21008. })(BABYLON || (BABYLON = {}));
  21009. //# sourceMappingURL=babylon.camera.js.map
  21010. "use strict";
  21011. var BABYLON;
  21012. (function (BABYLON) {
  21013. var RenderingManager = /** @class */ (function () {
  21014. function RenderingManager(scene) {
  21015. this._renderingGroups = new Array();
  21016. this._autoClearDepthStencil = {};
  21017. this._customOpaqueSortCompareFn = {};
  21018. this._customAlphaTestSortCompareFn = {};
  21019. this._customTransparentSortCompareFn = {};
  21020. this._renderinGroupInfo = null;
  21021. this._scene = scene;
  21022. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  21023. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  21024. }
  21025. }
  21026. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  21027. if (depth === void 0) { depth = true; }
  21028. if (stencil === void 0) { stencil = true; }
  21029. if (this._depthStencilBufferAlreadyCleaned) {
  21030. return;
  21031. }
  21032. this._scene.getEngine().clear(null, false, depth, stencil);
  21033. this._depthStencilBufferAlreadyCleaned = true;
  21034. };
  21035. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  21036. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  21037. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  21038. var info = null;
  21039. if (observable) {
  21040. if (!this._renderinGroupInfo) {
  21041. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  21042. }
  21043. info = this._renderinGroupInfo;
  21044. info.scene = this._scene;
  21045. info.camera = this._scene.activeCamera;
  21046. }
  21047. // Dispatch sprites
  21048. if (renderSprites) {
  21049. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  21050. var manager = this._scene.spriteManagers[index];
  21051. this.dispatchSprites(manager);
  21052. }
  21053. }
  21054. // Render
  21055. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  21056. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  21057. var renderingGroup = this._renderingGroups[index];
  21058. if (!renderingGroup && !observable)
  21059. continue;
  21060. var renderingGroupMask = 0;
  21061. // Fire PRECLEAR stage
  21062. if (observable && info) {
  21063. renderingGroupMask = Math.pow(2, index);
  21064. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  21065. info.renderingGroupId = index;
  21066. observable.notifyObservers(info, renderingGroupMask);
  21067. }
  21068. // Clear depth/stencil if needed
  21069. if (RenderingManager.AUTOCLEAR) {
  21070. var autoClear = this._autoClearDepthStencil[index];
  21071. if (autoClear && autoClear.autoClear) {
  21072. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  21073. }
  21074. }
  21075. if (observable && info) {
  21076. // Fire PREOPAQUE stage
  21077. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  21078. observable.notifyObservers(info, renderingGroupMask);
  21079. // Fire PRETRANSPARENT stage
  21080. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  21081. observable.notifyObservers(info, renderingGroupMask);
  21082. }
  21083. if (renderingGroup)
  21084. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  21085. // Fire POSTTRANSPARENT stage
  21086. if (observable && info) {
  21087. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  21088. observable.notifyObservers(info, renderingGroupMask);
  21089. }
  21090. }
  21091. };
  21092. RenderingManager.prototype.reset = function () {
  21093. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  21094. var renderingGroup = this._renderingGroups[index];
  21095. if (renderingGroup) {
  21096. renderingGroup.prepare();
  21097. }
  21098. }
  21099. };
  21100. RenderingManager.prototype.dispose = function () {
  21101. this.freeRenderingGroups();
  21102. this._renderingGroups.length = 0;
  21103. };
  21104. /**
  21105. * Clear the info related to rendering groups preventing retention points during dispose.
  21106. */
  21107. RenderingManager.prototype.freeRenderingGroups = function () {
  21108. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  21109. var renderingGroup = this._renderingGroups[index];
  21110. if (renderingGroup) {
  21111. renderingGroup.dispose();
  21112. }
  21113. }
  21114. };
  21115. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  21116. if (this._renderingGroups[renderingGroupId] === undefined) {
  21117. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  21118. }
  21119. };
  21120. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  21121. var renderingGroupId = spriteManager.renderingGroupId || 0;
  21122. this._prepareRenderingGroup(renderingGroupId);
  21123. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  21124. };
  21125. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  21126. var renderingGroupId = particleSystem.renderingGroupId || 0;
  21127. this._prepareRenderingGroup(renderingGroupId);
  21128. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  21129. };
  21130. /**
  21131. * @param subMesh The submesh to dispatch
  21132. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  21133. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  21134. */
  21135. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  21136. if (mesh === undefined) {
  21137. mesh = subMesh.getMesh();
  21138. }
  21139. var renderingGroupId = mesh.renderingGroupId || 0;
  21140. this._prepareRenderingGroup(renderingGroupId);
  21141. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  21142. };
  21143. /**
  21144. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  21145. * This allowed control for front to back rendering or reversly depending of the special needs.
  21146. *
  21147. * @param renderingGroupId The rendering group id corresponding to its index
  21148. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  21149. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  21150. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  21151. */
  21152. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  21153. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  21154. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  21155. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  21156. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  21157. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  21158. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  21159. if (this._renderingGroups[renderingGroupId]) {
  21160. var group = this._renderingGroups[renderingGroupId];
  21161. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  21162. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  21163. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  21164. }
  21165. };
  21166. /**
  21167. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  21168. *
  21169. * @param renderingGroupId The rendering group id corresponding to its index
  21170. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  21171. * @param depth Automatically clears depth between groups if true and autoClear is true.
  21172. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  21173. */
  21174. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  21175. if (depth === void 0) { depth = true; }
  21176. if (stencil === void 0) { stencil = true; }
  21177. this._autoClearDepthStencil[renderingGroupId] = {
  21178. autoClear: autoClearDepthStencil,
  21179. depth: depth,
  21180. stencil: stencil
  21181. };
  21182. };
  21183. /**
  21184. * The max id used for rendering groups (not included)
  21185. */
  21186. RenderingManager.MAX_RENDERINGGROUPS = 4;
  21187. /**
  21188. * The min id used for rendering groups (included)
  21189. */
  21190. RenderingManager.MIN_RENDERINGGROUPS = 0;
  21191. /**
  21192. * Used to globally prevent autoclearing scenes.
  21193. */
  21194. RenderingManager.AUTOCLEAR = true;
  21195. return RenderingManager;
  21196. }());
  21197. BABYLON.RenderingManager = RenderingManager;
  21198. })(BABYLON || (BABYLON = {}));
  21199. //# sourceMappingURL=babylon.renderingManager.js.map
  21200. "use strict";
  21201. var BABYLON;
  21202. (function (BABYLON) {
  21203. var RenderingGroup = /** @class */ (function () {
  21204. /**
  21205. * Creates a new rendering group.
  21206. * @param index The rendering group index
  21207. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  21208. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  21209. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  21210. */
  21211. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  21212. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  21213. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  21214. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  21215. this.index = index;
  21216. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  21217. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  21218. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  21219. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  21220. this._particleSystems = new BABYLON.SmartArray(256);
  21221. this._spriteManagers = new BABYLON.SmartArray(256);
  21222. this._edgesRenderers = new BABYLON.SmartArray(16);
  21223. this._scene = scene;
  21224. this.opaqueSortCompareFn = opaqueSortCompareFn;
  21225. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  21226. this.transparentSortCompareFn = transparentSortCompareFn;
  21227. }
  21228. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  21229. /**
  21230. * Set the opaque sort comparison function.
  21231. * If null the sub meshes will be render in the order they were created
  21232. */
  21233. set: function (value) {
  21234. this._opaqueSortCompareFn = value;
  21235. if (value) {
  21236. this._renderOpaque = this.renderOpaqueSorted;
  21237. }
  21238. else {
  21239. this._renderOpaque = RenderingGroup.renderUnsorted;
  21240. }
  21241. },
  21242. enumerable: true,
  21243. configurable: true
  21244. });
  21245. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  21246. /**
  21247. * Set the alpha test sort comparison function.
  21248. * If null the sub meshes will be render in the order they were created
  21249. */
  21250. set: function (value) {
  21251. this._alphaTestSortCompareFn = value;
  21252. if (value) {
  21253. this._renderAlphaTest = this.renderAlphaTestSorted;
  21254. }
  21255. else {
  21256. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  21257. }
  21258. },
  21259. enumerable: true,
  21260. configurable: true
  21261. });
  21262. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  21263. /**
  21264. * Set the transparent sort comparison function.
  21265. * If null the sub meshes will be render in the order they were created
  21266. */
  21267. set: function (value) {
  21268. if (value) {
  21269. this._transparentSortCompareFn = value;
  21270. }
  21271. else {
  21272. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  21273. }
  21274. this._renderTransparent = this.renderTransparentSorted;
  21275. },
  21276. enumerable: true,
  21277. configurable: true
  21278. });
  21279. /**
  21280. * Render all the sub meshes contained in the group.
  21281. * @param customRenderFunction Used to override the default render behaviour of the group.
  21282. * @returns true if rendered some submeshes.
  21283. */
  21284. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  21285. if (customRenderFunction) {
  21286. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  21287. return;
  21288. }
  21289. var engine = this._scene.getEngine();
  21290. // Depth only
  21291. if (this._depthOnlySubMeshes.length !== 0) {
  21292. engine.setColorWrite(false);
  21293. this._renderAlphaTest(this._depthOnlySubMeshes);
  21294. engine.setColorWrite(true);
  21295. }
  21296. // Opaque
  21297. if (this._opaqueSubMeshes.length !== 0) {
  21298. this._renderOpaque(this._opaqueSubMeshes);
  21299. }
  21300. // Alpha test
  21301. if (this._alphaTestSubMeshes.length !== 0) {
  21302. this._renderAlphaTest(this._alphaTestSubMeshes);
  21303. }
  21304. var stencilState = engine.getStencilBuffer();
  21305. engine.setStencilBuffer(false);
  21306. // Sprites
  21307. if (renderSprites) {
  21308. this._renderSprites();
  21309. }
  21310. // Particles
  21311. if (renderParticles) {
  21312. this._renderParticles(activeMeshes);
  21313. }
  21314. if (this.onBeforeTransparentRendering) {
  21315. this.onBeforeTransparentRendering();
  21316. }
  21317. // Transparent
  21318. if (this._transparentSubMeshes.length !== 0) {
  21319. this._renderTransparent(this._transparentSubMeshes);
  21320. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21321. }
  21322. // Set back stencil to false in case it changes before the edge renderer.
  21323. engine.setStencilBuffer(false);
  21324. // Edges
  21325. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  21326. this._edgesRenderers.data[edgesRendererIndex].render();
  21327. }
  21328. // Restore Stencil state.
  21329. engine.setStencilBuffer(stencilState);
  21330. };
  21331. /**
  21332. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  21333. * @param subMeshes The submeshes to render
  21334. */
  21335. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  21336. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  21337. };
  21338. /**
  21339. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  21340. * @param subMeshes The submeshes to render
  21341. */
  21342. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  21343. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  21344. };
  21345. /**
  21346. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  21347. * @param subMeshes The submeshes to render
  21348. */
  21349. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  21350. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  21351. };
  21352. /**
  21353. * Renders the submeshes in a specified order.
  21354. * @param subMeshes The submeshes to sort before render
  21355. * @param sortCompareFn The comparison function use to sort
  21356. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  21357. * @param transparent Specifies to activate blending if true
  21358. */
  21359. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  21360. var subIndex = 0;
  21361. var subMesh;
  21362. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  21363. for (; subIndex < subMeshes.length; subIndex++) {
  21364. subMesh = subMeshes.data[subIndex];
  21365. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  21366. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  21367. }
  21368. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  21369. if (sortCompareFn) {
  21370. sortedArray.sort(sortCompareFn);
  21371. }
  21372. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  21373. subMesh = sortedArray[subIndex];
  21374. if (transparent) {
  21375. var material = subMesh.getMaterial();
  21376. if (material && material.needDepthPrePass) {
  21377. var engine = material.getScene().getEngine();
  21378. engine.setColorWrite(false);
  21379. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21380. subMesh.render(false);
  21381. engine.setColorWrite(true);
  21382. }
  21383. }
  21384. subMesh.render(transparent);
  21385. }
  21386. };
  21387. /**
  21388. * Renders the submeshes in the order they were dispatched (no sort applied).
  21389. * @param subMeshes The submeshes to render
  21390. */
  21391. RenderingGroup.renderUnsorted = function (subMeshes) {
  21392. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  21393. var submesh = subMeshes.data[subIndex];
  21394. submesh.render(false);
  21395. }
  21396. };
  21397. /**
  21398. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21399. * are rendered back to front if in the same alpha index.
  21400. *
  21401. * @param a The first submesh
  21402. * @param b The second submesh
  21403. * @returns The result of the comparison
  21404. */
  21405. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  21406. // Alpha index first
  21407. if (a._alphaIndex > b._alphaIndex) {
  21408. return 1;
  21409. }
  21410. if (a._alphaIndex < b._alphaIndex) {
  21411. return -1;
  21412. }
  21413. // Then distance to camera
  21414. return RenderingGroup.backToFrontSortCompare(a, b);
  21415. };
  21416. /**
  21417. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21418. * are rendered back to front.
  21419. *
  21420. * @param a The first submesh
  21421. * @param b The second submesh
  21422. * @returns The result of the comparison
  21423. */
  21424. RenderingGroup.backToFrontSortCompare = function (a, b) {
  21425. // Then distance to camera
  21426. if (a._distanceToCamera < b._distanceToCamera) {
  21427. return 1;
  21428. }
  21429. if (a._distanceToCamera > b._distanceToCamera) {
  21430. return -1;
  21431. }
  21432. return 0;
  21433. };
  21434. /**
  21435. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21436. * are rendered front to back (prevent overdraw).
  21437. *
  21438. * @param a The first submesh
  21439. * @param b The second submesh
  21440. * @returns The result of the comparison
  21441. */
  21442. RenderingGroup.frontToBackSortCompare = function (a, b) {
  21443. // Then distance to camera
  21444. if (a._distanceToCamera < b._distanceToCamera) {
  21445. return -1;
  21446. }
  21447. if (a._distanceToCamera > b._distanceToCamera) {
  21448. return 1;
  21449. }
  21450. return 0;
  21451. };
  21452. /**
  21453. * Resets the different lists of submeshes to prepare a new frame.
  21454. */
  21455. RenderingGroup.prototype.prepare = function () {
  21456. this._opaqueSubMeshes.reset();
  21457. this._transparentSubMeshes.reset();
  21458. this._alphaTestSubMeshes.reset();
  21459. this._depthOnlySubMeshes.reset();
  21460. this._particleSystems.reset();
  21461. this._spriteManagers.reset();
  21462. this._edgesRenderers.reset();
  21463. };
  21464. RenderingGroup.prototype.dispose = function () {
  21465. this._opaqueSubMeshes.dispose();
  21466. this._transparentSubMeshes.dispose();
  21467. this._alphaTestSubMeshes.dispose();
  21468. this._depthOnlySubMeshes.dispose();
  21469. this._particleSystems.dispose();
  21470. this._spriteManagers.dispose();
  21471. this._edgesRenderers.dispose();
  21472. };
  21473. /**
  21474. * Inserts the submesh in its correct queue depending on its material.
  21475. * @param subMesh The submesh to dispatch
  21476. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  21477. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  21478. */
  21479. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  21480. // Get mesh and materials if not provided
  21481. if (mesh === undefined) {
  21482. mesh = subMesh.getMesh();
  21483. }
  21484. if (material === undefined) {
  21485. material = subMesh.getMaterial();
  21486. }
  21487. if (material === null || material === undefined) {
  21488. return;
  21489. }
  21490. if (material.needAlphaBlendingForMesh(mesh)) {
  21491. this._transparentSubMeshes.push(subMesh);
  21492. }
  21493. else if (material.needAlphaTesting()) {
  21494. if (material.needDepthPrePass) {
  21495. this._depthOnlySubMeshes.push(subMesh);
  21496. }
  21497. this._alphaTestSubMeshes.push(subMesh);
  21498. }
  21499. else {
  21500. if (material.needDepthPrePass) {
  21501. this._depthOnlySubMeshes.push(subMesh);
  21502. }
  21503. this._opaqueSubMeshes.push(subMesh); // Opaque
  21504. }
  21505. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  21506. this._edgesRenderers.push(mesh._edgesRenderer);
  21507. }
  21508. };
  21509. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  21510. this._spriteManagers.push(spriteManager);
  21511. };
  21512. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  21513. this._particleSystems.push(particleSystem);
  21514. };
  21515. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  21516. if (this._particleSystems.length === 0) {
  21517. return;
  21518. }
  21519. // Particles
  21520. var activeCamera = this._scene.activeCamera;
  21521. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  21522. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  21523. var particleSystem = this._particleSystems.data[particleIndex];
  21524. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  21525. continue;
  21526. }
  21527. var emitter = particleSystem.emitter;
  21528. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  21529. this._scene._activeParticles.addCount(particleSystem.render(), false);
  21530. }
  21531. }
  21532. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  21533. };
  21534. RenderingGroup.prototype._renderSprites = function () {
  21535. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  21536. return;
  21537. }
  21538. // Sprites
  21539. var activeCamera = this._scene.activeCamera;
  21540. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  21541. for (var id = 0; id < this._spriteManagers.length; id++) {
  21542. var spriteManager = this._spriteManagers.data[id];
  21543. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  21544. spriteManager.render();
  21545. }
  21546. }
  21547. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  21548. };
  21549. return RenderingGroup;
  21550. }());
  21551. BABYLON.RenderingGroup = RenderingGroup;
  21552. })(BABYLON || (BABYLON = {}));
  21553. //# sourceMappingURL=babylon.renderingGroup.js.map
  21554. "use strict";
  21555. var BABYLON;
  21556. (function (BABYLON) {
  21557. var ClickInfo = /** @class */ (function () {
  21558. function ClickInfo() {
  21559. this._singleClick = false;
  21560. this._doubleClick = false;
  21561. this._hasSwiped = false;
  21562. this._ignore = false;
  21563. }
  21564. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  21565. get: function () {
  21566. return this._singleClick;
  21567. },
  21568. set: function (b) {
  21569. this._singleClick = b;
  21570. },
  21571. enumerable: true,
  21572. configurable: true
  21573. });
  21574. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  21575. get: function () {
  21576. return this._doubleClick;
  21577. },
  21578. set: function (b) {
  21579. this._doubleClick = b;
  21580. },
  21581. enumerable: true,
  21582. configurable: true
  21583. });
  21584. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  21585. get: function () {
  21586. return this._hasSwiped;
  21587. },
  21588. set: function (b) {
  21589. this._hasSwiped = b;
  21590. },
  21591. enumerable: true,
  21592. configurable: true
  21593. });
  21594. Object.defineProperty(ClickInfo.prototype, "ignore", {
  21595. get: function () {
  21596. return this._ignore;
  21597. },
  21598. set: function (b) {
  21599. this._ignore = b;
  21600. },
  21601. enumerable: true,
  21602. configurable: true
  21603. });
  21604. return ClickInfo;
  21605. }());
  21606. /**
  21607. * This class is used by the onRenderingGroupObservable
  21608. */
  21609. var RenderingGroupInfo = /** @class */ (function () {
  21610. function RenderingGroupInfo() {
  21611. }
  21612. /**
  21613. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  21614. * This stage will be fired no matter what
  21615. */
  21616. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  21617. /**
  21618. * Called before opaque object are rendered.
  21619. * This stage will be fired only if there's 3D Opaque content to render
  21620. */
  21621. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  21622. /**
  21623. * Called after the opaque objects are rendered and before the transparent ones
  21624. * This stage will be fired only if there's 3D transparent content to render
  21625. */
  21626. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  21627. /**
  21628. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  21629. * This stage will be fired no matter what
  21630. */
  21631. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  21632. return RenderingGroupInfo;
  21633. }());
  21634. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  21635. /**
  21636. * Represents a scene to be rendered by the engine.
  21637. * @see http://doc.babylonjs.com/page.php?p=21911
  21638. */
  21639. var Scene = /** @class */ (function () {
  21640. /**
  21641. * @constructor
  21642. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  21643. */
  21644. function Scene(engine) {
  21645. // Members
  21646. this.autoClear = true;
  21647. this.autoClearDepthAndStencil = true;
  21648. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  21649. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  21650. this._forceWireframe = false;
  21651. this._forcePointsCloud = false;
  21652. this.forceShowBoundingBoxes = false;
  21653. this.animationsEnabled = true;
  21654. this.useConstantAnimationDeltaTime = false;
  21655. this.constantlyUpdateMeshUnderPointer = false;
  21656. this.hoverCursor = "pointer";
  21657. this.defaultCursor = "";
  21658. /**
  21659. * This is used to call preventDefault() on pointer down
  21660. * in order to block unwanted artifacts like system double clicks
  21661. */
  21662. this.preventDefaultOnPointerDown = true;
  21663. // Metadata
  21664. this.metadata = null;
  21665. /**
  21666. * An event triggered when the scene is disposed.
  21667. * @type {BABYLON.Observable}
  21668. */
  21669. this.onDisposeObservable = new BABYLON.Observable();
  21670. this._onDisposeObserver = null;
  21671. /**
  21672. * An event triggered before rendering the scene (right after animations and physics)
  21673. * @type {BABYLON.Observable}
  21674. */
  21675. this.onBeforeRenderObservable = new BABYLON.Observable();
  21676. this._onBeforeRenderObserver = null;
  21677. /**
  21678. * An event triggered after rendering the scene
  21679. * @type {BABYLON.Observable}
  21680. */
  21681. this.onAfterRenderObservable = new BABYLON.Observable();
  21682. this._onAfterRenderObserver = null;
  21683. /**
  21684. * An event triggered before animating the scene
  21685. * @type {BABYLON.Observable}
  21686. */
  21687. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  21688. /**
  21689. * An event triggered after animations processing
  21690. * @type {BABYLON.Observable}
  21691. */
  21692. this.onAfterAnimationsObservable = new BABYLON.Observable();
  21693. /**
  21694. * An event triggered before draw calls are ready to be sent
  21695. * @type {BABYLON.Observable}
  21696. */
  21697. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  21698. /**
  21699. * An event triggered after draw calls have been sent
  21700. * @type {BABYLON.Observable}
  21701. */
  21702. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  21703. /**
  21704. * An event triggered when physic simulation is about to be run
  21705. * @type {BABYLON.Observable}
  21706. */
  21707. this.onBeforePhysicsObservable = new BABYLON.Observable();
  21708. /**
  21709. * An event triggered when physic simulation has been done
  21710. * @type {BABYLON.Observable}
  21711. */
  21712. this.onAfterPhysicsObservable = new BABYLON.Observable();
  21713. /**
  21714. * An event triggered when the scene is ready
  21715. * @type {BABYLON.Observable}
  21716. */
  21717. this.onReadyObservable = new BABYLON.Observable();
  21718. /**
  21719. * An event triggered before rendering a camera
  21720. * @type {BABYLON.Observable}
  21721. */
  21722. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  21723. this._onBeforeCameraRenderObserver = null;
  21724. /**
  21725. * An event triggered after rendering a camera
  21726. * @type {BABYLON.Observable}
  21727. */
  21728. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  21729. this._onAfterCameraRenderObserver = null;
  21730. /**
  21731. * An event triggered when active meshes evaluation is about to start
  21732. * @type {BABYLON.Observable}
  21733. */
  21734. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  21735. /**
  21736. * An event triggered when active meshes evaluation is done
  21737. * @type {BABYLON.Observable}
  21738. */
  21739. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  21740. /**
  21741. * An event triggered when particles rendering is about to start
  21742. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  21743. * @type {BABYLON.Observable}
  21744. */
  21745. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  21746. /**
  21747. * An event triggered when particles rendering is done
  21748. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  21749. * @type {BABYLON.Observable}
  21750. */
  21751. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  21752. /**
  21753. * An event triggered when sprites rendering is about to start
  21754. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  21755. * @type {BABYLON.Observable}
  21756. */
  21757. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  21758. /**
  21759. * An event triggered when sprites rendering is done
  21760. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  21761. * @type {BABYLON.Observable}
  21762. */
  21763. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  21764. /**
  21765. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  21766. * @type {BABYLON.Observable}
  21767. */
  21768. this.onDataLoadedObservable = new BABYLON.Observable();
  21769. /**
  21770. * An event triggered when a camera is created
  21771. * @type {BABYLON.Observable}
  21772. */
  21773. this.onNewCameraAddedObservable = new BABYLON.Observable();
  21774. /**
  21775. * An event triggered when a camera is removed
  21776. * @type {BABYLON.Observable}
  21777. */
  21778. this.onCameraRemovedObservable = new BABYLON.Observable();
  21779. /**
  21780. * An event triggered when a light is created
  21781. * @type {BABYLON.Observable}
  21782. */
  21783. this.onNewLightAddedObservable = new BABYLON.Observable();
  21784. /**
  21785. * An event triggered when a light is removed
  21786. * @type {BABYLON.Observable}
  21787. */
  21788. this.onLightRemovedObservable = new BABYLON.Observable();
  21789. /**
  21790. * An event triggered when a geometry is created
  21791. * @type {BABYLON.Observable}
  21792. */
  21793. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  21794. /**
  21795. * An event triggered when a geometry is removed
  21796. * @type {BABYLON.Observable}
  21797. */
  21798. this.onGeometryRemovedObservable = new BABYLON.Observable();
  21799. /**
  21800. * An event triggered when a transform node is created
  21801. * @type {BABYLON.Observable}
  21802. */
  21803. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  21804. /**
  21805. * An event triggered when a transform node is removed
  21806. * @type {BABYLON.Observable}
  21807. */
  21808. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  21809. /**
  21810. * An event triggered when a mesh is created
  21811. * @type {BABYLON.Observable}
  21812. */
  21813. this.onNewMeshAddedObservable = new BABYLON.Observable();
  21814. /**
  21815. * An event triggered when a mesh is removed
  21816. * @type {BABYLON.Observable}
  21817. */
  21818. this.onMeshRemovedObservable = new BABYLON.Observable();
  21819. /**
  21820. * An event triggered when render targets are about to be rendered
  21821. * Can happen multiple times per frame.
  21822. * @type {BABYLON.Observable}
  21823. */
  21824. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  21825. /**
  21826. * An event triggered when render targets were rendered.
  21827. * Can happen multiple times per frame.
  21828. * @type {BABYLON.Observable}
  21829. */
  21830. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  21831. /**
  21832. * An event triggered before calculating deterministic simulation step
  21833. * @type {BABYLON.Observable}
  21834. */
  21835. this.onBeforeStepObservable = new BABYLON.Observable();
  21836. /**
  21837. * An event triggered after calculating deterministic simulation step
  21838. * @type {BABYLON.Observable}
  21839. */
  21840. this.onAfterStepObservable = new BABYLON.Observable();
  21841. /**
  21842. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  21843. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  21844. * 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)
  21845. */
  21846. this.onRenderingGroupObservable = new BABYLON.Observable();
  21847. // Animations
  21848. this.animations = [];
  21849. this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  21850. /**
  21851. * 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).
  21852. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  21853. */
  21854. this.onPrePointerObservable = new BABYLON.Observable();
  21855. /**
  21856. * Observable event triggered each time an input event is received from the rendering canvas
  21857. */
  21858. this.onPointerObservable = new BABYLON.Observable();
  21859. this._meshPickProceed = false;
  21860. this._currentPickResult = null;
  21861. this._previousPickResult = null;
  21862. this._totalPointersPressed = 0;
  21863. this._doubleClickOccured = false;
  21864. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  21865. this.cameraToUseForPointers = null;
  21866. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  21867. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  21868. this._startingPointerTime = 0;
  21869. this._previousStartingPointerTime = 0;
  21870. // Deterministic lockstep
  21871. this._timeAccumulator = 0;
  21872. this._currentStepId = 0;
  21873. this._currentInternalStep = 0;
  21874. // Keyboard
  21875. /**
  21876. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  21877. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  21878. */
  21879. this.onPreKeyboardObservable = new BABYLON.Observable();
  21880. /**
  21881. * Observable event triggered each time an keyboard event is received from the hosting window
  21882. */
  21883. this.onKeyboardObservable = new BABYLON.Observable();
  21884. // Coordinate system
  21885. /**
  21886. * use right-handed coordinate system on this scene.
  21887. * @type {boolean}
  21888. */
  21889. this._useRightHandedSystem = false;
  21890. // Fog
  21891. this._fogEnabled = true;
  21892. this._fogMode = Scene.FOGMODE_NONE;
  21893. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  21894. this.fogDensity = 0.1;
  21895. this.fogStart = 0;
  21896. this.fogEnd = 1000.0;
  21897. // Lights
  21898. /**
  21899. * is shadow enabled on this scene.
  21900. * @type {boolean}
  21901. */
  21902. this._shadowsEnabled = true;
  21903. /**
  21904. * is light enabled on this scene.
  21905. * @type {boolean}
  21906. */
  21907. this._lightsEnabled = true;
  21908. /**
  21909. * All of the lights added to this scene.
  21910. * @see BABYLON.Light
  21911. * @type {BABYLON.Light[]}
  21912. */
  21913. this.lights = new Array();
  21914. // Cameras
  21915. /** All of the cameras added to this scene. */
  21916. this.cameras = new Array();
  21917. /** All of the active cameras added to this scene. */
  21918. this.activeCameras = new Array();
  21919. // Meshes
  21920. /**
  21921. * All of the tranform nodes added to this scene.
  21922. * @see BABYLON.TransformNode
  21923. * @type {BABYLON.TransformNode[]}
  21924. */
  21925. this.transformNodes = new Array();
  21926. /**
  21927. * All of the (abstract) meshes added to this scene.
  21928. * @see BABYLON.AbstractMesh
  21929. * @type {BABYLON.AbstractMesh[]}
  21930. */
  21931. this.meshes = new Array();
  21932. /**
  21933. * All of the animation groups added to this scene.
  21934. * @see BABYLON.AnimationGroup
  21935. * @type {BABYLON.AnimationGroup[]}
  21936. */
  21937. this.animationGroups = new Array();
  21938. // Geometries
  21939. this._geometries = new Array();
  21940. this.materials = new Array();
  21941. this.multiMaterials = new Array();
  21942. // Textures
  21943. this._texturesEnabled = true;
  21944. this.textures = new Array();
  21945. // Particles
  21946. this.particlesEnabled = true;
  21947. this.particleSystems = new Array();
  21948. // Sprites
  21949. this.spritesEnabled = true;
  21950. this.spriteManagers = new Array();
  21951. /**
  21952. * The list of layers (background and foreground) of the scene.
  21953. */
  21954. this.layers = new Array();
  21955. /**
  21956. * The list of effect layers (highlights/glow) contained in the scene.
  21957. */
  21958. this.effectLayers = new Array();
  21959. // Skeletons
  21960. this._skeletonsEnabled = true;
  21961. this.skeletons = new Array();
  21962. // Morph targets
  21963. this.morphTargetManagers = new Array();
  21964. // Lens flares
  21965. this.lensFlaresEnabled = true;
  21966. this.lensFlareSystems = new Array();
  21967. // Collisions
  21968. this.collisionsEnabled = true;
  21969. /** Defines the gravity applied to this scene */
  21970. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  21971. // Postprocesses
  21972. this.postProcesses = new Array();
  21973. this.postProcessesEnabled = true;
  21974. // Customs render targets
  21975. this.renderTargetsEnabled = true;
  21976. this.dumpNextRenderTargets = false;
  21977. this.customRenderTargets = new Array();
  21978. // Imported meshes
  21979. this.importedMeshesFiles = new Array();
  21980. // Probes
  21981. this.probesEnabled = true;
  21982. this.reflectionProbes = new Array();
  21983. this._actionManagers = new Array();
  21984. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  21985. // Procedural textures
  21986. this.proceduralTexturesEnabled = true;
  21987. this._proceduralTextures = new Array();
  21988. this.soundTracks = new Array();
  21989. this._audioEnabled = true;
  21990. this._headphone = false;
  21991. // Performance counters
  21992. this._totalVertices = new BABYLON.PerfCounter();
  21993. this._activeIndices = new BABYLON.PerfCounter();
  21994. this._activeParticles = new BABYLON.PerfCounter();
  21995. this._activeBones = new BABYLON.PerfCounter();
  21996. this._animationTime = 0;
  21997. this.animationTimeScale = 1;
  21998. this._renderId = 0;
  21999. this._executeWhenReadyTimeoutId = -1;
  22000. this._intermediateRendering = false;
  22001. this._viewUpdateFlag = -1;
  22002. this._projectionUpdateFlag = -1;
  22003. this._alternateViewUpdateFlag = -1;
  22004. this._alternateProjectionUpdateFlag = -1;
  22005. this._toBeDisposed = new BABYLON.SmartArray(256);
  22006. this._activeRequests = new Array();
  22007. this._pendingData = new Array();
  22008. this._isDisposed = false;
  22009. this.dispatchAllSubMeshesOfActiveMeshes = false;
  22010. this._activeMeshes = new BABYLON.SmartArray(256);
  22011. this._processedMaterials = new BABYLON.SmartArray(256);
  22012. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  22013. this._activeParticleSystems = new BABYLON.SmartArray(256);
  22014. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  22015. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  22016. this._activeAnimatables = new Array();
  22017. this._transformMatrix = BABYLON.Matrix.Zero();
  22018. this._useAlternateCameraConfiguration = false;
  22019. this._alternateRendering = false;
  22020. this.requireLightSorting = false;
  22021. this._depthRenderer = {};
  22022. this._activeMeshesFrozen = false;
  22023. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  22024. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  22025. this._engine.scenes.push(this);
  22026. this._uid = null;
  22027. this._renderingManager = new BABYLON.RenderingManager(this);
  22028. this.postProcessManager = new BABYLON.PostProcessManager(this);
  22029. if (BABYLON.OutlineRenderer) {
  22030. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  22031. }
  22032. if (BABYLON.Tools.IsWindowObjectExist()) {
  22033. this.attachControl();
  22034. }
  22035. //simplification queue
  22036. if (BABYLON.SimplificationQueue) {
  22037. this.simplificationQueue = new BABYLON.SimplificationQueue();
  22038. }
  22039. //collision coordinator initialization. For now legacy per default.
  22040. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  22041. // Uniform Buffer
  22042. this._createUbo();
  22043. // Default Image processing definition.
  22044. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  22045. }
  22046. Object.defineProperty(Scene, "FOGMODE_NONE", {
  22047. /** The fog is deactivated */
  22048. get: function () {
  22049. return Scene._FOGMODE_NONE;
  22050. },
  22051. enumerable: true,
  22052. configurable: true
  22053. });
  22054. Object.defineProperty(Scene, "FOGMODE_EXP", {
  22055. /** The fog density is following an exponential function */
  22056. get: function () {
  22057. return Scene._FOGMODE_EXP;
  22058. },
  22059. enumerable: true,
  22060. configurable: true
  22061. });
  22062. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  22063. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  22064. get: function () {
  22065. return Scene._FOGMODE_EXP2;
  22066. },
  22067. enumerable: true,
  22068. configurable: true
  22069. });
  22070. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  22071. /** The fog density is following a linear function. */
  22072. get: function () {
  22073. return Scene._FOGMODE_LINEAR;
  22074. },
  22075. enumerable: true,
  22076. configurable: true
  22077. });
  22078. Object.defineProperty(Scene.prototype, "environmentTexture", {
  22079. /**
  22080. * Texture used in all pbr material as the reflection texture.
  22081. * As in the majority of the scene they are the same (exception for multi room and so on),
  22082. * this is easier to reference from here than from all the materials.
  22083. */
  22084. get: function () {
  22085. return this._environmentTexture;
  22086. },
  22087. /**
  22088. * Texture used in all pbr material as the reflection texture.
  22089. * As in the majority of the scene they are the same (exception for multi room and so on),
  22090. * this is easier to set here than in all the materials.
  22091. */
  22092. set: function (value) {
  22093. if (this._environmentTexture === value) {
  22094. return;
  22095. }
  22096. this._environmentTexture = value;
  22097. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  22098. },
  22099. enumerable: true,
  22100. configurable: true
  22101. });
  22102. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  22103. /**
  22104. * Default image processing configuration used either in the rendering
  22105. * Forward main pass or through the imageProcessingPostProcess if present.
  22106. * As in the majority of the scene they are the same (exception for multi camera),
  22107. * this is easier to reference from here than from all the materials and post process.
  22108. *
  22109. * No setter as we it is a shared configuration, you can set the values instead.
  22110. */
  22111. get: function () {
  22112. return this._imageProcessingConfiguration;
  22113. },
  22114. enumerable: true,
  22115. configurable: true
  22116. });
  22117. Object.defineProperty(Scene.prototype, "forceWireframe", {
  22118. get: function () {
  22119. return this._forceWireframe;
  22120. },
  22121. set: function (value) {
  22122. if (this._forceWireframe === value) {
  22123. return;
  22124. }
  22125. this._forceWireframe = value;
  22126. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22127. },
  22128. enumerable: true,
  22129. configurable: true
  22130. });
  22131. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  22132. get: function () {
  22133. return this._forcePointsCloud;
  22134. },
  22135. set: function (value) {
  22136. if (this._forcePointsCloud === value) {
  22137. return;
  22138. }
  22139. this._forcePointsCloud = value;
  22140. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22141. },
  22142. enumerable: true,
  22143. configurable: true
  22144. });
  22145. Object.defineProperty(Scene.prototype, "onDispose", {
  22146. /** A function to be executed when this scene is disposed. */
  22147. set: function (callback) {
  22148. if (this._onDisposeObserver) {
  22149. this.onDisposeObservable.remove(this._onDisposeObserver);
  22150. }
  22151. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  22152. },
  22153. enumerable: true,
  22154. configurable: true
  22155. });
  22156. Object.defineProperty(Scene.prototype, "beforeRender", {
  22157. /** A function to be executed before rendering this scene */
  22158. set: function (callback) {
  22159. if (this._onBeforeRenderObserver) {
  22160. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  22161. }
  22162. if (callback) {
  22163. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  22164. }
  22165. },
  22166. enumerable: true,
  22167. configurable: true
  22168. });
  22169. Object.defineProperty(Scene.prototype, "afterRender", {
  22170. /** A function to be executed after rendering this scene */
  22171. set: function (callback) {
  22172. if (this._onAfterRenderObserver) {
  22173. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  22174. }
  22175. if (callback) {
  22176. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  22177. }
  22178. },
  22179. enumerable: true,
  22180. configurable: true
  22181. });
  22182. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  22183. set: function (callback) {
  22184. if (this._onBeforeCameraRenderObserver) {
  22185. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  22186. }
  22187. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  22188. },
  22189. enumerable: true,
  22190. configurable: true
  22191. });
  22192. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  22193. set: function (callback) {
  22194. if (this._onAfterCameraRenderObserver) {
  22195. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  22196. }
  22197. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  22198. },
  22199. enumerable: true,
  22200. configurable: true
  22201. });
  22202. Object.defineProperty(Scene.prototype, "gamepadManager", {
  22203. get: function () {
  22204. if (!this._gamepadManager) {
  22205. this._gamepadManager = new BABYLON.GamepadManager(this);
  22206. }
  22207. return this._gamepadManager;
  22208. },
  22209. enumerable: true,
  22210. configurable: true
  22211. });
  22212. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  22213. get: function () {
  22214. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  22215. },
  22216. enumerable: true,
  22217. configurable: true
  22218. });
  22219. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  22220. get: function () {
  22221. return this._useRightHandedSystem;
  22222. },
  22223. set: function (value) {
  22224. if (this._useRightHandedSystem === value) {
  22225. return;
  22226. }
  22227. this._useRightHandedSystem = value;
  22228. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22229. },
  22230. enumerable: true,
  22231. configurable: true
  22232. });
  22233. Scene.prototype.setStepId = function (newStepId) {
  22234. this._currentStepId = newStepId;
  22235. };
  22236. ;
  22237. Scene.prototype.getStepId = function () {
  22238. return this._currentStepId;
  22239. };
  22240. ;
  22241. Scene.prototype.getInternalStep = function () {
  22242. return this._currentInternalStep;
  22243. };
  22244. ;
  22245. Object.defineProperty(Scene.prototype, "fogEnabled", {
  22246. get: function () {
  22247. return this._fogEnabled;
  22248. },
  22249. /**
  22250. * is fog enabled on this scene.
  22251. */
  22252. set: function (value) {
  22253. if (this._fogEnabled === value) {
  22254. return;
  22255. }
  22256. this._fogEnabled = value;
  22257. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22258. },
  22259. enumerable: true,
  22260. configurable: true
  22261. });
  22262. Object.defineProperty(Scene.prototype, "fogMode", {
  22263. get: function () {
  22264. return this._fogMode;
  22265. },
  22266. set: function (value) {
  22267. if (this._fogMode === value) {
  22268. return;
  22269. }
  22270. this._fogMode = value;
  22271. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22272. },
  22273. enumerable: true,
  22274. configurable: true
  22275. });
  22276. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  22277. get: function () {
  22278. return this._shadowsEnabled;
  22279. },
  22280. set: function (value) {
  22281. if (this._shadowsEnabled === value) {
  22282. return;
  22283. }
  22284. this._shadowsEnabled = value;
  22285. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  22286. },
  22287. enumerable: true,
  22288. configurable: true
  22289. });
  22290. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  22291. get: function () {
  22292. return this._lightsEnabled;
  22293. },
  22294. set: function (value) {
  22295. if (this._lightsEnabled === value) {
  22296. return;
  22297. }
  22298. this._lightsEnabled = value;
  22299. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  22300. },
  22301. enumerable: true,
  22302. configurable: true
  22303. });
  22304. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  22305. /** The default material used on meshes when no material is affected */
  22306. get: function () {
  22307. if (!this._defaultMaterial) {
  22308. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  22309. }
  22310. return this._defaultMaterial;
  22311. },
  22312. /** The default material used on meshes when no material is affected */
  22313. set: function (value) {
  22314. this._defaultMaterial = value;
  22315. },
  22316. enumerable: true,
  22317. configurable: true
  22318. });
  22319. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  22320. get: function () {
  22321. return this._texturesEnabled;
  22322. },
  22323. set: function (value) {
  22324. if (this._texturesEnabled === value) {
  22325. return;
  22326. }
  22327. this._texturesEnabled = value;
  22328. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  22329. },
  22330. enumerable: true,
  22331. configurable: true
  22332. });
  22333. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  22334. get: function () {
  22335. return this._skeletonsEnabled;
  22336. },
  22337. set: function (value) {
  22338. if (this._skeletonsEnabled === value) {
  22339. return;
  22340. }
  22341. this._skeletonsEnabled = value;
  22342. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  22343. },
  22344. enumerable: true,
  22345. configurable: true
  22346. });
  22347. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  22348. get: function () {
  22349. if (!this._postProcessRenderPipelineManager) {
  22350. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  22351. }
  22352. return this._postProcessRenderPipelineManager;
  22353. },
  22354. enumerable: true,
  22355. configurable: true
  22356. });
  22357. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  22358. get: function () {
  22359. if (!this._mainSoundTrack) {
  22360. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  22361. }
  22362. return this._mainSoundTrack;
  22363. },
  22364. enumerable: true,
  22365. configurable: true
  22366. });
  22367. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  22368. get: function () {
  22369. return this._alternateRendering;
  22370. },
  22371. enumerable: true,
  22372. configurable: true
  22373. });
  22374. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  22375. get: function () {
  22376. return this._frustumPlanes;
  22377. },
  22378. enumerable: true,
  22379. configurable: true
  22380. });
  22381. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  22382. /**
  22383. * Gets the current geometry buffer associated to the scene.
  22384. */
  22385. get: function () {
  22386. return this._geometryBufferRenderer;
  22387. },
  22388. /**
  22389. * Sets the current geometry buffer for the scene.
  22390. */
  22391. set: function (geometryBufferRenderer) {
  22392. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  22393. this._geometryBufferRenderer = geometryBufferRenderer;
  22394. }
  22395. },
  22396. enumerable: true,
  22397. configurable: true
  22398. });
  22399. Object.defineProperty(Scene.prototype, "debugLayer", {
  22400. // Properties
  22401. get: function () {
  22402. if (!this._debugLayer) {
  22403. this._debugLayer = new BABYLON.DebugLayer(this);
  22404. }
  22405. return this._debugLayer;
  22406. },
  22407. enumerable: true,
  22408. configurable: true
  22409. });
  22410. Object.defineProperty(Scene.prototype, "workerCollisions", {
  22411. get: function () {
  22412. return this._workerCollisions;
  22413. },
  22414. set: function (enabled) {
  22415. if (!BABYLON.CollisionCoordinatorLegacy) {
  22416. return;
  22417. }
  22418. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  22419. this._workerCollisions = enabled;
  22420. if (this.collisionCoordinator) {
  22421. this.collisionCoordinator.destroy();
  22422. }
  22423. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  22424. this.collisionCoordinator.init(this);
  22425. },
  22426. enumerable: true,
  22427. configurable: true
  22428. });
  22429. Object.defineProperty(Scene.prototype, "selectionOctree", {
  22430. get: function () {
  22431. return this._selectionOctree;
  22432. },
  22433. enumerable: true,
  22434. configurable: true
  22435. });
  22436. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  22437. /**
  22438. * The mesh that is currently under the pointer.
  22439. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  22440. */
  22441. get: function () {
  22442. return this._pointerOverMesh;
  22443. },
  22444. enumerable: true,
  22445. configurable: true
  22446. });
  22447. Object.defineProperty(Scene.prototype, "pointerX", {
  22448. /**
  22449. * Current on-screen X position of the pointer
  22450. * @return {number} X position of the pointer
  22451. */
  22452. get: function () {
  22453. return this._pointerX;
  22454. },
  22455. enumerable: true,
  22456. configurable: true
  22457. });
  22458. Object.defineProperty(Scene.prototype, "pointerY", {
  22459. /**
  22460. * Current on-screen Y position of the pointer
  22461. * @return {number} Y position of the pointer
  22462. */
  22463. get: function () {
  22464. return this._pointerY;
  22465. },
  22466. enumerable: true,
  22467. configurable: true
  22468. });
  22469. Scene.prototype.getCachedMaterial = function () {
  22470. return this._cachedMaterial;
  22471. };
  22472. Scene.prototype.getCachedEffect = function () {
  22473. return this._cachedEffect;
  22474. };
  22475. Scene.prototype.getCachedVisibility = function () {
  22476. return this._cachedVisibility;
  22477. };
  22478. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  22479. if (visibility === void 0) { visibility = 1; }
  22480. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  22481. };
  22482. Scene.prototype.getBoundingBoxRenderer = function () {
  22483. if (!this._boundingBoxRenderer) {
  22484. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  22485. }
  22486. return this._boundingBoxRenderer;
  22487. };
  22488. Scene.prototype.getOutlineRenderer = function () {
  22489. return this._outlineRenderer;
  22490. };
  22491. Scene.prototype.getEngine = function () {
  22492. return this._engine;
  22493. };
  22494. Scene.prototype.getTotalVertices = function () {
  22495. return this._totalVertices.current;
  22496. };
  22497. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  22498. get: function () {
  22499. return this._totalVertices;
  22500. },
  22501. enumerable: true,
  22502. configurable: true
  22503. });
  22504. Scene.prototype.getActiveIndices = function () {
  22505. return this._activeIndices.current;
  22506. };
  22507. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  22508. get: function () {
  22509. return this._activeIndices;
  22510. },
  22511. enumerable: true,
  22512. configurable: true
  22513. });
  22514. Scene.prototype.getActiveParticles = function () {
  22515. return this._activeParticles.current;
  22516. };
  22517. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  22518. get: function () {
  22519. return this._activeParticles;
  22520. },
  22521. enumerable: true,
  22522. configurable: true
  22523. });
  22524. Scene.prototype.getActiveBones = function () {
  22525. return this._activeBones.current;
  22526. };
  22527. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  22528. get: function () {
  22529. return this._activeBones;
  22530. },
  22531. enumerable: true,
  22532. configurable: true
  22533. });
  22534. // Stats
  22535. Scene.prototype.getInterFramePerfCounter = function () {
  22536. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22537. return 0;
  22538. };
  22539. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  22540. get: function () {
  22541. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22542. return null;
  22543. },
  22544. enumerable: true,
  22545. configurable: true
  22546. });
  22547. Scene.prototype.getLastFrameDuration = function () {
  22548. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  22549. return 0;
  22550. };
  22551. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  22552. get: function () {
  22553. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22554. return null;
  22555. },
  22556. enumerable: true,
  22557. configurable: true
  22558. });
  22559. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  22560. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  22561. return 0;
  22562. };
  22563. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  22564. get: function () {
  22565. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22566. return null;
  22567. },
  22568. enumerable: true,
  22569. configurable: true
  22570. });
  22571. Scene.prototype.getActiveMeshes = function () {
  22572. return this._activeMeshes;
  22573. };
  22574. Scene.prototype.getRenderTargetsDuration = function () {
  22575. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  22576. return 0;
  22577. };
  22578. Scene.prototype.getRenderDuration = function () {
  22579. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  22580. return 0;
  22581. };
  22582. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  22583. get: function () {
  22584. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22585. return null;
  22586. },
  22587. enumerable: true,
  22588. configurable: true
  22589. });
  22590. Scene.prototype.getParticlesDuration = function () {
  22591. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  22592. return 0;
  22593. };
  22594. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  22595. get: function () {
  22596. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22597. return null;
  22598. },
  22599. enumerable: true,
  22600. configurable: true
  22601. });
  22602. Scene.prototype.getSpritesDuration = function () {
  22603. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  22604. return 0;
  22605. };
  22606. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  22607. get: function () {
  22608. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  22609. return null;
  22610. },
  22611. enumerable: true,
  22612. configurable: true
  22613. });
  22614. Scene.prototype.getAnimationRatio = function () {
  22615. return this._animationRatio;
  22616. };
  22617. Scene.prototype.getRenderId = function () {
  22618. return this._renderId;
  22619. };
  22620. Scene.prototype.incrementRenderId = function () {
  22621. this._renderId++;
  22622. };
  22623. Scene.prototype._updatePointerPosition = function (evt) {
  22624. var canvasRect = this._engine.getRenderingCanvasClientRect();
  22625. if (!canvasRect) {
  22626. return;
  22627. }
  22628. this._pointerX = evt.clientX - canvasRect.left;
  22629. this._pointerY = evt.clientY - canvasRect.top;
  22630. this._unTranslatedPointerX = this._pointerX;
  22631. this._unTranslatedPointerY = this._pointerY;
  22632. };
  22633. Scene.prototype._createUbo = function () {
  22634. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  22635. this._sceneUbo.addUniform("viewProjection", 16);
  22636. this._sceneUbo.addUniform("view", 16);
  22637. };
  22638. Scene.prototype._createAlternateUbo = function () {
  22639. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  22640. this._alternateSceneUbo.addUniform("viewProjection", 16);
  22641. this._alternateSceneUbo.addUniform("view", 16);
  22642. };
  22643. // Pointers handling
  22644. /**
  22645. * Use this method to simulate a pointer move on a mesh
  22646. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22647. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22648. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22649. */
  22650. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  22651. var evt = new PointerEvent("pointermove", pointerEventInit);
  22652. return this._processPointerMove(pickResult, evt);
  22653. };
  22654. Scene.prototype._processPointerMove = function (pickResult, evt) {
  22655. var canvas = this._engine.getRenderingCanvas();
  22656. if (!canvas) {
  22657. return this;
  22658. }
  22659. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  22660. this.setPointerOverSprite(null);
  22661. this.setPointerOverMesh(pickResult.pickedMesh);
  22662. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  22663. if (this._pointerOverMesh.actionManager.hoverCursor) {
  22664. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  22665. }
  22666. else {
  22667. canvas.style.cursor = this.hoverCursor;
  22668. }
  22669. }
  22670. else {
  22671. canvas.style.cursor = this.defaultCursor;
  22672. }
  22673. }
  22674. else {
  22675. this.setPointerOverMesh(null);
  22676. // Sprites
  22677. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  22678. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  22679. this.setPointerOverSprite(pickResult.pickedSprite);
  22680. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  22681. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  22682. }
  22683. else {
  22684. canvas.style.cursor = this.hoverCursor;
  22685. }
  22686. }
  22687. else {
  22688. this.setPointerOverSprite(null);
  22689. // Restore pointer
  22690. canvas.style.cursor = this.defaultCursor;
  22691. }
  22692. }
  22693. if (pickResult) {
  22694. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  22695. if (this.onPointerMove) {
  22696. this.onPointerMove(evt, pickResult, type);
  22697. }
  22698. if (this.onPointerObservable.hasObservers()) {
  22699. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22700. this.onPointerObservable.notifyObservers(pi, type);
  22701. }
  22702. }
  22703. return this;
  22704. };
  22705. /**
  22706. * Use this method to simulate a pointer down on a mesh
  22707. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22708. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22709. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22710. */
  22711. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  22712. var evt = new PointerEvent("pointerdown", pointerEventInit);
  22713. return this._processPointerDown(pickResult, evt);
  22714. };
  22715. Scene.prototype._processPointerDown = function (pickResult, evt) {
  22716. var _this = this;
  22717. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  22718. this._pickedDownMesh = pickResult.pickedMesh;
  22719. var actionManager = pickResult.pickedMesh.actionManager;
  22720. if (actionManager) {
  22721. if (actionManager.hasPickTriggers) {
  22722. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22723. switch (evt.button) {
  22724. case 0:
  22725. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22726. break;
  22727. case 1:
  22728. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22729. break;
  22730. case 2:
  22731. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22732. break;
  22733. }
  22734. }
  22735. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  22736. window.setTimeout(function () {
  22737. 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);
  22738. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  22739. if (_this._totalPointersPressed !== 0 &&
  22740. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  22741. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  22742. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  22743. _this._startingPointerTime = 0;
  22744. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22745. }
  22746. }
  22747. }, Scene.LongPressDelay);
  22748. }
  22749. }
  22750. }
  22751. if (pickResult) {
  22752. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  22753. if (this.onPointerDown) {
  22754. this.onPointerDown(evt, pickResult, type);
  22755. }
  22756. if (this.onPointerObservable.hasObservers()) {
  22757. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22758. this.onPointerObservable.notifyObservers(pi, type);
  22759. }
  22760. }
  22761. return this;
  22762. };
  22763. /**
  22764. * Use this method to simulate a pointer up on a mesh
  22765. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22766. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22767. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22768. */
  22769. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  22770. var evt = new PointerEvent("pointerup", pointerEventInit);
  22771. var clickInfo = new ClickInfo();
  22772. clickInfo.singleClick = true;
  22773. clickInfo.ignore = true;
  22774. return this._processPointerUp(pickResult, evt, clickInfo);
  22775. };
  22776. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  22777. if (pickResult && pickResult && pickResult.pickedMesh) {
  22778. this._pickedUpMesh = pickResult.pickedMesh;
  22779. if (this._pickedDownMesh === this._pickedUpMesh) {
  22780. if (this.onPointerPick) {
  22781. this.onPointerPick(evt, pickResult);
  22782. }
  22783. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  22784. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  22785. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  22786. this.onPointerObservable.notifyObservers(pi, type_1);
  22787. }
  22788. }
  22789. if (pickResult.pickedMesh.actionManager) {
  22790. if (clickInfo.ignore) {
  22791. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22792. }
  22793. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  22794. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22795. }
  22796. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22797. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22798. }
  22799. }
  22800. }
  22801. if (this._pickedDownMesh &&
  22802. this._pickedDownMesh.actionManager &&
  22803. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  22804. this._pickedDownMesh !== this._pickedUpMesh) {
  22805. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  22806. }
  22807. var type = BABYLON.PointerEventTypes.POINTERUP;
  22808. if (this.onPointerObservable.hasObservers()) {
  22809. if (!clickInfo.ignore) {
  22810. if (!clickInfo.hasSwiped) {
  22811. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  22812. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  22813. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  22814. this.onPointerObservable.notifyObservers(pi, type_2);
  22815. }
  22816. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  22817. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  22818. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  22819. this.onPointerObservable.notifyObservers(pi, type_3);
  22820. }
  22821. }
  22822. }
  22823. else {
  22824. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22825. this.onPointerObservable.notifyObservers(pi, type);
  22826. }
  22827. }
  22828. if (this.onPointerUp) {
  22829. this.onPointerUp(evt, pickResult, type);
  22830. }
  22831. return this;
  22832. };
  22833. /**
  22834. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  22835. * @param attachUp defines if you want to attach events to pointerup
  22836. * @param attachDown defines if you want to attach events to pointerdown
  22837. * @param attachMove defines if you want to attach events to pointermove
  22838. */
  22839. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  22840. var _this = this;
  22841. if (attachUp === void 0) { attachUp = true; }
  22842. if (attachDown === void 0) { attachDown = true; }
  22843. if (attachMove === void 0) { attachMove = true; }
  22844. this._initActionManager = function (act, clickInfo) {
  22845. if (!_this._meshPickProceed) {
  22846. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  22847. _this._currentPickResult = pickResult;
  22848. if (pickResult) {
  22849. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  22850. }
  22851. _this._meshPickProceed = true;
  22852. }
  22853. return act;
  22854. };
  22855. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  22856. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  22857. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  22858. btn !== _this._previousButtonPressed) {
  22859. _this._doubleClickOccured = false;
  22860. clickInfo.singleClick = true;
  22861. clickInfo.ignore = false;
  22862. cb(clickInfo, _this._currentPickResult);
  22863. }
  22864. };
  22865. this._initClickEvent = function (obs1, obs2, evt, cb) {
  22866. var clickInfo = new ClickInfo();
  22867. _this._currentPickResult = null;
  22868. var act = null;
  22869. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  22870. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  22871. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22872. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  22873. act = _this._initActionManager(act, clickInfo);
  22874. if (act)
  22875. checkPicking = act.hasPickTriggers;
  22876. }
  22877. if (checkPicking) {
  22878. var btn = evt.button;
  22879. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  22880. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  22881. if (!clickInfo.hasSwiped) {
  22882. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  22883. if (!checkSingleClickImmediately) {
  22884. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  22885. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22886. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22887. act = _this._initActionManager(act, clickInfo);
  22888. if (act)
  22889. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  22890. }
  22891. }
  22892. if (checkSingleClickImmediately) {
  22893. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  22894. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  22895. btn !== _this._previousButtonPressed) {
  22896. clickInfo.singleClick = true;
  22897. cb(clickInfo, _this._currentPickResult);
  22898. }
  22899. }
  22900. else {
  22901. // wait that no double click has been raised during the double click delay
  22902. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22903. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  22904. }
  22905. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  22906. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22907. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22908. act = _this._initActionManager(act, clickInfo);
  22909. if (act)
  22910. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  22911. }
  22912. if (checkDoubleClick) {
  22913. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  22914. if (btn === _this._previousButtonPressed &&
  22915. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  22916. !_this._doubleClickOccured) {
  22917. // pointer has not moved for 2 clicks, it's a double click
  22918. if (!clickInfo.hasSwiped &&
  22919. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  22920. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  22921. _this._previousStartingPointerTime = 0;
  22922. _this._doubleClickOccured = true;
  22923. clickInfo.doubleClick = true;
  22924. clickInfo.ignore = false;
  22925. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  22926. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22927. }
  22928. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22929. cb(clickInfo, _this._currentPickResult);
  22930. }
  22931. else {
  22932. _this._doubleClickOccured = false;
  22933. _this._previousStartingPointerTime = _this._startingPointerTime;
  22934. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22935. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22936. _this._previousButtonPressed = btn;
  22937. if (Scene.ExclusiveDoubleClickMode) {
  22938. if (_this._previousDelayedSimpleClickTimeout) {
  22939. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22940. }
  22941. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22942. cb(clickInfo, _this._previousPickResult);
  22943. }
  22944. else {
  22945. cb(clickInfo, _this._currentPickResult);
  22946. }
  22947. }
  22948. }
  22949. else {
  22950. _this._doubleClickOccured = false;
  22951. _this._previousStartingPointerTime = _this._startingPointerTime;
  22952. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22953. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22954. _this._previousButtonPressed = btn;
  22955. }
  22956. }
  22957. }
  22958. }
  22959. clickInfo.ignore = true;
  22960. cb(clickInfo, _this._currentPickResult);
  22961. };
  22962. this._spritePredicate = function (sprite) {
  22963. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  22964. };
  22965. this._onPointerMove = function (evt) {
  22966. _this._updatePointerPosition(evt);
  22967. // PreObservable support
  22968. if (_this.onPrePointerObservable.hasObservers()) {
  22969. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  22970. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22971. _this.onPrePointerObservable.notifyObservers(pi, type);
  22972. if (pi.skipOnPointerObservable) {
  22973. return;
  22974. }
  22975. }
  22976. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22977. return;
  22978. }
  22979. if (!_this.pointerMovePredicate) {
  22980. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  22981. }
  22982. // Meshes
  22983. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  22984. _this._processPointerMove(pickResult, evt);
  22985. };
  22986. this._onPointerDown = function (evt) {
  22987. _this._totalPointersPressed++;
  22988. _this._pickedDownMesh = null;
  22989. _this._meshPickProceed = false;
  22990. _this._updatePointerPosition(evt);
  22991. if (_this.preventDefaultOnPointerDown && canvas) {
  22992. evt.preventDefault();
  22993. canvas.focus();
  22994. }
  22995. // PreObservable support
  22996. if (_this.onPrePointerObservable.hasObservers()) {
  22997. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  22998. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22999. _this.onPrePointerObservable.notifyObservers(pi, type);
  23000. if (pi.skipOnPointerObservable) {
  23001. return;
  23002. }
  23003. }
  23004. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  23005. return;
  23006. }
  23007. _this._startingPointerPosition.x = _this._pointerX;
  23008. _this._startingPointerPosition.y = _this._pointerY;
  23009. _this._startingPointerTime = new Date().getTime();
  23010. if (!_this.pointerDownPredicate) {
  23011. _this.pointerDownPredicate = function (mesh) {
  23012. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  23013. };
  23014. }
  23015. // Meshes
  23016. _this._pickedDownMesh = null;
  23017. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  23018. _this._processPointerDown(pickResult, evt);
  23019. // Sprites
  23020. _this._pickedDownSprite = null;
  23021. if (_this.spriteManagers.length > 0) {
  23022. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  23023. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  23024. if (pickResult.pickedSprite.actionManager) {
  23025. _this._pickedDownSprite = pickResult.pickedSprite;
  23026. switch (evt.button) {
  23027. case 0:
  23028. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  23029. break;
  23030. case 1:
  23031. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  23032. break;
  23033. case 2:
  23034. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  23035. break;
  23036. }
  23037. if (pickResult.pickedSprite.actionManager) {
  23038. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  23039. }
  23040. }
  23041. }
  23042. }
  23043. };
  23044. this._onPointerUp = function (evt) {
  23045. if (_this._totalPointersPressed === 0) {
  23046. return; // So we need to test it the pointer down was pressed before.
  23047. }
  23048. _this._totalPointersPressed--;
  23049. _this._pickedUpMesh = null;
  23050. _this._meshPickProceed = false;
  23051. _this._updatePointerPosition(evt);
  23052. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  23053. // PreObservable support
  23054. if (_this.onPrePointerObservable.hasObservers()) {
  23055. if (!clickInfo.ignore) {
  23056. if (!clickInfo.hasSwiped) {
  23057. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  23058. var type = BABYLON.PointerEventTypes.POINTERTAP;
  23059. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  23060. _this.onPrePointerObservable.notifyObservers(pi, type);
  23061. if (pi.skipOnPointerObservable) {
  23062. return;
  23063. }
  23064. }
  23065. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  23066. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  23067. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  23068. _this.onPrePointerObservable.notifyObservers(pi, type);
  23069. if (pi.skipOnPointerObservable) {
  23070. return;
  23071. }
  23072. }
  23073. }
  23074. }
  23075. else {
  23076. var type = BABYLON.PointerEventTypes.POINTERUP;
  23077. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  23078. _this.onPrePointerObservable.notifyObservers(pi, type);
  23079. if (pi.skipOnPointerObservable) {
  23080. return;
  23081. }
  23082. }
  23083. }
  23084. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  23085. return;
  23086. }
  23087. if (!_this.pointerUpPredicate) {
  23088. _this.pointerUpPredicate = function (mesh) {
  23089. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  23090. };
  23091. }
  23092. // Meshes
  23093. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  23094. _this._initActionManager(null, clickInfo);
  23095. }
  23096. if (!pickResult) {
  23097. pickResult = _this._currentPickResult;
  23098. }
  23099. _this._processPointerUp(pickResult, evt, clickInfo);
  23100. // Sprites
  23101. if (_this.spriteManagers.length > 0) {
  23102. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  23103. if (spritePickResult) {
  23104. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  23105. if (spritePickResult.pickedSprite.actionManager) {
  23106. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  23107. if (spritePickResult.pickedSprite.actionManager) {
  23108. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  23109. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  23110. }
  23111. }
  23112. }
  23113. }
  23114. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  23115. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  23116. }
  23117. }
  23118. }
  23119. _this._previousPickResult = _this._currentPickResult;
  23120. });
  23121. };
  23122. this._onKeyDown = function (evt) {
  23123. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  23124. if (_this.onPreKeyboardObservable.hasObservers()) {
  23125. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  23126. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  23127. if (pi.skipOnPointerObservable) {
  23128. return;
  23129. }
  23130. }
  23131. if (_this.onKeyboardObservable.hasObservers()) {
  23132. var pi = new BABYLON.KeyboardInfo(type, evt);
  23133. _this.onKeyboardObservable.notifyObservers(pi, type);
  23134. }
  23135. if (_this.actionManager) {
  23136. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  23137. }
  23138. };
  23139. this._onKeyUp = function (evt) {
  23140. var type = BABYLON.KeyboardEventTypes.KEYUP;
  23141. if (_this.onPreKeyboardObservable.hasObservers()) {
  23142. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  23143. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  23144. if (pi.skipOnPointerObservable) {
  23145. return;
  23146. }
  23147. }
  23148. if (_this.onKeyboardObservable.hasObservers()) {
  23149. var pi = new BABYLON.KeyboardInfo(type, evt);
  23150. _this.onKeyboardObservable.notifyObservers(pi, type);
  23151. }
  23152. if (_this.actionManager) {
  23153. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  23154. }
  23155. };
  23156. var engine = this.getEngine();
  23157. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  23158. if (!canvas) {
  23159. return;
  23160. }
  23161. canvas.addEventListener("keydown", _this._onKeyDown, false);
  23162. canvas.addEventListener("keyup", _this._onKeyUp, false);
  23163. });
  23164. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  23165. if (!canvas) {
  23166. return;
  23167. }
  23168. canvas.removeEventListener("keydown", _this._onKeyDown);
  23169. canvas.removeEventListener("keyup", _this._onKeyUp);
  23170. });
  23171. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  23172. var canvas = this._engine.getRenderingCanvas();
  23173. if (!canvas) {
  23174. return;
  23175. }
  23176. if (attachMove) {
  23177. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  23178. // Wheel
  23179. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  23180. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  23181. }
  23182. if (attachDown) {
  23183. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  23184. }
  23185. if (attachUp) {
  23186. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  23187. }
  23188. canvas.tabIndex = 1;
  23189. };
  23190. Scene.prototype.detachControl = function () {
  23191. var engine = this.getEngine();
  23192. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  23193. var canvas = engine.getRenderingCanvas();
  23194. if (!canvas) {
  23195. return;
  23196. }
  23197. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  23198. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  23199. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  23200. if (this._onCanvasBlurObserver) {
  23201. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  23202. }
  23203. if (this._onCanvasFocusObserver) {
  23204. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  23205. }
  23206. // Wheel
  23207. canvas.removeEventListener('mousewheel', this._onPointerMove);
  23208. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  23209. // Keyboard
  23210. canvas.removeEventListener("keydown", this._onKeyDown);
  23211. canvas.removeEventListener("keyup", this._onKeyUp);
  23212. // Observables
  23213. this.onKeyboardObservable.clear();
  23214. this.onPreKeyboardObservable.clear();
  23215. this.onPointerObservable.clear();
  23216. this.onPrePointerObservable.clear();
  23217. };
  23218. /**
  23219. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  23220. * Delay loaded resources are not taking in account
  23221. * @return true if all required resources are ready
  23222. */
  23223. Scene.prototype.isReady = function () {
  23224. if (this._isDisposed) {
  23225. return false;
  23226. }
  23227. if (this._pendingData.length > 0) {
  23228. return false;
  23229. }
  23230. var index;
  23231. var engine = this.getEngine();
  23232. // Geometries
  23233. for (index = 0; index < this._geometries.length; index++) {
  23234. var geometry = this._geometries[index];
  23235. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  23236. return false;
  23237. }
  23238. }
  23239. // Meshes
  23240. for (index = 0; index < this.meshes.length; index++) {
  23241. var mesh = this.meshes[index];
  23242. if (!mesh.isEnabled()) {
  23243. continue;
  23244. }
  23245. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  23246. continue;
  23247. }
  23248. if (!mesh.isReady(true)) {
  23249. return false;
  23250. }
  23251. // Effect layers
  23252. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  23253. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  23254. var layer = _a[_i];
  23255. if (!layer.hasMesh(mesh)) {
  23256. continue;
  23257. }
  23258. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  23259. var subMesh = _c[_b];
  23260. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  23261. return false;
  23262. }
  23263. }
  23264. }
  23265. }
  23266. // Particles
  23267. for (var _d = 0, _e = this.particleSystems; _d < _e.length; _d++) {
  23268. var particleSystem = _e[_d];
  23269. if (!particleSystem.isReady()) {
  23270. return false;
  23271. }
  23272. }
  23273. return true;
  23274. };
  23275. Scene.prototype.resetCachedMaterial = function () {
  23276. this._cachedMaterial = null;
  23277. this._cachedEffect = null;
  23278. this._cachedVisibility = null;
  23279. };
  23280. Scene.prototype.registerBeforeRender = function (func) {
  23281. this.onBeforeRenderObservable.add(func);
  23282. };
  23283. Scene.prototype.unregisterBeforeRender = function (func) {
  23284. this.onBeforeRenderObservable.removeCallback(func);
  23285. };
  23286. Scene.prototype.registerAfterRender = function (func) {
  23287. this.onAfterRenderObservable.add(func);
  23288. };
  23289. Scene.prototype.unregisterAfterRender = function (func) {
  23290. this.onAfterRenderObservable.removeCallback(func);
  23291. };
  23292. Scene.prototype._executeOnceBeforeRender = function (func) {
  23293. var _this = this;
  23294. var execFunc = function () {
  23295. func();
  23296. setTimeout(function () {
  23297. _this.unregisterBeforeRender(execFunc);
  23298. });
  23299. };
  23300. this.registerBeforeRender(execFunc);
  23301. };
  23302. /**
  23303. * The provided function will run before render once and will be disposed afterwards.
  23304. * A timeout delay can be provided so that the function will be executed in N ms.
  23305. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  23306. * @param func The function to be executed.
  23307. * @param timeout optional delay in ms
  23308. */
  23309. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  23310. var _this = this;
  23311. if (timeout !== undefined) {
  23312. setTimeout(function () {
  23313. _this._executeOnceBeforeRender(func);
  23314. }, timeout);
  23315. }
  23316. else {
  23317. this._executeOnceBeforeRender(func);
  23318. }
  23319. };
  23320. Scene.prototype._addPendingData = function (data) {
  23321. this._pendingData.push(data);
  23322. };
  23323. Scene.prototype._removePendingData = function (data) {
  23324. var wasLoading = this.isLoading;
  23325. var index = this._pendingData.indexOf(data);
  23326. if (index !== -1) {
  23327. this._pendingData.splice(index, 1);
  23328. }
  23329. if (wasLoading && !this.isLoading) {
  23330. this.onDataLoadedObservable.notifyObservers(this);
  23331. }
  23332. };
  23333. Scene.prototype.getWaitingItemsCount = function () {
  23334. return this._pendingData.length;
  23335. };
  23336. Object.defineProperty(Scene.prototype, "isLoading", {
  23337. get: function () {
  23338. return this._pendingData.length > 0;
  23339. },
  23340. enumerable: true,
  23341. configurable: true
  23342. });
  23343. /**
  23344. * Registers a function to be executed when the scene is ready.
  23345. * @param {Function} func - the function to be executed.
  23346. */
  23347. Scene.prototype.executeWhenReady = function (func) {
  23348. var _this = this;
  23349. this.onReadyObservable.add(func);
  23350. if (this._executeWhenReadyTimeoutId !== -1) {
  23351. return;
  23352. }
  23353. this._executeWhenReadyTimeoutId = setTimeout(function () {
  23354. _this._checkIsReady();
  23355. }, 150);
  23356. };
  23357. /**
  23358. * Returns a promise that resolves when the scene is ready.
  23359. * @returns A promise that resolves when the scene is ready.
  23360. */
  23361. Scene.prototype.whenReadyAsync = function () {
  23362. var _this = this;
  23363. return new Promise(function (resolve) {
  23364. _this.executeWhenReady(function () {
  23365. resolve();
  23366. });
  23367. });
  23368. };
  23369. Scene.prototype._checkIsReady = function () {
  23370. var _this = this;
  23371. if (this.isReady()) {
  23372. this.onReadyObservable.notifyObservers(this);
  23373. this.onReadyObservable.clear();
  23374. this._executeWhenReadyTimeoutId = -1;
  23375. return;
  23376. }
  23377. this._executeWhenReadyTimeoutId = setTimeout(function () {
  23378. _this._checkIsReady();
  23379. }, 150);
  23380. };
  23381. // Animations
  23382. /**
  23383. * Will start the animation sequence of a given target
  23384. * @param target defines the target
  23385. * @param from defines from which frame should animation start
  23386. * @param to defines until which frame should animation run.
  23387. * @param weight defines the weight to apply to the animation (1.0 by default)
  23388. * @param loop defines if the animation loops
  23389. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  23390. * @param onAnimationEnd defines the function to be executed when the animation ends
  23391. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  23392. * @returns the animatable object created for this animation
  23393. * @see BABYLON.Animatable
  23394. */
  23395. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable) {
  23396. if (weight === void 0) { weight = 1.0; }
  23397. if (speedRatio === void 0) { speedRatio = 1.0; }
  23398. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false);
  23399. returnedAnimatable.weight = weight;
  23400. return returnedAnimatable;
  23401. };
  23402. /**
  23403. * Will start the animation sequence of a given target
  23404. * @param target defines the target
  23405. * @param from defines from which frame should animation start
  23406. * @param to defines until which frame should animation run.
  23407. * @param loop defines if the animation loops
  23408. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  23409. * @param onAnimationEnd defines the function to be executed when the animation ends
  23410. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  23411. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  23412. * @returns the animatable object created for this animation
  23413. * @see BABYLON.Animatable
  23414. */
  23415. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent) {
  23416. if (speedRatio === void 0) { speedRatio = 1.0; }
  23417. if (stopCurrent === void 0) { stopCurrent = true; }
  23418. if (from > to && speedRatio > 0) {
  23419. speedRatio *= -1;
  23420. }
  23421. if (stopCurrent) {
  23422. this.stopAnimation(target);
  23423. }
  23424. if (!animatable) {
  23425. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  23426. }
  23427. // Local animations
  23428. if (target.animations) {
  23429. animatable.appendAnimations(target, target.animations);
  23430. }
  23431. // Children animations
  23432. if (target.getAnimatables) {
  23433. var animatables = target.getAnimatables();
  23434. for (var index = 0; index < animatables.length; index++) {
  23435. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent);
  23436. }
  23437. }
  23438. animatable.reset();
  23439. return animatable;
  23440. };
  23441. /**
  23442. * Begin a new animation on a given node
  23443. * @param {BABYLON.Node} node defines the root node where the animation will take place
  23444. * @param {BABYLON.Animation[]} defines the list of animations to start
  23445. * @param {number} from defines the initial value
  23446. * @param {number} to defines the final value
  23447. * @param {boolean} loop defines if you want animation to loop (off by default)
  23448. * @param {number} speedRatio defines the speed ratio to apply to all animations
  23449. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  23450. * @returns the list of created animatables
  23451. */
  23452. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  23453. if (speedRatio === undefined) {
  23454. speedRatio = 1.0;
  23455. }
  23456. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  23457. return animatable;
  23458. };
  23459. /**
  23460. * Begin a new animation on a given node and its hierarchy
  23461. * @param {BABYLON.Node} node defines the root node where the animation will take place
  23462. * @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.
  23463. * @param {BABYLON.Animation[]} defines the list of animations to start
  23464. * @param {number} from defines the initial value
  23465. * @param {number} to defines the final value
  23466. * @param {boolean} loop defines if you want animation to loop (off by default)
  23467. * @param {number} speedRatio defines the speed ratio to apply to all animations
  23468. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  23469. * @returns the list of animatables created for all nodes
  23470. */
  23471. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  23472. var children = target.getDescendants(directDescendantsOnly);
  23473. var result = [];
  23474. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  23475. var child = children_1[_i];
  23476. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  23477. }
  23478. return result;
  23479. };
  23480. Scene.prototype.getAnimatableByTarget = function (target) {
  23481. for (var index = 0; index < this._activeAnimatables.length; index++) {
  23482. if (this._activeAnimatables[index].target === target) {
  23483. return this._activeAnimatables[index];
  23484. }
  23485. }
  23486. return null;
  23487. };
  23488. /**
  23489. * Gets all animatables associated with a given target
  23490. * @param target defines the target to look animatables for
  23491. * @returns an array of Animatables
  23492. */
  23493. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  23494. var result = [];
  23495. for (var index = 0; index < this._activeAnimatables.length; index++) {
  23496. if (this._activeAnimatables[index].target === target) {
  23497. result.push(this._activeAnimatables[index]);
  23498. }
  23499. }
  23500. return result;
  23501. };
  23502. Object.defineProperty(Scene.prototype, "animatables", {
  23503. get: function () {
  23504. return this._activeAnimatables;
  23505. },
  23506. enumerable: true,
  23507. configurable: true
  23508. });
  23509. /**
  23510. * Will stop the animation of the given target
  23511. * @param target - the target
  23512. * @param animationName - the name of the animation to stop (all animations will be stopped if empty)
  23513. * @see beginAnimation
  23514. */
  23515. Scene.prototype.stopAnimation = function (target, animationName) {
  23516. var animatables = this.getAllAnimatablesByTarget(target);
  23517. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  23518. var animatable = animatables_1[_i];
  23519. animatable.stop(animationName);
  23520. }
  23521. };
  23522. /**
  23523. * Stops and removes all animations that have been applied to the scene
  23524. */
  23525. Scene.prototype.stopAllAnimations = function () {
  23526. if (this._activeAnimatables) {
  23527. for (var i = 0; i < this._activeAnimatables.length; i++) {
  23528. this._activeAnimatables[i].stop();
  23529. }
  23530. this._activeAnimatables = [];
  23531. }
  23532. };
  23533. Scene.prototype._animate = function () {
  23534. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  23535. return;
  23536. }
  23537. // Getting time
  23538. var now = BABYLON.Tools.Now;
  23539. if (!this._animationTimeLast) {
  23540. if (this._pendingData.length > 0) {
  23541. return;
  23542. }
  23543. this._animationTimeLast = now;
  23544. }
  23545. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  23546. this._animationTime += deltaTime;
  23547. this._animationTimeLast = now;
  23548. for (var index = 0; index < this._activeAnimatables.length; index++) {
  23549. this._activeAnimatables[index]._animate(this._animationTime);
  23550. }
  23551. // Late animation bindings
  23552. this._processLateAnimationBindings();
  23553. };
  23554. /** @ignore */
  23555. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation) {
  23556. var target = runtimeAnimation.target;
  23557. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  23558. if (!target._lateAnimationHolders) {
  23559. target._lateAnimationHolders = {};
  23560. }
  23561. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  23562. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  23563. totalWeight: 0,
  23564. animations: []
  23565. };
  23566. }
  23567. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  23568. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  23569. };
  23570. Scene.prototype._processLateAnimationBindings = function () {
  23571. if (!this._registeredForLateAnimationBindings.length) {
  23572. return;
  23573. }
  23574. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  23575. var target = this._registeredForLateAnimationBindings.data[index];
  23576. for (var path in target._lateAnimationHolders) {
  23577. var holder = target._lateAnimationHolders[path];
  23578. // Sanity check
  23579. if (!holder.animations[0].originalValue.scaleAndAddToRef) {
  23580. continue;
  23581. }
  23582. var normalizer = 1.0;
  23583. var finalValue = void 0;
  23584. if (holder.totalWeight < 1.0) {
  23585. // We need to mix the original value in
  23586. var originalValue = holder.animations[0].originalValue;
  23587. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  23588. }
  23589. else {
  23590. // We need to normalize the weights
  23591. normalizer = holder.totalWeight;
  23592. }
  23593. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  23594. var runtimeAnimation = holder.animations[animIndex];
  23595. if (finalValue) {
  23596. runtimeAnimation.currentValue.scaleAndAddToRef(runtimeAnimation.weight / normalizer, finalValue);
  23597. }
  23598. else {
  23599. finalValue = runtimeAnimation.currentValue.scale(runtimeAnimation.weight / normalizer);
  23600. }
  23601. }
  23602. runtimeAnimation.target[path] = finalValue;
  23603. }
  23604. target._lateAnimationHolders = {};
  23605. }
  23606. this._registeredForLateAnimationBindings.reset();
  23607. };
  23608. // Matrix
  23609. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  23610. this._useAlternateCameraConfiguration = active;
  23611. };
  23612. Scene.prototype.getViewMatrix = function () {
  23613. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  23614. };
  23615. Scene.prototype.getProjectionMatrix = function () {
  23616. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  23617. };
  23618. Scene.prototype.getTransformMatrix = function () {
  23619. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  23620. };
  23621. Scene.prototype.setTransformMatrix = function (view, projection) {
  23622. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  23623. return;
  23624. }
  23625. this._viewUpdateFlag = view.updateFlag;
  23626. this._projectionUpdateFlag = projection.updateFlag;
  23627. this._viewMatrix = view;
  23628. this._projectionMatrix = projection;
  23629. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  23630. // Update frustum
  23631. if (!this._frustumPlanes) {
  23632. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  23633. }
  23634. else {
  23635. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  23636. }
  23637. if (this.activeCamera && this.activeCamera._alternateCamera) {
  23638. var otherCamera = this.activeCamera._alternateCamera;
  23639. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  23640. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  23641. }
  23642. if (this._sceneUbo.useUbo) {
  23643. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  23644. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  23645. this._sceneUbo.update();
  23646. }
  23647. };
  23648. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  23649. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  23650. return;
  23651. }
  23652. this._alternateViewUpdateFlag = view.updateFlag;
  23653. this._alternateProjectionUpdateFlag = projection.updateFlag;
  23654. this._alternateViewMatrix = view;
  23655. this._alternateProjectionMatrix = projection;
  23656. if (!this._alternateTransformMatrix) {
  23657. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  23658. }
  23659. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  23660. if (!this._alternateSceneUbo) {
  23661. this._createAlternateUbo();
  23662. }
  23663. if (this._alternateSceneUbo.useUbo) {
  23664. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  23665. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  23666. this._alternateSceneUbo.update();
  23667. }
  23668. };
  23669. Scene.prototype.getSceneUniformBuffer = function () {
  23670. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  23671. };
  23672. // Methods
  23673. Scene.prototype.getUniqueId = function () {
  23674. var result = Scene._uniqueIdCounter;
  23675. Scene._uniqueIdCounter++;
  23676. return result;
  23677. };
  23678. Scene.prototype.addMesh = function (newMesh) {
  23679. this.meshes.push(newMesh);
  23680. //notify the collision coordinator
  23681. if (this.collisionCoordinator) {
  23682. this.collisionCoordinator.onMeshAdded(newMesh);
  23683. }
  23684. newMesh._resyncLightSources();
  23685. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  23686. };
  23687. Scene.prototype.removeMesh = function (toRemove) {
  23688. var index = this.meshes.indexOf(toRemove);
  23689. if (index !== -1) {
  23690. // Remove from the scene if mesh found
  23691. this.meshes.splice(index, 1);
  23692. }
  23693. this.onMeshRemovedObservable.notifyObservers(toRemove);
  23694. return index;
  23695. };
  23696. Scene.prototype.addTransformNode = function (newTransformNode) {
  23697. this.transformNodes.push(newTransformNode);
  23698. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  23699. };
  23700. Scene.prototype.removeTransformNode = function (toRemove) {
  23701. var index = this.transformNodes.indexOf(toRemove);
  23702. if (index !== -1) {
  23703. // Remove from the scene if found
  23704. this.transformNodes.splice(index, 1);
  23705. }
  23706. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  23707. return index;
  23708. };
  23709. Scene.prototype.removeSkeleton = function (toRemove) {
  23710. var index = this.skeletons.indexOf(toRemove);
  23711. if (index !== -1) {
  23712. // Remove from the scene if found
  23713. this.skeletons.splice(index, 1);
  23714. }
  23715. return index;
  23716. };
  23717. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  23718. var index = this.morphTargetManagers.indexOf(toRemove);
  23719. if (index !== -1) {
  23720. // Remove from the scene if found
  23721. this.morphTargetManagers.splice(index, 1);
  23722. }
  23723. return index;
  23724. };
  23725. Scene.prototype.removeLight = function (toRemove) {
  23726. var index = this.lights.indexOf(toRemove);
  23727. if (index !== -1) {
  23728. // Remove from meshes
  23729. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  23730. var mesh = _a[_i];
  23731. mesh._removeLightSource(toRemove);
  23732. }
  23733. // Remove from the scene if mesh found
  23734. this.lights.splice(index, 1);
  23735. this.sortLightsByPriority();
  23736. }
  23737. this.onLightRemovedObservable.notifyObservers(toRemove);
  23738. return index;
  23739. };
  23740. Scene.prototype.removeCamera = function (toRemove) {
  23741. var index = this.cameras.indexOf(toRemove);
  23742. if (index !== -1) {
  23743. // Remove from the scene if mesh found
  23744. this.cameras.splice(index, 1);
  23745. }
  23746. // Remove from activeCameras
  23747. var index2 = this.activeCameras.indexOf(toRemove);
  23748. if (index2 !== -1) {
  23749. // Remove from the scene if mesh found
  23750. this.activeCameras.splice(index2, 1);
  23751. }
  23752. // Reset the activeCamera
  23753. if (this.activeCamera === toRemove) {
  23754. if (this.cameras.length > 0) {
  23755. this.activeCamera = this.cameras[0];
  23756. }
  23757. else {
  23758. this.activeCamera = null;
  23759. }
  23760. }
  23761. this.onCameraRemovedObservable.notifyObservers(toRemove);
  23762. return index;
  23763. };
  23764. Scene.prototype.removeParticleSystem = function (toRemove) {
  23765. var index = this.particleSystems.indexOf(toRemove);
  23766. if (index !== -1) {
  23767. this.particleSystems.splice(index, 1);
  23768. }
  23769. return index;
  23770. };
  23771. ;
  23772. Scene.prototype.removeAnimation = function (toRemove) {
  23773. var index = this.animations.indexOf(toRemove);
  23774. if (index !== -1) {
  23775. this.animations.splice(index, 1);
  23776. }
  23777. return index;
  23778. };
  23779. ;
  23780. Scene.prototype.removeMultiMaterial = function (toRemove) {
  23781. var index = this.multiMaterials.indexOf(toRemove);
  23782. if (index !== -1) {
  23783. this.multiMaterials.splice(index, 1);
  23784. }
  23785. return index;
  23786. };
  23787. ;
  23788. Scene.prototype.removeMaterial = function (toRemove) {
  23789. var index = this.materials.indexOf(toRemove);
  23790. if (index !== -1) {
  23791. this.materials.splice(index, 1);
  23792. }
  23793. return index;
  23794. };
  23795. ;
  23796. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  23797. var index = this.lensFlareSystems.indexOf(toRemove);
  23798. if (index !== -1) {
  23799. this.lensFlareSystems.splice(index, 1);
  23800. }
  23801. return index;
  23802. };
  23803. ;
  23804. Scene.prototype.removeActionManager = function (toRemove) {
  23805. var index = this._actionManagers.indexOf(toRemove);
  23806. if (index !== -1) {
  23807. this._actionManagers.splice(index, 1);
  23808. }
  23809. return index;
  23810. };
  23811. ;
  23812. Scene.prototype.addLight = function (newLight) {
  23813. this.lights.push(newLight);
  23814. this.sortLightsByPriority();
  23815. // Add light to all meshes (To support if the light is removed and then readded)
  23816. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  23817. var mesh = _a[_i];
  23818. if (mesh._lightSources.indexOf(newLight) === -1) {
  23819. mesh._lightSources.push(newLight);
  23820. mesh._resyncLightSources();
  23821. }
  23822. }
  23823. this.onNewLightAddedObservable.notifyObservers(newLight);
  23824. };
  23825. Scene.prototype.sortLightsByPriority = function () {
  23826. if (this.requireLightSorting) {
  23827. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  23828. }
  23829. };
  23830. Scene.prototype.addCamera = function (newCamera) {
  23831. this.cameras.push(newCamera);
  23832. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  23833. };
  23834. Scene.prototype.addSkeleton = function (newSkeleton) {
  23835. this.skeletons.push(newSkeleton);
  23836. };
  23837. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  23838. this.particleSystems.push(newParticleSystem);
  23839. };
  23840. Scene.prototype.addAnimation = function (newAnimation) {
  23841. this.animations.push(newAnimation);
  23842. };
  23843. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  23844. this.multiMaterials.push(newMultiMaterial);
  23845. };
  23846. Scene.prototype.addMaterial = function (newMaterial) {
  23847. this.materials.push(newMaterial);
  23848. };
  23849. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  23850. this.morphTargetManagers.push(newMorphTargetManager);
  23851. };
  23852. Scene.prototype.addGeometry = function (newGeometrie) {
  23853. this._geometries.push(newGeometrie);
  23854. };
  23855. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  23856. this.lensFlareSystems.push(newLensFlareSystem);
  23857. };
  23858. Scene.prototype.addActionManager = function (newActionManager) {
  23859. this._actionManagers.push(newActionManager);
  23860. };
  23861. /**
  23862. * Switch active camera
  23863. * @param {Camera} newCamera - new active camera
  23864. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  23865. */
  23866. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  23867. if (attachControl === void 0) { attachControl = true; }
  23868. var canvas = this._engine.getRenderingCanvas();
  23869. if (!canvas) {
  23870. return;
  23871. }
  23872. if (this.activeCamera) {
  23873. this.activeCamera.detachControl(canvas);
  23874. }
  23875. this.activeCamera = newCamera;
  23876. if (attachControl) {
  23877. newCamera.attachControl(canvas);
  23878. }
  23879. };
  23880. /**
  23881. * sets the active camera of the scene using its ID
  23882. * @param {string} id - the camera's ID
  23883. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  23884. * @see activeCamera
  23885. */
  23886. Scene.prototype.setActiveCameraByID = function (id) {
  23887. var camera = this.getCameraByID(id);
  23888. if (camera) {
  23889. this.activeCamera = camera;
  23890. return camera;
  23891. }
  23892. return null;
  23893. };
  23894. /**
  23895. * sets the active camera of the scene using its name
  23896. * @param {string} name - the camera's name
  23897. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  23898. * @see activeCamera
  23899. */
  23900. Scene.prototype.setActiveCameraByName = function (name) {
  23901. var camera = this.getCameraByName(name);
  23902. if (camera) {
  23903. this.activeCamera = camera;
  23904. return camera;
  23905. }
  23906. return null;
  23907. };
  23908. /**
  23909. * get an animation group using its name
  23910. * @param {string} the material's name
  23911. * @return {BABYLON.AnimationGroup|null} the animation group or null if none found.
  23912. */
  23913. Scene.prototype.getAnimationGroupByName = function (name) {
  23914. for (var index = 0; index < this.animationGroups.length; index++) {
  23915. if (this.animationGroups[index].name === name) {
  23916. return this.animationGroups[index];
  23917. }
  23918. }
  23919. return null;
  23920. };
  23921. /**
  23922. * get a material using its id
  23923. * @param {string} the material's ID
  23924. * @return {BABYLON.Material|null} the material or null if none found.
  23925. */
  23926. Scene.prototype.getMaterialByID = function (id) {
  23927. for (var index = 0; index < this.materials.length; index++) {
  23928. if (this.materials[index].id === id) {
  23929. return this.materials[index];
  23930. }
  23931. }
  23932. return null;
  23933. };
  23934. /**
  23935. * get a material using its name
  23936. * @param {string} the material's name
  23937. * @return {BABYLON.Material|null} the material or null if none found.
  23938. */
  23939. Scene.prototype.getMaterialByName = function (name) {
  23940. for (var index = 0; index < this.materials.length; index++) {
  23941. if (this.materials[index].name === name) {
  23942. return this.materials[index];
  23943. }
  23944. }
  23945. return null;
  23946. };
  23947. Scene.prototype.getLensFlareSystemByName = function (name) {
  23948. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  23949. if (this.lensFlareSystems[index].name === name) {
  23950. return this.lensFlareSystems[index];
  23951. }
  23952. }
  23953. return null;
  23954. };
  23955. Scene.prototype.getLensFlareSystemByID = function (id) {
  23956. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  23957. if (this.lensFlareSystems[index].id === id) {
  23958. return this.lensFlareSystems[index];
  23959. }
  23960. }
  23961. return null;
  23962. };
  23963. Scene.prototype.getCameraByID = function (id) {
  23964. for (var index = 0; index < this.cameras.length; index++) {
  23965. if (this.cameras[index].id === id) {
  23966. return this.cameras[index];
  23967. }
  23968. }
  23969. return null;
  23970. };
  23971. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  23972. for (var index = 0; index < this.cameras.length; index++) {
  23973. if (this.cameras[index].uniqueId === uniqueId) {
  23974. return this.cameras[index];
  23975. }
  23976. }
  23977. return null;
  23978. };
  23979. /**
  23980. * get a camera using its name
  23981. * @param {string} the camera's name
  23982. * @return {BABYLON.Camera|null} the camera or null if none found.
  23983. */
  23984. Scene.prototype.getCameraByName = function (name) {
  23985. for (var index = 0; index < this.cameras.length; index++) {
  23986. if (this.cameras[index].name === name) {
  23987. return this.cameras[index];
  23988. }
  23989. }
  23990. return null;
  23991. };
  23992. /**
  23993. * get a bone using its id
  23994. * @param {string} the bone's id
  23995. * @return {BABYLON.Bone|null} the bone or null if not found
  23996. */
  23997. Scene.prototype.getBoneByID = function (id) {
  23998. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  23999. var skeleton = this.skeletons[skeletonIndex];
  24000. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  24001. if (skeleton.bones[boneIndex].id === id) {
  24002. return skeleton.bones[boneIndex];
  24003. }
  24004. }
  24005. }
  24006. return null;
  24007. };
  24008. /**
  24009. * get a bone using its id
  24010. * @param {string} the bone's name
  24011. * @return {BABYLON.Bone|null} the bone or null if not found
  24012. */
  24013. Scene.prototype.getBoneByName = function (name) {
  24014. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  24015. var skeleton = this.skeletons[skeletonIndex];
  24016. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  24017. if (skeleton.bones[boneIndex].name === name) {
  24018. return skeleton.bones[boneIndex];
  24019. }
  24020. }
  24021. }
  24022. return null;
  24023. };
  24024. /**
  24025. * get a light node using its name
  24026. * @param {string} the light's name
  24027. * @return {BABYLON.Light|null} the light or null if none found.
  24028. */
  24029. Scene.prototype.getLightByName = function (name) {
  24030. for (var index = 0; index < this.lights.length; index++) {
  24031. if (this.lights[index].name === name) {
  24032. return this.lights[index];
  24033. }
  24034. }
  24035. return null;
  24036. };
  24037. /**
  24038. * get a light node using its ID
  24039. * @param {string} the light's id
  24040. * @return {BABYLON.Light|null} the light or null if none found.
  24041. */
  24042. Scene.prototype.getLightByID = function (id) {
  24043. for (var index = 0; index < this.lights.length; index++) {
  24044. if (this.lights[index].id === id) {
  24045. return this.lights[index];
  24046. }
  24047. }
  24048. return null;
  24049. };
  24050. /**
  24051. * get a light node using its scene-generated unique ID
  24052. * @param {number} the light's unique id
  24053. * @return {BABYLON.Light|null} the light or null if none found.
  24054. */
  24055. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  24056. for (var index = 0; index < this.lights.length; index++) {
  24057. if (this.lights[index].uniqueId === uniqueId) {
  24058. return this.lights[index];
  24059. }
  24060. }
  24061. return null;
  24062. };
  24063. /**
  24064. * get a particle system by id
  24065. * @param id {number} the particle system id
  24066. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  24067. */
  24068. Scene.prototype.getParticleSystemByID = function (id) {
  24069. for (var index = 0; index < this.particleSystems.length; index++) {
  24070. if (this.particleSystems[index].id === id) {
  24071. return this.particleSystems[index];
  24072. }
  24073. }
  24074. return null;
  24075. };
  24076. /**
  24077. * get a geometry using its ID
  24078. * @param {string} the geometry's id
  24079. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  24080. */
  24081. Scene.prototype.getGeometryByID = function (id) {
  24082. for (var index = 0; index < this._geometries.length; index++) {
  24083. if (this._geometries[index].id === id) {
  24084. return this._geometries[index];
  24085. }
  24086. }
  24087. return null;
  24088. };
  24089. /**
  24090. * add a new geometry to this scene.
  24091. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  24092. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  24093. * @return {boolean} was the geometry added or not
  24094. */
  24095. Scene.prototype.pushGeometry = function (geometry, force) {
  24096. if (!force && this.getGeometryByID(geometry.id)) {
  24097. return false;
  24098. }
  24099. this._geometries.push(geometry);
  24100. //notify the collision coordinator
  24101. if (this.collisionCoordinator) {
  24102. this.collisionCoordinator.onGeometryAdded(geometry);
  24103. }
  24104. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  24105. return true;
  24106. };
  24107. /**
  24108. * Removes an existing geometry
  24109. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  24110. * @return {boolean} was the geometry removed or not
  24111. */
  24112. Scene.prototype.removeGeometry = function (geometry) {
  24113. var index = this._geometries.indexOf(geometry);
  24114. if (index > -1) {
  24115. this._geometries.splice(index, 1);
  24116. //notify the collision coordinator
  24117. if (this.collisionCoordinator) {
  24118. this.collisionCoordinator.onGeometryDeleted(geometry);
  24119. }
  24120. this.onGeometryRemovedObservable.notifyObservers(geometry);
  24121. return true;
  24122. }
  24123. return false;
  24124. };
  24125. Scene.prototype.getGeometries = function () {
  24126. return this._geometries;
  24127. };
  24128. /**
  24129. * Get the first added mesh found of a given ID
  24130. * @param {string} id - the id to search for
  24131. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  24132. */
  24133. Scene.prototype.getMeshByID = function (id) {
  24134. for (var index = 0; index < this.meshes.length; index++) {
  24135. if (this.meshes[index].id === id) {
  24136. return this.meshes[index];
  24137. }
  24138. }
  24139. return null;
  24140. };
  24141. Scene.prototype.getMeshesByID = function (id) {
  24142. return this.meshes.filter(function (m) {
  24143. return m.id === id;
  24144. });
  24145. };
  24146. /**
  24147. * Get the first added transform node found of a given ID
  24148. * @param {string} id - the id to search for
  24149. * @return {BABYLON.TransformNode|null} the transform node found or null if not found at all.
  24150. */
  24151. Scene.prototype.getTransformNodeByID = function (id) {
  24152. for (var index = 0; index < this.transformNodes.length; index++) {
  24153. if (this.transformNodes[index].id === id) {
  24154. return this.transformNodes[index];
  24155. }
  24156. }
  24157. return null;
  24158. };
  24159. Scene.prototype.getTransformNodesByID = function (id) {
  24160. return this.transformNodes.filter(function (m) {
  24161. return m.id === id;
  24162. });
  24163. };
  24164. /**
  24165. * Get a mesh with its auto-generated unique id
  24166. * @param {number} uniqueId - the unique id to search for
  24167. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  24168. */
  24169. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  24170. for (var index = 0; index < this.meshes.length; index++) {
  24171. if (this.meshes[index].uniqueId === uniqueId) {
  24172. return this.meshes[index];
  24173. }
  24174. }
  24175. return null;
  24176. };
  24177. /**
  24178. * Get a the last added mesh found of a given ID
  24179. * @param {string} id - the id to search for
  24180. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  24181. */
  24182. Scene.prototype.getLastMeshByID = function (id) {
  24183. for (var index = this.meshes.length - 1; index >= 0; index--) {
  24184. if (this.meshes[index].id === id) {
  24185. return this.meshes[index];
  24186. }
  24187. }
  24188. return null;
  24189. };
  24190. /**
  24191. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  24192. * @param {string} id - the id to search for
  24193. * @return {BABYLON.Node|null} the node found or null if not found at all.
  24194. */
  24195. Scene.prototype.getLastEntryByID = function (id) {
  24196. var index;
  24197. for (index = this.meshes.length - 1; index >= 0; index--) {
  24198. if (this.meshes[index].id === id) {
  24199. return this.meshes[index];
  24200. }
  24201. }
  24202. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  24203. if (this.transformNodes[index].id === id) {
  24204. return this.transformNodes[index];
  24205. }
  24206. }
  24207. for (index = this.cameras.length - 1; index >= 0; index--) {
  24208. if (this.cameras[index].id === id) {
  24209. return this.cameras[index];
  24210. }
  24211. }
  24212. for (index = this.lights.length - 1; index >= 0; index--) {
  24213. if (this.lights[index].id === id) {
  24214. return this.lights[index];
  24215. }
  24216. }
  24217. return null;
  24218. };
  24219. Scene.prototype.getNodeByID = function (id) {
  24220. var mesh = this.getMeshByID(id);
  24221. if (mesh) {
  24222. return mesh;
  24223. }
  24224. var light = this.getLightByID(id);
  24225. if (light) {
  24226. return light;
  24227. }
  24228. var camera = this.getCameraByID(id);
  24229. if (camera) {
  24230. return camera;
  24231. }
  24232. var bone = this.getBoneByID(id);
  24233. return bone;
  24234. };
  24235. Scene.prototype.getNodeByName = function (name) {
  24236. var mesh = this.getMeshByName(name);
  24237. if (mesh) {
  24238. return mesh;
  24239. }
  24240. var light = this.getLightByName(name);
  24241. if (light) {
  24242. return light;
  24243. }
  24244. var camera = this.getCameraByName(name);
  24245. if (camera) {
  24246. return camera;
  24247. }
  24248. var bone = this.getBoneByName(name);
  24249. return bone;
  24250. };
  24251. Scene.prototype.getMeshByName = function (name) {
  24252. for (var index = 0; index < this.meshes.length; index++) {
  24253. if (this.meshes[index].name === name) {
  24254. return this.meshes[index];
  24255. }
  24256. }
  24257. return null;
  24258. };
  24259. Scene.prototype.getTransformNodeByName = function (name) {
  24260. for (var index = 0; index < this.transformNodes.length; index++) {
  24261. if (this.transformNodes[index].name === name) {
  24262. return this.transformNodes[index];
  24263. }
  24264. }
  24265. return null;
  24266. };
  24267. Scene.prototype.getSoundByName = function (name) {
  24268. var index;
  24269. if (BABYLON.AudioEngine) {
  24270. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  24271. if (this.mainSoundTrack.soundCollection[index].name === name) {
  24272. return this.mainSoundTrack.soundCollection[index];
  24273. }
  24274. }
  24275. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  24276. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  24277. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  24278. return this.soundTracks[sdIndex].soundCollection[index];
  24279. }
  24280. }
  24281. }
  24282. }
  24283. return null;
  24284. };
  24285. Scene.prototype.getLastSkeletonByID = function (id) {
  24286. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  24287. if (this.skeletons[index].id === id) {
  24288. return this.skeletons[index];
  24289. }
  24290. }
  24291. return null;
  24292. };
  24293. Scene.prototype.getSkeletonById = function (id) {
  24294. for (var index = 0; index < this.skeletons.length; index++) {
  24295. if (this.skeletons[index].id === id) {
  24296. return this.skeletons[index];
  24297. }
  24298. }
  24299. return null;
  24300. };
  24301. Scene.prototype.getSkeletonByName = function (name) {
  24302. for (var index = 0; index < this.skeletons.length; index++) {
  24303. if (this.skeletons[index].name === name) {
  24304. return this.skeletons[index];
  24305. }
  24306. }
  24307. return null;
  24308. };
  24309. Scene.prototype.getMorphTargetManagerById = function (id) {
  24310. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  24311. if (this.morphTargetManagers[index].uniqueId === id) {
  24312. return this.morphTargetManagers[index];
  24313. }
  24314. }
  24315. return null;
  24316. };
  24317. Scene.prototype.isActiveMesh = function (mesh) {
  24318. return (this._activeMeshes.indexOf(mesh) !== -1);
  24319. };
  24320. /**
  24321. * Return a the first highlight layer of the scene with a given name.
  24322. * @param name The name of the highlight layer to look for.
  24323. * @return The highlight layer if found otherwise null.
  24324. */
  24325. Scene.prototype.getHighlightLayerByName = function (name) {
  24326. for (var index = 0; index < this.effectLayers.length; index++) {
  24327. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  24328. return this.effectLayers[index];
  24329. }
  24330. }
  24331. return null;
  24332. };
  24333. /**
  24334. * Return a the first highlight layer of the scene with a given name.
  24335. * @param name The name of the highlight layer to look for.
  24336. * @return The highlight layer if found otherwise null.
  24337. */
  24338. Scene.prototype.getGlowLayerByName = function (name) {
  24339. for (var index = 0; index < this.effectLayers.length; index++) {
  24340. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  24341. return this.effectLayers[index];
  24342. }
  24343. }
  24344. return null;
  24345. };
  24346. Object.defineProperty(Scene.prototype, "uid", {
  24347. /**
  24348. * Return a unique id as a string which can serve as an identifier for the scene
  24349. */
  24350. get: function () {
  24351. if (!this._uid) {
  24352. this._uid = BABYLON.Tools.RandomId();
  24353. }
  24354. return this._uid;
  24355. },
  24356. enumerable: true,
  24357. configurable: true
  24358. });
  24359. /**
  24360. * Add an externaly attached data from its key.
  24361. * This method call will fail and return false, if such key already exists.
  24362. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  24363. * @param key the unique key that identifies the data
  24364. * @param data the data object to associate to the key for this Engine instance
  24365. * @return true if no such key were already present and the data was added successfully, false otherwise
  24366. */
  24367. Scene.prototype.addExternalData = function (key, data) {
  24368. if (!this._externalData) {
  24369. this._externalData = new BABYLON.StringDictionary();
  24370. }
  24371. return this._externalData.add(key, data);
  24372. };
  24373. /**
  24374. * Get an externaly attached data from its key
  24375. * @param key the unique key that identifies the data
  24376. * @return the associated data, if present (can be null), or undefined if not present
  24377. */
  24378. Scene.prototype.getExternalData = function (key) {
  24379. if (!this._externalData) {
  24380. return null;
  24381. }
  24382. return this._externalData.get(key);
  24383. };
  24384. /**
  24385. * Get an externaly attached data from its key, create it using a factory if it's not already present
  24386. * @param key the unique key that identifies the data
  24387. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  24388. * @return the associated data, can be null if the factory returned null.
  24389. */
  24390. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  24391. if (!this._externalData) {
  24392. this._externalData = new BABYLON.StringDictionary();
  24393. }
  24394. return this._externalData.getOrAddWithFactory(key, factory);
  24395. };
  24396. /**
  24397. * Remove an externaly attached data from the Engine instance
  24398. * @param key the unique key that identifies the data
  24399. * @return true if the data was successfully removed, false if it doesn't exist
  24400. */
  24401. Scene.prototype.removeExternalData = function (key) {
  24402. return this._externalData.remove(key);
  24403. };
  24404. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  24405. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  24406. if (mesh.showSubMeshesBoundingBox) {
  24407. var boundingInfo = subMesh.getBoundingInfo();
  24408. if (boundingInfo !== null && boundingInfo !== undefined) {
  24409. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  24410. }
  24411. }
  24412. var material = subMesh.getMaterial();
  24413. if (material !== null && material !== undefined) {
  24414. // Render targets
  24415. if (material.getRenderTargetTextures !== undefined) {
  24416. if (this._processedMaterials.indexOf(material) === -1) {
  24417. this._processedMaterials.push(material);
  24418. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  24419. }
  24420. }
  24421. // Dispatch
  24422. this._activeIndices.addCount(subMesh.indexCount, false);
  24423. this._renderingManager.dispatch(subMesh, mesh, material);
  24424. }
  24425. }
  24426. };
  24427. /**
  24428. * Clear the processed materials smart array preventing retention point in material dispose.
  24429. */
  24430. Scene.prototype.freeProcessedMaterials = function () {
  24431. this._processedMaterials.dispose();
  24432. };
  24433. /**
  24434. * Clear the active meshes smart array preventing retention point in mesh dispose.
  24435. */
  24436. Scene.prototype.freeActiveMeshes = function () {
  24437. this._activeMeshes.dispose();
  24438. if (this.activeCamera && this.activeCamera._activeMeshes) {
  24439. this.activeCamera._activeMeshes.dispose();
  24440. }
  24441. if (this.activeCameras) {
  24442. for (var i = 0; i < this.activeCameras.length; i++) {
  24443. var activeCamera = this.activeCameras[i];
  24444. if (activeCamera && activeCamera._activeMeshes) {
  24445. activeCamera._activeMeshes.dispose();
  24446. }
  24447. }
  24448. }
  24449. };
  24450. /**
  24451. * Clear the info related to rendering groups preventing retention points during dispose.
  24452. */
  24453. Scene.prototype.freeRenderingGroups = function () {
  24454. if (this._renderingManager) {
  24455. this._renderingManager.freeRenderingGroups();
  24456. }
  24457. if (this.textures) {
  24458. for (var i = 0; i < this.textures.length; i++) {
  24459. var texture = this.textures[i];
  24460. if (texture && texture.renderList) {
  24461. texture.freeRenderingGroups();
  24462. }
  24463. }
  24464. }
  24465. };
  24466. Scene.prototype._isInIntermediateRendering = function () {
  24467. return this._intermediateRendering;
  24468. };
  24469. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  24470. this._activeMeshCandidateProvider = provider;
  24471. };
  24472. Scene.prototype.getActiveMeshCandidateProvider = function () {
  24473. return this._activeMeshCandidateProvider;
  24474. };
  24475. /**
  24476. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  24477. */
  24478. Scene.prototype.freezeActiveMeshes = function () {
  24479. if (!this.activeCamera) {
  24480. return this;
  24481. }
  24482. if (!this._frustumPlanes) {
  24483. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  24484. }
  24485. this._evaluateActiveMeshes();
  24486. this._activeMeshesFrozen = true;
  24487. return this;
  24488. };
  24489. /**
  24490. * Use this function to restart evaluating active meshes on every frame
  24491. */
  24492. Scene.prototype.unfreezeActiveMeshes = function () {
  24493. this._activeMeshesFrozen = false;
  24494. return this;
  24495. };
  24496. Scene.prototype._evaluateActiveMeshes = function () {
  24497. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  24498. return;
  24499. }
  24500. if (!this.activeCamera) {
  24501. return;
  24502. }
  24503. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  24504. this.activeCamera._activeMeshes.reset();
  24505. this._activeMeshes.reset();
  24506. this._renderingManager.reset();
  24507. this._processedMaterials.reset();
  24508. this._activeParticleSystems.reset();
  24509. this._activeSkeletons.reset();
  24510. this._softwareSkinnedMeshes.reset();
  24511. if (this._boundingBoxRenderer) {
  24512. this._boundingBoxRenderer.reset();
  24513. }
  24514. // Meshes
  24515. var meshes;
  24516. var len;
  24517. var checkIsEnabled = true;
  24518. // Determine mesh candidates
  24519. if (this._activeMeshCandidateProvider !== undefined) {
  24520. // Use _activeMeshCandidateProvider
  24521. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  24522. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  24523. if (meshes !== undefined) {
  24524. len = meshes.length;
  24525. }
  24526. else {
  24527. len = 0;
  24528. }
  24529. }
  24530. else if (this._selectionOctree !== undefined) {
  24531. // Octree
  24532. var selection = this._selectionOctree.select(this._frustumPlanes);
  24533. meshes = selection.data;
  24534. len = selection.length;
  24535. }
  24536. else {
  24537. // Full scene traversal
  24538. len = this.meshes.length;
  24539. meshes = this.meshes;
  24540. }
  24541. // Check each mesh
  24542. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  24543. mesh = meshes[meshIndex];
  24544. if (mesh.isBlocked) {
  24545. continue;
  24546. }
  24547. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  24548. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  24549. continue;
  24550. }
  24551. mesh.computeWorldMatrix();
  24552. // Intersections
  24553. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  24554. this._meshesForIntersections.pushNoDuplicate(mesh);
  24555. }
  24556. // Switch to current LOD
  24557. meshLOD = mesh.getLOD(this.activeCamera);
  24558. if (meshLOD === undefined || meshLOD === null) {
  24559. continue;
  24560. }
  24561. mesh._preActivate();
  24562. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  24563. this._activeMeshes.push(mesh);
  24564. this.activeCamera._activeMeshes.push(mesh);
  24565. mesh._activate(this._renderId);
  24566. if (meshLOD !== mesh) {
  24567. meshLOD._activate(this._renderId);
  24568. }
  24569. this._activeMesh(mesh, meshLOD);
  24570. }
  24571. }
  24572. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  24573. // Particle systems
  24574. if (this.particlesEnabled) {
  24575. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  24576. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  24577. var particleSystem = this.particleSystems[particleIndex];
  24578. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  24579. continue;
  24580. }
  24581. var emitter = particleSystem.emitter;
  24582. if (!emitter.position || emitter.isEnabled()) {
  24583. this._activeParticleSystems.push(particleSystem);
  24584. particleSystem.animate();
  24585. this._renderingManager.dispatchParticles(particleSystem);
  24586. }
  24587. }
  24588. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  24589. }
  24590. };
  24591. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  24592. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  24593. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  24594. mesh.skeleton.prepare();
  24595. }
  24596. if (!mesh.computeBonesUsingShaders) {
  24597. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  24598. }
  24599. }
  24600. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  24601. var boundingInfo = sourceMesh.getBoundingInfo();
  24602. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  24603. }
  24604. if (mesh !== undefined && mesh !== null
  24605. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  24606. // Submeshes Octrees
  24607. var len;
  24608. var subMeshes;
  24609. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  24610. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  24611. len = intersections.length;
  24612. subMeshes = intersections.data;
  24613. }
  24614. else {
  24615. subMeshes = mesh.subMeshes;
  24616. len = subMeshes.length;
  24617. }
  24618. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  24619. subMesh = subMeshes[subIndex];
  24620. this._evaluateSubMesh(subMesh, mesh);
  24621. }
  24622. }
  24623. };
  24624. Scene.prototype.updateTransformMatrix = function (force) {
  24625. if (!this.activeCamera) {
  24626. return;
  24627. }
  24628. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  24629. };
  24630. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  24631. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  24632. };
  24633. Scene.prototype._renderForCamera = function (camera, rigParent) {
  24634. if (camera && camera._skipRendering) {
  24635. return;
  24636. }
  24637. var engine = this._engine;
  24638. this.activeCamera = camera;
  24639. if (!this.activeCamera)
  24640. throw new Error("Active camera not set");
  24641. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  24642. // Viewport
  24643. engine.setViewport(this.activeCamera.viewport);
  24644. // Camera
  24645. this.resetCachedMaterial();
  24646. this._renderId++;
  24647. this.updateTransformMatrix();
  24648. if (camera._alternateCamera) {
  24649. this.updateAlternateTransformMatrix(camera._alternateCamera);
  24650. this._alternateRendering = true;
  24651. }
  24652. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  24653. // Meshes
  24654. this._evaluateActiveMeshes();
  24655. // Software skinning
  24656. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  24657. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  24658. mesh.applySkeleton(mesh.skeleton);
  24659. }
  24660. // Render targets
  24661. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  24662. var needsRestoreFrameBuffer = false;
  24663. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  24664. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  24665. }
  24666. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  24667. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  24668. }
  24669. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  24670. this._intermediateRendering = true;
  24671. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  24672. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  24673. var renderTarget = this._renderTargets.data[renderIndex];
  24674. if (renderTarget._shouldRender()) {
  24675. this._renderId++;
  24676. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  24677. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  24678. }
  24679. }
  24680. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  24681. this._intermediateRendering = false;
  24682. this._renderId++;
  24683. needsRestoreFrameBuffer = true; // Restore back buffer
  24684. }
  24685. // Render EffecttLayer Texture
  24686. var stencilState = this._engine.getStencilBuffer();
  24687. var renderEffects = false;
  24688. var needStencil = false;
  24689. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  24690. this._intermediateRendering = true;
  24691. for (var i = 0; i < this.effectLayers.length; i++) {
  24692. var effectLayer = this.effectLayers[i];
  24693. if (effectLayer.shouldRender() &&
  24694. (!effectLayer.camera ||
  24695. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  24696. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  24697. renderEffects = true;
  24698. needStencil = needStencil || effectLayer.needStencil();
  24699. var renderTarget = effectLayer._mainTexture;
  24700. if (renderTarget._shouldRender()) {
  24701. this._renderId++;
  24702. renderTarget.render(false, false);
  24703. needsRestoreFrameBuffer = true;
  24704. }
  24705. }
  24706. }
  24707. this._intermediateRendering = false;
  24708. this._renderId++;
  24709. }
  24710. if (needsRestoreFrameBuffer) {
  24711. engine.restoreDefaultFramebuffer(); // Restore back buffer
  24712. }
  24713. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  24714. // Prepare Frame
  24715. this.postProcessManager._prepareFrame();
  24716. // Backgrounds
  24717. var layerIndex;
  24718. var layer;
  24719. if (this.layers.length) {
  24720. engine.setDepthBuffer(false);
  24721. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  24722. layer = this.layers[layerIndex];
  24723. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  24724. layer.render();
  24725. }
  24726. }
  24727. engine.setDepthBuffer(true);
  24728. }
  24729. // Activate effect Layer stencil
  24730. if (needStencil) {
  24731. this._engine.setStencilBuffer(true);
  24732. }
  24733. // Render
  24734. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  24735. this._renderingManager.render(null, null, true, true);
  24736. this.onAfterDrawPhaseObservable.notifyObservers(this);
  24737. // Restore effect Layer stencil
  24738. if (needStencil) {
  24739. this._engine.setStencilBuffer(stencilState);
  24740. }
  24741. // Bounding boxes
  24742. if (this._boundingBoxRenderer) {
  24743. this._boundingBoxRenderer.render();
  24744. }
  24745. // Lens flares
  24746. if (this.lensFlaresEnabled) {
  24747. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  24748. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  24749. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  24750. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  24751. lensFlareSystem.render();
  24752. }
  24753. }
  24754. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  24755. }
  24756. // Foregrounds
  24757. if (this.layers.length) {
  24758. engine.setDepthBuffer(false);
  24759. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  24760. layer = this.layers[layerIndex];
  24761. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  24762. layer.render();
  24763. }
  24764. }
  24765. engine.setDepthBuffer(true);
  24766. }
  24767. // Effect Layer
  24768. if (renderEffects) {
  24769. engine.setDepthBuffer(false);
  24770. for (var i = 0; i < this.effectLayers.length; i++) {
  24771. if (this.effectLayers[i].shouldRender()) {
  24772. this.effectLayers[i].render();
  24773. }
  24774. }
  24775. engine.setDepthBuffer(true);
  24776. }
  24777. // Finalize frame
  24778. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  24779. // Reset some special arrays
  24780. this._renderTargets.reset();
  24781. this._alternateRendering = false;
  24782. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  24783. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  24784. };
  24785. Scene.prototype._processSubCameras = function (camera) {
  24786. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  24787. this._renderForCamera(camera);
  24788. return;
  24789. }
  24790. // rig cameras
  24791. for (var index = 0; index < camera._rigCameras.length; index++) {
  24792. this._renderForCamera(camera._rigCameras[index], camera);
  24793. }
  24794. this.activeCamera = camera;
  24795. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  24796. };
  24797. Scene.prototype._checkIntersections = function () {
  24798. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  24799. var sourceMesh = this._meshesForIntersections.data[index];
  24800. if (!sourceMesh.actionManager) {
  24801. continue;
  24802. }
  24803. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  24804. var action = sourceMesh.actionManager.actions[actionIndex];
  24805. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24806. var parameters = action.getTriggerParameter();
  24807. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  24808. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  24809. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  24810. if (areIntersecting && currentIntersectionInProgress === -1) {
  24811. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  24812. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  24813. sourceMesh._intersectionsInProgress.push(otherMesh);
  24814. }
  24815. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24816. sourceMesh._intersectionsInProgress.push(otherMesh);
  24817. }
  24818. }
  24819. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  24820. //They intersected, and now they don't.
  24821. //is this trigger an exit trigger? execute an event.
  24822. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24823. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  24824. }
  24825. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  24826. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24827. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  24828. }
  24829. }
  24830. }
  24831. }
  24832. }
  24833. };
  24834. Scene.prototype.render = function () {
  24835. if (this.isDisposed) {
  24836. return;
  24837. }
  24838. this._activeParticles.fetchNewFrame();
  24839. this._totalVertices.fetchNewFrame();
  24840. this._activeIndices.fetchNewFrame();
  24841. this._activeBones.fetchNewFrame();
  24842. this._meshesForIntersections.reset();
  24843. this.resetCachedMaterial();
  24844. this.onBeforeAnimationsObservable.notifyObservers(this);
  24845. // Actions
  24846. if (this.actionManager) {
  24847. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  24848. }
  24849. //Simplification Queue
  24850. if (this.simplificationQueue && !this.simplificationQueue.running) {
  24851. this.simplificationQueue.executeNext();
  24852. }
  24853. if (this._engine.isDeterministicLockStep()) {
  24854. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  24855. var defaultFPS = (60.0 / 1000.0);
  24856. var defaultFrameTime = 1000 / 60; // frame time in MS
  24857. if (this._physicsEngine) {
  24858. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  24859. }
  24860. var stepsTaken = 0;
  24861. var maxSubSteps = this._engine.getLockstepMaxSteps();
  24862. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  24863. internalSteps = Math.min(internalSteps, maxSubSteps);
  24864. do {
  24865. this.onBeforeStepObservable.notifyObservers(this);
  24866. // Animations
  24867. this._animationRatio = defaultFrameTime * defaultFPS;
  24868. this._animate();
  24869. this.onAfterAnimationsObservable.notifyObservers(this);
  24870. // Physics
  24871. if (this._physicsEngine) {
  24872. this.onBeforePhysicsObservable.notifyObservers(this);
  24873. this._physicsEngine._step(defaultFrameTime / 1000);
  24874. this.onAfterPhysicsObservable.notifyObservers(this);
  24875. }
  24876. this.onAfterStepObservable.notifyObservers(this);
  24877. this._currentStepId++;
  24878. stepsTaken++;
  24879. deltaTime -= defaultFrameTime;
  24880. } while (deltaTime > 0 && stepsTaken < internalSteps);
  24881. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  24882. }
  24883. else {
  24884. // Animations
  24885. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  24886. this._animationRatio = deltaTime * (60.0 / 1000.0);
  24887. this._animate();
  24888. this.onAfterAnimationsObservable.notifyObservers(this);
  24889. // Physics
  24890. if (this._physicsEngine) {
  24891. this.onBeforePhysicsObservable.notifyObservers(this);
  24892. this._physicsEngine._step(deltaTime / 1000.0);
  24893. this.onAfterPhysicsObservable.notifyObservers(this);
  24894. }
  24895. }
  24896. // update gamepad manager
  24897. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  24898. this._gamepadManager._checkGamepadsStatus();
  24899. }
  24900. // Update Cameras
  24901. if (this.activeCameras.length > 0) {
  24902. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  24903. var camera = this.activeCameras[cameraIndex];
  24904. camera.update();
  24905. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  24906. // rig cameras
  24907. for (var index = 0; index < camera._rigCameras.length; index++) {
  24908. camera._rigCameras[index].update();
  24909. }
  24910. }
  24911. }
  24912. }
  24913. else if (this.activeCamera) {
  24914. this.activeCamera.update();
  24915. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  24916. // rig cameras
  24917. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  24918. this.activeCamera._rigCameras[index].update();
  24919. }
  24920. }
  24921. }
  24922. // Before render
  24923. this.onBeforeRenderObservable.notifyObservers(this);
  24924. // Customs render targets
  24925. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  24926. var engine = this.getEngine();
  24927. var currentActiveCamera = this.activeCamera;
  24928. if (this.renderTargetsEnabled) {
  24929. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  24930. this._intermediateRendering = true;
  24931. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  24932. var renderTarget = this.customRenderTargets[customIndex];
  24933. if (renderTarget._shouldRender()) {
  24934. this._renderId++;
  24935. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  24936. if (!this.activeCamera)
  24937. throw new Error("Active camera not set");
  24938. // Viewport
  24939. engine.setViewport(this.activeCamera.viewport);
  24940. // Camera
  24941. this.updateTransformMatrix();
  24942. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  24943. }
  24944. }
  24945. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  24946. this._intermediateRendering = false;
  24947. this._renderId++;
  24948. }
  24949. // Restore back buffer
  24950. if (this.customRenderTargets.length > 0) {
  24951. engine.restoreDefaultFramebuffer();
  24952. }
  24953. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  24954. this.activeCamera = currentActiveCamera;
  24955. // Procedural textures
  24956. if (this.proceduralTexturesEnabled) {
  24957. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  24958. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  24959. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  24960. if (proceduralTexture._shouldRender()) {
  24961. proceduralTexture.render();
  24962. }
  24963. }
  24964. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  24965. }
  24966. // Clear
  24967. if (this.autoClearDepthAndStencil || this.autoClear) {
  24968. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  24969. }
  24970. // Shadows
  24971. if (this.shadowsEnabled) {
  24972. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  24973. var light = this.lights[lightIndex];
  24974. var shadowGenerator = light.getShadowGenerator();
  24975. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  24976. var shadowMap = (shadowGenerator.getShadowMap());
  24977. if (this.textures.indexOf(shadowMap) !== -1) {
  24978. this._renderTargets.push(shadowMap);
  24979. }
  24980. }
  24981. }
  24982. }
  24983. // Depth renderer
  24984. for (var key in this._depthRenderer) {
  24985. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  24986. }
  24987. // Geometry renderer
  24988. if (this._geometryBufferRenderer) {
  24989. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  24990. }
  24991. // RenderPipeline
  24992. if (this._postProcessRenderPipelineManager) {
  24993. this._postProcessRenderPipelineManager.update();
  24994. }
  24995. // Multi-cameras?
  24996. if (this.activeCameras.length > 0) {
  24997. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  24998. if (cameraIndex > 0) {
  24999. this._engine.clear(null, false, true, true);
  25000. }
  25001. this._processSubCameras(this.activeCameras[cameraIndex]);
  25002. }
  25003. }
  25004. else {
  25005. if (!this.activeCamera) {
  25006. throw new Error("No camera defined");
  25007. }
  25008. this._processSubCameras(this.activeCamera);
  25009. }
  25010. // Intersection checks
  25011. this._checkIntersections();
  25012. // Update the audio listener attached to the camera
  25013. if (BABYLON.AudioEngine) {
  25014. this._updateAudioParameters();
  25015. }
  25016. // After render
  25017. if (this.afterRender) {
  25018. this.afterRender();
  25019. }
  25020. this.onAfterRenderObservable.notifyObservers(this);
  25021. // Cleaning
  25022. for (var index = 0; index < this._toBeDisposed.length; index++) {
  25023. var data = this._toBeDisposed.data[index];
  25024. if (data) {
  25025. data.dispose();
  25026. }
  25027. this._toBeDisposed[index] = null;
  25028. }
  25029. this._toBeDisposed.reset();
  25030. if (this.dumpNextRenderTargets) {
  25031. this.dumpNextRenderTargets = false;
  25032. }
  25033. this._activeBones.addCount(0, true);
  25034. this._activeIndices.addCount(0, true);
  25035. this._activeParticles.addCount(0, true);
  25036. };
  25037. Scene.prototype._updateAudioParameters = function () {
  25038. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  25039. return;
  25040. }
  25041. var listeningCamera;
  25042. var audioEngine = BABYLON.Engine.audioEngine;
  25043. if (this.activeCameras.length > 0) {
  25044. listeningCamera = this.activeCameras[0];
  25045. }
  25046. else {
  25047. listeningCamera = this.activeCamera;
  25048. }
  25049. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  25050. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  25051. // for VR cameras
  25052. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  25053. listeningCamera = listeningCamera.rigCameras[0];
  25054. }
  25055. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  25056. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  25057. cameraDirection.normalize();
  25058. // To avoid some errors on GearVR
  25059. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  25060. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  25061. }
  25062. var i;
  25063. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  25064. var sound = this.mainSoundTrack.soundCollection[i];
  25065. if (sound.useCustomAttenuation) {
  25066. sound.updateDistanceFromListener();
  25067. }
  25068. }
  25069. for (i = 0; i < this.soundTracks.length; i++) {
  25070. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  25071. sound = this.soundTracks[i].soundCollection[j];
  25072. if (sound.useCustomAttenuation) {
  25073. sound.updateDistanceFromListener();
  25074. }
  25075. }
  25076. }
  25077. }
  25078. };
  25079. Object.defineProperty(Scene.prototype, "audioEnabled", {
  25080. // Audio
  25081. get: function () {
  25082. return this._audioEnabled;
  25083. },
  25084. set: function (value) {
  25085. this._audioEnabled = value;
  25086. if (BABYLON.AudioEngine) {
  25087. if (this._audioEnabled) {
  25088. this._enableAudio();
  25089. }
  25090. else {
  25091. this._disableAudio();
  25092. }
  25093. }
  25094. },
  25095. enumerable: true,
  25096. configurable: true
  25097. });
  25098. Scene.prototype._disableAudio = function () {
  25099. var i;
  25100. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  25101. this.mainSoundTrack.soundCollection[i].pause();
  25102. }
  25103. for (i = 0; i < this.soundTracks.length; i++) {
  25104. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  25105. this.soundTracks[i].soundCollection[j].pause();
  25106. }
  25107. }
  25108. };
  25109. Scene.prototype._enableAudio = function () {
  25110. var i;
  25111. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  25112. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  25113. this.mainSoundTrack.soundCollection[i].play();
  25114. }
  25115. }
  25116. for (i = 0; i < this.soundTracks.length; i++) {
  25117. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  25118. if (this.soundTracks[i].soundCollection[j].isPaused) {
  25119. this.soundTracks[i].soundCollection[j].play();
  25120. }
  25121. }
  25122. }
  25123. };
  25124. Object.defineProperty(Scene.prototype, "headphone", {
  25125. get: function () {
  25126. return this._headphone;
  25127. },
  25128. set: function (value) {
  25129. this._headphone = value;
  25130. if (BABYLON.AudioEngine) {
  25131. if (this._headphone) {
  25132. this._switchAudioModeForHeadphones();
  25133. }
  25134. else {
  25135. this._switchAudioModeForNormalSpeakers();
  25136. }
  25137. }
  25138. },
  25139. enumerable: true,
  25140. configurable: true
  25141. });
  25142. Scene.prototype._switchAudioModeForHeadphones = function () {
  25143. this.mainSoundTrack.switchPanningModelToHRTF();
  25144. for (var i = 0; i < this.soundTracks.length; i++) {
  25145. this.soundTracks[i].switchPanningModelToHRTF();
  25146. }
  25147. };
  25148. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  25149. this.mainSoundTrack.switchPanningModelToEqualPower();
  25150. for (var i = 0; i < this.soundTracks.length; i++) {
  25151. this.soundTracks[i].switchPanningModelToEqualPower();
  25152. }
  25153. };
  25154. /**
  25155. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  25156. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  25157. * @returns the created depth renderer
  25158. */
  25159. Scene.prototype.enableDepthRenderer = function (camera) {
  25160. camera = camera || this.activeCamera;
  25161. if (!camera) {
  25162. throw "No camera available to enable depth renderer";
  25163. }
  25164. if (!this._depthRenderer[camera.id]) {
  25165. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, BABYLON.Engine.TEXTURETYPE_FLOAT, camera);
  25166. }
  25167. return this._depthRenderer[camera.id];
  25168. };
  25169. /**
  25170. * Disables a depth renderer for a given camera
  25171. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  25172. */
  25173. Scene.prototype.disableDepthRenderer = function (camera) {
  25174. camera = camera || this.activeCamera;
  25175. if (!camera || !this._depthRenderer[camera.id]) {
  25176. return;
  25177. }
  25178. this._depthRenderer[camera.id].dispose();
  25179. delete this._depthRenderer[camera.id];
  25180. };
  25181. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  25182. if (ratio === void 0) { ratio = 1; }
  25183. if (this._geometryBufferRenderer) {
  25184. return this._geometryBufferRenderer;
  25185. }
  25186. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  25187. if (!this._geometryBufferRenderer.isSupported) {
  25188. this._geometryBufferRenderer = null;
  25189. }
  25190. return this._geometryBufferRenderer;
  25191. };
  25192. Scene.prototype.disableGeometryBufferRenderer = function () {
  25193. if (!this._geometryBufferRenderer) {
  25194. return;
  25195. }
  25196. this._geometryBufferRenderer.dispose();
  25197. this._geometryBufferRenderer = null;
  25198. };
  25199. Scene.prototype.freezeMaterials = function () {
  25200. for (var i = 0; i < this.materials.length; i++) {
  25201. this.materials[i].freeze();
  25202. }
  25203. };
  25204. Scene.prototype.unfreezeMaterials = function () {
  25205. for (var i = 0; i < this.materials.length; i++) {
  25206. this.materials[i].unfreeze();
  25207. }
  25208. };
  25209. Scene.prototype.dispose = function () {
  25210. this.beforeRender = null;
  25211. this.afterRender = null;
  25212. this.skeletons = [];
  25213. this.morphTargetManagers = [];
  25214. this.importedMeshesFiles = new Array();
  25215. this.stopAllAnimations();
  25216. this.resetCachedMaterial();
  25217. for (var key in this._depthRenderer) {
  25218. this._depthRenderer[key].dispose();
  25219. }
  25220. if (this._gamepadManager) {
  25221. this._gamepadManager.dispose();
  25222. this._gamepadManager = null;
  25223. }
  25224. // Smart arrays
  25225. if (this.activeCamera) {
  25226. this.activeCamera._activeMeshes.dispose();
  25227. this.activeCamera = null;
  25228. }
  25229. this._activeMeshes.dispose();
  25230. this._renderingManager.dispose();
  25231. this._processedMaterials.dispose();
  25232. this._activeParticleSystems.dispose();
  25233. this._activeSkeletons.dispose();
  25234. this._softwareSkinnedMeshes.dispose();
  25235. this._renderTargets.dispose();
  25236. this._registeredForLateAnimationBindings.dispose();
  25237. if (this._boundingBoxRenderer) {
  25238. this._boundingBoxRenderer.dispose();
  25239. }
  25240. this._meshesForIntersections.dispose();
  25241. this._toBeDisposed.dispose();
  25242. // Abort active requests
  25243. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  25244. var request = _a[_i];
  25245. request.abort();
  25246. }
  25247. // Debug layer
  25248. if (this._debugLayer) {
  25249. this._debugLayer.hide();
  25250. }
  25251. // Events
  25252. this.onDisposeObservable.notifyObservers(this);
  25253. this.onDisposeObservable.clear();
  25254. this.onBeforeRenderObservable.clear();
  25255. this.onAfterRenderObservable.clear();
  25256. this.OnBeforeRenderTargetsRenderObservable.clear();
  25257. this.OnAfterRenderTargetsRenderObservable.clear();
  25258. this.onAfterStepObservable.clear();
  25259. this.onBeforeStepObservable.clear();
  25260. this.onBeforeActiveMeshesEvaluationObservable.clear();
  25261. this.onAfterActiveMeshesEvaluationObservable.clear();
  25262. this.onBeforeParticlesRenderingObservable.clear();
  25263. this.onAfterParticlesRenderingObservable.clear();
  25264. this.onBeforeSpritesRenderingObservable.clear();
  25265. this.onAfterSpritesRenderingObservable.clear();
  25266. this.onBeforeDrawPhaseObservable.clear();
  25267. this.onAfterDrawPhaseObservable.clear();
  25268. this.onBeforePhysicsObservable.clear();
  25269. this.onAfterPhysicsObservable.clear();
  25270. this.onBeforeAnimationsObservable.clear();
  25271. this.onAfterAnimationsObservable.clear();
  25272. this.onDataLoadedObservable.clear();
  25273. this.detachControl();
  25274. // Release sounds & sounds tracks
  25275. if (BABYLON.AudioEngine) {
  25276. this.disposeSounds();
  25277. }
  25278. // VR Helper
  25279. if (this.VRHelper) {
  25280. this.VRHelper.dispose();
  25281. }
  25282. // Detach cameras
  25283. var canvas = this._engine.getRenderingCanvas();
  25284. if (canvas) {
  25285. var index;
  25286. for (index = 0; index < this.cameras.length; index++) {
  25287. this.cameras[index].detachControl(canvas);
  25288. }
  25289. }
  25290. // Release animation groups
  25291. while (this.animationGroups.length) {
  25292. this.animationGroups[0].dispose();
  25293. }
  25294. // Release lights
  25295. while (this.lights.length) {
  25296. this.lights[0].dispose();
  25297. }
  25298. // Release meshes
  25299. while (this.meshes.length) {
  25300. this.meshes[0].dispose(true);
  25301. }
  25302. while (this.transformNodes.length) {
  25303. this.removeTransformNode(this.transformNodes[0]);
  25304. }
  25305. // Release cameras
  25306. while (this.cameras.length) {
  25307. this.cameras[0].dispose();
  25308. }
  25309. // Release materials
  25310. if (this.defaultMaterial) {
  25311. this.defaultMaterial.dispose();
  25312. }
  25313. while (this.multiMaterials.length) {
  25314. this.multiMaterials[0].dispose();
  25315. }
  25316. while (this.materials.length) {
  25317. this.materials[0].dispose();
  25318. }
  25319. // Release particles
  25320. while (this.particleSystems.length) {
  25321. this.particleSystems[0].dispose();
  25322. }
  25323. // Release sprites
  25324. while (this.spriteManagers.length) {
  25325. this.spriteManagers[0].dispose();
  25326. }
  25327. // Release postProcesses
  25328. while (this.postProcesses.length) {
  25329. this.postProcesses[0].dispose();
  25330. }
  25331. // Release layers
  25332. while (this.layers.length) {
  25333. this.layers[0].dispose();
  25334. }
  25335. while (this.effectLayers.length) {
  25336. this.effectLayers[0].dispose();
  25337. }
  25338. // Release textures
  25339. while (this.textures.length) {
  25340. this.textures[0].dispose();
  25341. }
  25342. // Release UBO
  25343. this._sceneUbo.dispose();
  25344. if (this._alternateSceneUbo) {
  25345. this._alternateSceneUbo.dispose();
  25346. }
  25347. // Post-processes
  25348. this.postProcessManager.dispose();
  25349. if (this._postProcessRenderPipelineManager) {
  25350. this._postProcessRenderPipelineManager.dispose();
  25351. }
  25352. // Physics
  25353. if (this._physicsEngine) {
  25354. this.disablePhysicsEngine();
  25355. }
  25356. // Remove from engine
  25357. index = this._engine.scenes.indexOf(this);
  25358. if (index > -1) {
  25359. this._engine.scenes.splice(index, 1);
  25360. }
  25361. this._engine.wipeCaches(true);
  25362. this._isDisposed = true;
  25363. };
  25364. Object.defineProperty(Scene.prototype, "isDisposed", {
  25365. get: function () {
  25366. return this._isDisposed;
  25367. },
  25368. enumerable: true,
  25369. configurable: true
  25370. });
  25371. // Release sounds & sounds tracks
  25372. Scene.prototype.disposeSounds = function () {
  25373. if (!this._mainSoundTrack) {
  25374. return;
  25375. }
  25376. this.mainSoundTrack.dispose();
  25377. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  25378. this.soundTracks[scIndex].dispose();
  25379. }
  25380. };
  25381. // Octrees
  25382. /**
  25383. * Get the world extend vectors with an optional filter
  25384. *
  25385. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  25386. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  25387. */
  25388. Scene.prototype.getWorldExtends = function (filterPredicate) {
  25389. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  25390. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  25391. filterPredicate = filterPredicate || (function () { return true; });
  25392. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  25393. mesh.computeWorldMatrix(true);
  25394. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  25395. return;
  25396. }
  25397. var boundingInfo = mesh.getBoundingInfo();
  25398. var minBox = boundingInfo.boundingBox.minimumWorld;
  25399. var maxBox = boundingInfo.boundingBox.maximumWorld;
  25400. BABYLON.Tools.CheckExtends(minBox, min, max);
  25401. BABYLON.Tools.CheckExtends(maxBox, min, max);
  25402. });
  25403. return {
  25404. min: min,
  25405. max: max
  25406. };
  25407. };
  25408. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  25409. if (maxCapacity === void 0) { maxCapacity = 64; }
  25410. if (maxDepth === void 0) { maxDepth = 2; }
  25411. if (!this._selectionOctree) {
  25412. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  25413. }
  25414. var worldExtends = this.getWorldExtends();
  25415. // Update octree
  25416. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  25417. return this._selectionOctree;
  25418. };
  25419. // Picking
  25420. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  25421. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  25422. var result = BABYLON.Ray.Zero();
  25423. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  25424. return result;
  25425. };
  25426. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  25427. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  25428. var engine = this._engine;
  25429. if (!camera) {
  25430. if (!this.activeCamera)
  25431. throw new Error("Active camera not set");
  25432. camera = this.activeCamera;
  25433. }
  25434. var cameraViewport = camera.viewport;
  25435. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  25436. // Moving coordinates to local viewport world
  25437. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  25438. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  25439. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  25440. return this;
  25441. };
  25442. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  25443. var result = BABYLON.Ray.Zero();
  25444. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  25445. return result;
  25446. };
  25447. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  25448. if (!BABYLON.PickingInfo) {
  25449. return this;
  25450. }
  25451. var engine = this._engine;
  25452. if (!camera) {
  25453. if (!this.activeCamera)
  25454. throw new Error("Active camera not set");
  25455. camera = this.activeCamera;
  25456. }
  25457. var cameraViewport = camera.viewport;
  25458. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  25459. var identity = BABYLON.Matrix.Identity();
  25460. // Moving coordinates to local viewport world
  25461. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  25462. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  25463. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  25464. return this;
  25465. };
  25466. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  25467. if (!BABYLON.PickingInfo) {
  25468. return null;
  25469. }
  25470. var pickingInfo = null;
  25471. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  25472. var mesh = this.meshes[meshIndex];
  25473. if (predicate) {
  25474. if (!predicate(mesh)) {
  25475. continue;
  25476. }
  25477. }
  25478. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  25479. continue;
  25480. }
  25481. var world = mesh.getWorldMatrix();
  25482. var ray = rayFunction(world);
  25483. var result = mesh.intersects(ray, fastCheck);
  25484. if (!result || !result.hit)
  25485. continue;
  25486. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  25487. continue;
  25488. pickingInfo = result;
  25489. if (fastCheck) {
  25490. break;
  25491. }
  25492. }
  25493. return pickingInfo || new BABYLON.PickingInfo();
  25494. };
  25495. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  25496. if (!BABYLON.PickingInfo) {
  25497. return null;
  25498. }
  25499. var pickingInfos = new Array();
  25500. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  25501. var mesh = this.meshes[meshIndex];
  25502. if (predicate) {
  25503. if (!predicate(mesh)) {
  25504. continue;
  25505. }
  25506. }
  25507. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  25508. continue;
  25509. }
  25510. var world = mesh.getWorldMatrix();
  25511. var ray = rayFunction(world);
  25512. var result = mesh.intersects(ray, false);
  25513. if (!result || !result.hit)
  25514. continue;
  25515. pickingInfos.push(result);
  25516. }
  25517. return pickingInfos;
  25518. };
  25519. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  25520. if (!BABYLON.PickingInfo) {
  25521. return null;
  25522. }
  25523. var pickingInfo = null;
  25524. if (!camera) {
  25525. if (!this.activeCamera) {
  25526. return null;
  25527. }
  25528. camera = this.activeCamera;
  25529. }
  25530. if (this.spriteManagers.length > 0) {
  25531. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  25532. var spriteManager = this.spriteManagers[spriteIndex];
  25533. if (!spriteManager.isPickable) {
  25534. continue;
  25535. }
  25536. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  25537. if (!result || !result.hit)
  25538. continue;
  25539. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  25540. continue;
  25541. pickingInfo = result;
  25542. if (fastCheck) {
  25543. break;
  25544. }
  25545. }
  25546. }
  25547. return pickingInfo || new BABYLON.PickingInfo();
  25548. };
  25549. /** Launch a ray to try to pick a mesh in the scene
  25550. * @param x position on screen
  25551. * @param y position on screen
  25552. * @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
  25553. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  25554. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  25555. */
  25556. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  25557. var _this = this;
  25558. if (!BABYLON.PickingInfo) {
  25559. return null;
  25560. }
  25561. return this._internalPick(function (world) {
  25562. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  25563. return _this._tempPickingRay;
  25564. }, predicate, fastCheck);
  25565. };
  25566. /** Launch a ray to try to pick a sprite in the scene
  25567. * @param x position on screen
  25568. * @param y position on screen
  25569. * @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
  25570. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  25571. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  25572. */
  25573. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  25574. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  25575. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  25576. };
  25577. /** Use the given ray to pick a mesh in the scene
  25578. * @param ray The ray to use to pick meshes
  25579. * @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
  25580. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  25581. */
  25582. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  25583. var _this = this;
  25584. return this._internalPick(function (world) {
  25585. if (!_this._pickWithRayInverseMatrix) {
  25586. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  25587. }
  25588. world.invertToRef(_this._pickWithRayInverseMatrix);
  25589. if (!_this._cachedRayForTransform) {
  25590. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  25591. }
  25592. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  25593. return _this._cachedRayForTransform;
  25594. }, predicate, fastCheck);
  25595. };
  25596. /**
  25597. * Launch a ray to try to pick a mesh in the scene
  25598. * @param x X position on screen
  25599. * @param y Y position on screen
  25600. * @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
  25601. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  25602. */
  25603. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  25604. var _this = this;
  25605. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  25606. };
  25607. /**
  25608. * Launch a ray to try to pick a mesh in the scene
  25609. * @param ray Ray to use
  25610. * @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
  25611. */
  25612. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  25613. var _this = this;
  25614. return this._internalMultiPick(function (world) {
  25615. if (!_this._pickWithRayInverseMatrix) {
  25616. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  25617. }
  25618. world.invertToRef(_this._pickWithRayInverseMatrix);
  25619. if (!_this._cachedRayForTransform) {
  25620. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  25621. }
  25622. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  25623. return _this._cachedRayForTransform;
  25624. }, predicate);
  25625. };
  25626. Scene.prototype.setPointerOverMesh = function (mesh) {
  25627. if (this._pointerOverMesh === mesh) {
  25628. return;
  25629. }
  25630. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  25631. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  25632. }
  25633. this._pointerOverMesh = mesh;
  25634. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  25635. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  25636. }
  25637. };
  25638. Scene.prototype.getPointerOverMesh = function () {
  25639. return this._pointerOverMesh;
  25640. };
  25641. Scene.prototype.setPointerOverSprite = function (sprite) {
  25642. if (this._pointerOverSprite === sprite) {
  25643. return;
  25644. }
  25645. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  25646. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  25647. }
  25648. this._pointerOverSprite = sprite;
  25649. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  25650. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  25651. }
  25652. };
  25653. Scene.prototype.getPointerOverSprite = function () {
  25654. return this._pointerOverSprite;
  25655. };
  25656. // Physics
  25657. Scene.prototype.getPhysicsEngine = function () {
  25658. return this._physicsEngine;
  25659. };
  25660. /**
  25661. * Enables physics to the current scene
  25662. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  25663. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  25664. * @return {boolean} was the physics engine initialized
  25665. */
  25666. Scene.prototype.enablePhysics = function (gravity, plugin) {
  25667. if (gravity === void 0) { gravity = null; }
  25668. if (this._physicsEngine) {
  25669. return true;
  25670. }
  25671. try {
  25672. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  25673. return true;
  25674. }
  25675. catch (e) {
  25676. BABYLON.Tools.Error(e.message);
  25677. return false;
  25678. }
  25679. };
  25680. Scene.prototype.disablePhysicsEngine = function () {
  25681. if (!this._physicsEngine) {
  25682. return;
  25683. }
  25684. this._physicsEngine.dispose();
  25685. this._physicsEngine = null;
  25686. };
  25687. Scene.prototype.isPhysicsEnabled = function () {
  25688. return this._physicsEngine !== undefined;
  25689. };
  25690. Scene.prototype.deleteCompoundImpostor = function (compound) {
  25691. var mesh = compound.parts[0].mesh;
  25692. if (mesh.physicsImpostor) {
  25693. mesh.physicsImpostor.dispose();
  25694. mesh.physicsImpostor = null;
  25695. }
  25696. };
  25697. // Misc.
  25698. Scene.prototype._rebuildGeometries = function () {
  25699. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  25700. var geometry = _a[_i];
  25701. geometry._rebuild();
  25702. }
  25703. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  25704. var mesh = _c[_b];
  25705. mesh._rebuild();
  25706. }
  25707. if (this.postProcessManager) {
  25708. this.postProcessManager._rebuild();
  25709. }
  25710. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  25711. var layer = _e[_d];
  25712. layer._rebuild();
  25713. }
  25714. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  25715. var effectLayer = _g[_f];
  25716. effectLayer._rebuild();
  25717. }
  25718. if (this._boundingBoxRenderer) {
  25719. this._boundingBoxRenderer._rebuild();
  25720. }
  25721. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  25722. var system = _j[_h];
  25723. system.rebuild();
  25724. }
  25725. if (this._postProcessRenderPipelineManager) {
  25726. this._postProcessRenderPipelineManager._rebuild();
  25727. }
  25728. };
  25729. Scene.prototype._rebuildTextures = function () {
  25730. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  25731. var texture = _a[_i];
  25732. texture._rebuild();
  25733. }
  25734. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  25735. };
  25736. /**
  25737. * Creates a default light for the scene.
  25738. * @param replace Whether to replace the existing lights in the scene.
  25739. */
  25740. Scene.prototype.createDefaultLight = function (replace) {
  25741. if (replace === void 0) { replace = false; }
  25742. // Dispose existing light in replace mode.
  25743. if (replace) {
  25744. if (this.lights) {
  25745. for (var i = 0; i < this.lights.length; i++) {
  25746. this.lights[i].dispose();
  25747. }
  25748. }
  25749. }
  25750. // Light
  25751. if (this.lights.length === 0) {
  25752. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  25753. }
  25754. };
  25755. /**
  25756. * Creates a default camera for the scene.
  25757. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  25758. * @param replace Whether to replace the existing active camera in the scene.
  25759. * @param attachCameraControls Whether to attach camera controls to the canvas.
  25760. */
  25761. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  25762. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  25763. if (replace === void 0) { replace = false; }
  25764. if (attachCameraControls === void 0) { attachCameraControls = false; }
  25765. // Dispose existing camera in replace mode.
  25766. if (replace) {
  25767. if (this.activeCamera) {
  25768. this.activeCamera.dispose();
  25769. this.activeCamera = null;
  25770. }
  25771. }
  25772. // Camera
  25773. if (!this.activeCamera) {
  25774. var worldExtends = this.getWorldExtends();
  25775. var worldSize = worldExtends.max.subtract(worldExtends.min);
  25776. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  25777. var camera;
  25778. var radius = worldSize.length() * 1.5;
  25779. // empty scene scenario!
  25780. if (!isFinite(radius)) {
  25781. radius = 1;
  25782. worldCenter.copyFromFloats(0, 0, 0);
  25783. }
  25784. if (createArcRotateCamera) {
  25785. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  25786. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  25787. arcRotateCamera.wheelPrecision = 100 / radius;
  25788. camera = arcRotateCamera;
  25789. }
  25790. else {
  25791. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  25792. freeCamera.setTarget(worldCenter);
  25793. camera = freeCamera;
  25794. }
  25795. camera.minZ = radius * 0.01;
  25796. camera.maxZ = radius * 1000;
  25797. camera.speed = radius * 0.2;
  25798. this.activeCamera = camera;
  25799. var canvas = this.getEngine().getRenderingCanvas();
  25800. if (attachCameraControls && canvas) {
  25801. camera.attachControl(canvas);
  25802. }
  25803. }
  25804. };
  25805. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  25806. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  25807. if (replace === void 0) { replace = false; }
  25808. if (attachCameraControls === void 0) { attachCameraControls = false; }
  25809. this.createDefaultLight(replace);
  25810. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  25811. };
  25812. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  25813. if (pbr === void 0) { pbr = false; }
  25814. if (scale === void 0) { scale = 1000; }
  25815. if (blur === void 0) { blur = 0; }
  25816. if (environmentTexture) {
  25817. this.environmentTexture = environmentTexture;
  25818. }
  25819. if (!this.environmentTexture) {
  25820. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  25821. return null;
  25822. }
  25823. // Skybox
  25824. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  25825. if (pbr) {
  25826. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  25827. hdrSkyboxMaterial.backFaceCulling = false;
  25828. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  25829. if (hdrSkyboxMaterial.reflectionTexture) {
  25830. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  25831. }
  25832. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  25833. hdrSkyboxMaterial.disableLighting = true;
  25834. hdrSkyboxMaterial.twoSidedLighting = true;
  25835. hdrSkybox.infiniteDistance = true;
  25836. hdrSkybox.material = hdrSkyboxMaterial;
  25837. }
  25838. else {
  25839. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  25840. skyboxMaterial.backFaceCulling = false;
  25841. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  25842. if (skyboxMaterial.reflectionTexture) {
  25843. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  25844. }
  25845. skyboxMaterial.disableLighting = true;
  25846. hdrSkybox.infiniteDistance = true;
  25847. hdrSkybox.material = skyboxMaterial;
  25848. }
  25849. return hdrSkybox;
  25850. };
  25851. Scene.prototype.createDefaultEnvironment = function (options) {
  25852. if (BABYLON.EnvironmentHelper) {
  25853. return new BABYLON.EnvironmentHelper(options, this);
  25854. }
  25855. return null;
  25856. };
  25857. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  25858. if (webVROptions === void 0) { webVROptions = {}; }
  25859. return new BABYLON.VRExperienceHelper(this, webVROptions);
  25860. };
  25861. // Tags
  25862. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  25863. if (tagsQuery === undefined) {
  25864. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  25865. return list;
  25866. }
  25867. var listByTags = [];
  25868. forEach = forEach || (function (item) { return; });
  25869. for (var i in list) {
  25870. var item = list[i];
  25871. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  25872. listByTags.push(item);
  25873. forEach(item);
  25874. }
  25875. }
  25876. return listByTags;
  25877. };
  25878. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  25879. return this._getByTags(this.meshes, tagsQuery, forEach);
  25880. };
  25881. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  25882. return this._getByTags(this.cameras, tagsQuery, forEach);
  25883. };
  25884. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  25885. return this._getByTags(this.lights, tagsQuery, forEach);
  25886. };
  25887. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  25888. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  25889. };
  25890. /**
  25891. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  25892. * This allowed control for front to back rendering or reversly depending of the special needs.
  25893. *
  25894. * @param renderingGroupId The rendering group id corresponding to its index
  25895. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  25896. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  25897. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  25898. */
  25899. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  25900. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  25901. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  25902. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  25903. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  25904. };
  25905. /**
  25906. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  25907. *
  25908. * @param renderingGroupId The rendering group id corresponding to its index
  25909. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  25910. * @param depth Automatically clears depth between groups if true and autoClear is true.
  25911. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  25912. */
  25913. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  25914. if (depth === void 0) { depth = true; }
  25915. if (stencil === void 0) { stencil = true; }
  25916. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  25917. };
  25918. /**
  25919. * Will flag all materials as dirty to trigger new shader compilation
  25920. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  25921. */
  25922. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  25923. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  25924. var material = _a[_i];
  25925. if (predicate && !predicate(material)) {
  25926. continue;
  25927. }
  25928. material.markAsDirty(flag);
  25929. }
  25930. };
  25931. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  25932. var _this = this;
  25933. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  25934. this._activeRequests.push(request);
  25935. request.onCompleteObservable.add(function (request) {
  25936. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  25937. });
  25938. return request;
  25939. };
  25940. /** @ignore */
  25941. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  25942. var _this = this;
  25943. return new Promise(function (resolve, reject) {
  25944. _this._loadFile(url, function (data) {
  25945. resolve(data);
  25946. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  25947. reject(exception);
  25948. });
  25949. });
  25950. };
  25951. // Statics
  25952. Scene._FOGMODE_NONE = 0;
  25953. Scene._FOGMODE_EXP = 1;
  25954. Scene._FOGMODE_EXP2 = 2;
  25955. Scene._FOGMODE_LINEAR = 3;
  25956. Scene._uniqueIdCounter = 0;
  25957. Scene.MinDeltaTime = 1.0;
  25958. Scene.MaxDeltaTime = 1000.0;
  25959. /** The distance in pixel that you have to move to prevent some events */
  25960. Scene.DragMovementThreshold = 10; // in pixels
  25961. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  25962. Scene.LongPressDelay = 500; // in milliseconds
  25963. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  25964. Scene.DoubleClickDelay = 300; // in milliseconds
  25965. /** If you need to check double click without raising a single click at first click, enable this flag */
  25966. Scene.ExclusiveDoubleClickMode = false;
  25967. return Scene;
  25968. }());
  25969. BABYLON.Scene = Scene;
  25970. })(BABYLON || (BABYLON = {}));
  25971. //# sourceMappingURL=babylon.scene.js.map
  25972. "use strict";
  25973. var BABYLON;
  25974. (function (BABYLON) {
  25975. /**
  25976. * Set of assets to keep when moving a scene into an asset container.
  25977. */
  25978. var KeepAssets = /** @class */ (function () {
  25979. function KeepAssets() {
  25980. /**
  25981. * Cameras to keep.
  25982. */
  25983. this.cameras = new Array();
  25984. /**
  25985. * Lights to keep.
  25986. */
  25987. this.lights = new Array();
  25988. /**
  25989. * Meshes to keep.
  25990. */
  25991. this.meshes = new Array();
  25992. /**
  25993. * Skeletons to keep.
  25994. */
  25995. this.skeletons = new Array();
  25996. /**
  25997. * ParticleSystems to keep.
  25998. */
  25999. this.particleSystems = new Array();
  26000. /**
  26001. * Animations to keep.
  26002. */
  26003. this.animations = new Array();
  26004. /**
  26005. * MultiMaterials to keep.
  26006. */
  26007. this.multiMaterials = new Array();
  26008. /**
  26009. * Materials to keep.
  26010. */
  26011. this.materials = new Array();
  26012. /**
  26013. * MorphTargetManagers to keep.
  26014. */
  26015. this.morphTargetManagers = new Array();
  26016. /**
  26017. * Geometries to keep.
  26018. */
  26019. this.geometries = new Array();
  26020. /**
  26021. * TransformNodes to keep.
  26022. */
  26023. this.transformNodes = new Array();
  26024. /**
  26025. * LensFlareSystems to keep.
  26026. */
  26027. this.lensFlareSystems = new Array();
  26028. /**
  26029. * ShadowGenerators to keep.
  26030. */
  26031. this.shadowGenerators = new Array();
  26032. /**
  26033. * ActionManagers to keep.
  26034. */
  26035. this.actionManagers = new Array();
  26036. /**
  26037. * Sounds to keep.
  26038. */
  26039. this.sounds = new Array();
  26040. }
  26041. return KeepAssets;
  26042. }());
  26043. BABYLON.KeepAssets = KeepAssets;
  26044. /**
  26045. * Container with a set of assets that can be added or removed from a scene.
  26046. */
  26047. var AssetContainer = /** @class */ (function () {
  26048. /**
  26049. * Instantiates an AssetContainer.
  26050. * @param scene The scene the AssetContainer belongs to.
  26051. */
  26052. function AssetContainer(scene) {
  26053. // Objects
  26054. /**
  26055. * Cameras populated in the container.
  26056. */
  26057. this.cameras = new Array();
  26058. /**
  26059. * Lights populated in the container.
  26060. */
  26061. this.lights = new Array();
  26062. /**
  26063. * Meshes populated in the container.
  26064. */
  26065. this.meshes = new Array();
  26066. /**
  26067. * Skeletons populated in the container.
  26068. */
  26069. this.skeletons = new Array();
  26070. /**
  26071. * ParticleSystems populated in the container.
  26072. */
  26073. this.particleSystems = new Array();
  26074. /**
  26075. * Animations populated in the container.
  26076. */
  26077. this.animations = new Array();
  26078. /**
  26079. * MultiMaterials populated in the container.
  26080. */
  26081. this.multiMaterials = new Array();
  26082. /**
  26083. * Materials populated in the container.
  26084. */
  26085. this.materials = new Array();
  26086. /**
  26087. * MorphTargetManagers populated in the container.
  26088. */
  26089. this.morphTargetManagers = new Array();
  26090. /**
  26091. * Geometries populated in the container.
  26092. */
  26093. this.geometries = new Array();
  26094. /**
  26095. * TransformNodes populated in the container.
  26096. */
  26097. this.transformNodes = new Array();
  26098. /**
  26099. * LensFlareSystems populated in the container.
  26100. */
  26101. this.lensFlareSystems = new Array();
  26102. /**
  26103. * ShadowGenerators populated in the container.
  26104. */
  26105. this.shadowGenerators = new Array();
  26106. /**
  26107. * ActionManagers populated in the container.
  26108. */
  26109. this.actionManagers = new Array();
  26110. /**
  26111. * Sounds populated in the container.
  26112. */
  26113. this.sounds = new Array();
  26114. this.scene = scene;
  26115. }
  26116. /**
  26117. * Adds all the assets from the container to the scene.
  26118. */
  26119. AssetContainer.prototype.addAllToScene = function () {
  26120. var _this = this;
  26121. this.cameras.forEach(function (o) {
  26122. _this.scene.addCamera(o);
  26123. });
  26124. this.lights.forEach(function (o) {
  26125. _this.scene.addLight(o);
  26126. });
  26127. this.meshes.forEach(function (o) {
  26128. _this.scene.addMesh(o);
  26129. });
  26130. this.skeletons.forEach(function (o) {
  26131. _this.scene.addSkeleton(o);
  26132. });
  26133. this.particleSystems.forEach(function (o) {
  26134. _this.scene.addParticleSystem(o);
  26135. });
  26136. this.animations.forEach(function (o) {
  26137. _this.scene.addAnimation(o);
  26138. });
  26139. this.multiMaterials.forEach(function (o) {
  26140. _this.scene.addMultiMaterial(o);
  26141. });
  26142. this.materials.forEach(function (o) {
  26143. _this.scene.addMaterial(o);
  26144. });
  26145. this.morphTargetManagers.forEach(function (o) {
  26146. _this.scene.addMorphTargetManager(o);
  26147. });
  26148. this.geometries.forEach(function (o) {
  26149. _this.scene.addGeometry(o);
  26150. });
  26151. this.transformNodes.forEach(function (o) {
  26152. _this.scene.addTransformNode(o);
  26153. });
  26154. this.lensFlareSystems.forEach(function (o) {
  26155. _this.scene.addLensFlareSystem(o);
  26156. });
  26157. this.actionManagers.forEach(function (o) {
  26158. _this.scene.addActionManager(o);
  26159. });
  26160. this.sounds.forEach(function (o) {
  26161. o.play();
  26162. o.autoplay = true;
  26163. _this.scene.mainSoundTrack.AddSound(o);
  26164. });
  26165. };
  26166. /**
  26167. * Removes all the assets in the container from the scene
  26168. */
  26169. AssetContainer.prototype.removeAllFromScene = function () {
  26170. var _this = this;
  26171. this.cameras.forEach(function (o) {
  26172. _this.scene.removeCamera(o);
  26173. });
  26174. this.lights.forEach(function (o) {
  26175. _this.scene.removeLight(o);
  26176. });
  26177. this.meshes.forEach(function (o) {
  26178. _this.scene.removeMesh(o);
  26179. });
  26180. this.skeletons.forEach(function (o) {
  26181. _this.scene.removeSkeleton(o);
  26182. });
  26183. this.particleSystems.forEach(function (o) {
  26184. _this.scene.removeParticleSystem(o);
  26185. });
  26186. this.animations.forEach(function (o) {
  26187. _this.scene.removeAnimation(o);
  26188. });
  26189. this.multiMaterials.forEach(function (o) {
  26190. _this.scene.removeMultiMaterial(o);
  26191. });
  26192. this.materials.forEach(function (o) {
  26193. _this.scene.removeMaterial(o);
  26194. });
  26195. this.morphTargetManagers.forEach(function (o) {
  26196. _this.scene.removeMorphTargetManager(o);
  26197. });
  26198. this.geometries.forEach(function (o) {
  26199. _this.scene.removeGeometry(o);
  26200. });
  26201. this.transformNodes.forEach(function (o) {
  26202. _this.scene.removeTransformNode(o);
  26203. });
  26204. this.lensFlareSystems.forEach(function (o) {
  26205. _this.scene.removeLensFlareSystem(o);
  26206. });
  26207. this.actionManagers.forEach(function (o) {
  26208. _this.scene.removeActionManager(o);
  26209. });
  26210. this.sounds.forEach(function (o) {
  26211. o.stop();
  26212. o.autoplay = false;
  26213. _this.scene.mainSoundTrack.RemoveSound(o);
  26214. });
  26215. };
  26216. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  26217. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  26218. var asset = sourceAssets_1[_i];
  26219. var move = true;
  26220. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  26221. var keepAsset = keepAssets_1[_a];
  26222. if (asset === keepAsset) {
  26223. move = false;
  26224. break;
  26225. }
  26226. }
  26227. if (move) {
  26228. targetAssets.push(asset);
  26229. }
  26230. }
  26231. };
  26232. /**
  26233. * Removes all the assets contained in the scene and adds them to the container.
  26234. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  26235. */
  26236. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  26237. if (keepAssets === undefined) {
  26238. keepAssets = new KeepAssets();
  26239. }
  26240. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  26241. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  26242. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  26243. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  26244. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  26245. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  26246. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  26247. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  26248. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  26249. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  26250. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  26251. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  26252. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  26253. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  26254. this.removeAllFromScene();
  26255. };
  26256. return AssetContainer;
  26257. }());
  26258. BABYLON.AssetContainer = AssetContainer;
  26259. })(BABYLON || (BABYLON = {}));
  26260. //# sourceMappingURL=babylon.assetContainer.js.map
  26261. "use strict";
  26262. var BABYLON;
  26263. (function (BABYLON) {
  26264. var Buffer = /** @class */ (function () {
  26265. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  26266. if (instanced === void 0) { instanced = false; }
  26267. if (engine instanceof BABYLON.Mesh) {
  26268. this._engine = engine.getScene().getEngine();
  26269. }
  26270. else {
  26271. this._engine = engine;
  26272. }
  26273. this._updatable = updatable;
  26274. this._instanced = instanced;
  26275. this._data = data;
  26276. this._strideSize = stride;
  26277. if (!postponeInternalCreation) {
  26278. this.create();
  26279. }
  26280. }
  26281. /**
  26282. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  26283. * @param kind defines the vertex buffer kind (position, normal, etc.)
  26284. * @param offset defines offset in the buffer (0 by default)
  26285. * @param size defines the size in floats of attributes (position is 3 for instance)
  26286. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  26287. * @param instanced defines if the vertex buffer contains indexed data
  26288. * @returns the new vertex buffer
  26289. */
  26290. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced) {
  26291. // a lot of these parameters are ignored as they are overriden by the buffer
  26292. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, instanced === undefined ? this._instanced : instanced, offset, size);
  26293. };
  26294. // Properties
  26295. Buffer.prototype.isUpdatable = function () {
  26296. return this._updatable;
  26297. };
  26298. Buffer.prototype.getData = function () {
  26299. return this._data;
  26300. };
  26301. Buffer.prototype.getBuffer = function () {
  26302. return this._buffer;
  26303. };
  26304. Buffer.prototype.getStrideSize = function () {
  26305. return this._strideSize;
  26306. };
  26307. // public getIsInstanced(): boolean {
  26308. // return this._instanced;
  26309. // }
  26310. // public get instanceDivisor(): number {
  26311. // return this._instanceDivisor;
  26312. // }
  26313. // public set instanceDivisor(value: number) {
  26314. // this._instanceDivisor = value;
  26315. // if (value == 0) {
  26316. // this._instanced = false;
  26317. // } else {
  26318. // this._instanced = true;
  26319. // }
  26320. // }
  26321. // Methods
  26322. Buffer.prototype.create = function (data) {
  26323. if (data === void 0) { data = null; }
  26324. if (!data && this._buffer) {
  26325. return; // nothing to do
  26326. }
  26327. data = data || this._data;
  26328. if (!data) {
  26329. return;
  26330. }
  26331. if (!this._buffer) {
  26332. if (this._updatable) {
  26333. this._buffer = this._engine.createDynamicVertexBuffer(data);
  26334. this._data = data;
  26335. }
  26336. else {
  26337. this._buffer = this._engine.createVertexBuffer(data);
  26338. }
  26339. }
  26340. else if (this._updatable) {
  26341. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  26342. this._data = data;
  26343. }
  26344. };
  26345. Buffer.prototype._rebuild = function () {
  26346. this._buffer = null;
  26347. this.create(this._data);
  26348. };
  26349. Buffer.prototype.update = function (data) {
  26350. this.create(data);
  26351. };
  26352. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  26353. if (!this._buffer) {
  26354. return;
  26355. }
  26356. if (this._updatable) {
  26357. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  26358. this._data = null;
  26359. }
  26360. };
  26361. Buffer.prototype.dispose = function () {
  26362. if (!this._buffer) {
  26363. return;
  26364. }
  26365. if (this._engine._releaseBuffer(this._buffer)) {
  26366. this._buffer = null;
  26367. }
  26368. };
  26369. return Buffer;
  26370. }());
  26371. BABYLON.Buffer = Buffer;
  26372. })(BABYLON || (BABYLON = {}));
  26373. //# sourceMappingURL=babylon.buffer.js.map
  26374. "use strict";
  26375. var BABYLON;
  26376. (function (BABYLON) {
  26377. var VertexBuffer = /** @class */ (function () {
  26378. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  26379. if (data instanceof BABYLON.Buffer) {
  26380. if (!stride) {
  26381. stride = data.getStrideSize();
  26382. }
  26383. this._buffer = data;
  26384. this._ownsBuffer = false;
  26385. }
  26386. else {
  26387. if (!stride) {
  26388. stride = VertexBuffer.DeduceStride(kind);
  26389. }
  26390. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  26391. this._ownsBuffer = true;
  26392. }
  26393. this._stride = stride;
  26394. this._instanced = instanced !== undefined ? instanced : false;
  26395. this._instanceDivisor = instanced ? 1 : 0;
  26396. this._offset = offset ? offset : 0;
  26397. this._size = size ? size : stride;
  26398. this._kind = kind;
  26399. }
  26400. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  26401. /**
  26402. * Gets or sets the instance divisor when in instanced mode
  26403. */
  26404. get: function () {
  26405. return this._instanceDivisor;
  26406. },
  26407. set: function (value) {
  26408. this._instanceDivisor = value;
  26409. if (value == 0) {
  26410. this._instanced = false;
  26411. }
  26412. else {
  26413. this._instanced = true;
  26414. }
  26415. },
  26416. enumerable: true,
  26417. configurable: true
  26418. });
  26419. VertexBuffer.prototype._rebuild = function () {
  26420. if (!this._buffer) {
  26421. return;
  26422. }
  26423. this._buffer._rebuild();
  26424. };
  26425. /**
  26426. * Returns the kind of the VertexBuffer (string).
  26427. */
  26428. VertexBuffer.prototype.getKind = function () {
  26429. return this._kind;
  26430. };
  26431. // Properties
  26432. /**
  26433. * Boolean : is the VertexBuffer updatable ?
  26434. */
  26435. VertexBuffer.prototype.isUpdatable = function () {
  26436. return this._buffer.isUpdatable();
  26437. };
  26438. /**
  26439. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  26440. */
  26441. VertexBuffer.prototype.getData = function () {
  26442. return this._buffer.getData();
  26443. };
  26444. /**
  26445. * Returns the WebGLBuffer associated to the VertexBuffer.
  26446. */
  26447. VertexBuffer.prototype.getBuffer = function () {
  26448. return this._buffer.getBuffer();
  26449. };
  26450. /**
  26451. * Returns the stride of the VertexBuffer (integer).
  26452. */
  26453. VertexBuffer.prototype.getStrideSize = function () {
  26454. return this._stride;
  26455. };
  26456. /**
  26457. * Returns the offset (integer).
  26458. */
  26459. VertexBuffer.prototype.getOffset = function () {
  26460. return this._offset;
  26461. };
  26462. /**
  26463. * Returns the VertexBuffer total size (integer).
  26464. */
  26465. VertexBuffer.prototype.getSize = function () {
  26466. return this._size;
  26467. };
  26468. /**
  26469. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  26470. */
  26471. VertexBuffer.prototype.getIsInstanced = function () {
  26472. return this._instanced;
  26473. };
  26474. /**
  26475. * Returns the instancing divisor, zero for non-instanced (integer).
  26476. */
  26477. VertexBuffer.prototype.getInstanceDivisor = function () {
  26478. return this._instanceDivisor;
  26479. };
  26480. // Methods
  26481. /**
  26482. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  26483. * Returns the created WebGLBuffer.
  26484. */
  26485. VertexBuffer.prototype.create = function (data) {
  26486. return this._buffer.create(data);
  26487. };
  26488. /**
  26489. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  26490. * This function will create a new buffer if the current one is not updatable
  26491. * Returns the updated WebGLBuffer.
  26492. */
  26493. VertexBuffer.prototype.update = function (data) {
  26494. return this._buffer.update(data);
  26495. };
  26496. /**
  26497. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  26498. * Returns the directly updated WebGLBuffer.
  26499. */
  26500. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  26501. return this._buffer.updateDirectly(data, offset);
  26502. };
  26503. /**
  26504. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  26505. */
  26506. VertexBuffer.prototype.dispose = function () {
  26507. if (this._ownsBuffer) {
  26508. this._buffer.dispose();
  26509. }
  26510. };
  26511. Object.defineProperty(VertexBuffer, "PositionKind", {
  26512. get: function () {
  26513. return VertexBuffer._PositionKind;
  26514. },
  26515. enumerable: true,
  26516. configurable: true
  26517. });
  26518. Object.defineProperty(VertexBuffer, "NormalKind", {
  26519. get: function () {
  26520. return VertexBuffer._NormalKind;
  26521. },
  26522. enumerable: true,
  26523. configurable: true
  26524. });
  26525. Object.defineProperty(VertexBuffer, "TangentKind", {
  26526. get: function () {
  26527. return VertexBuffer._TangentKind;
  26528. },
  26529. enumerable: true,
  26530. configurable: true
  26531. });
  26532. Object.defineProperty(VertexBuffer, "UVKind", {
  26533. get: function () {
  26534. return VertexBuffer._UVKind;
  26535. },
  26536. enumerable: true,
  26537. configurable: true
  26538. });
  26539. Object.defineProperty(VertexBuffer, "UV2Kind", {
  26540. get: function () {
  26541. return VertexBuffer._UV2Kind;
  26542. },
  26543. enumerable: true,
  26544. configurable: true
  26545. });
  26546. Object.defineProperty(VertexBuffer, "UV3Kind", {
  26547. get: function () {
  26548. return VertexBuffer._UV3Kind;
  26549. },
  26550. enumerable: true,
  26551. configurable: true
  26552. });
  26553. Object.defineProperty(VertexBuffer, "UV4Kind", {
  26554. get: function () {
  26555. return VertexBuffer._UV4Kind;
  26556. },
  26557. enumerable: true,
  26558. configurable: true
  26559. });
  26560. Object.defineProperty(VertexBuffer, "UV5Kind", {
  26561. get: function () {
  26562. return VertexBuffer._UV5Kind;
  26563. },
  26564. enumerable: true,
  26565. configurable: true
  26566. });
  26567. Object.defineProperty(VertexBuffer, "UV6Kind", {
  26568. get: function () {
  26569. return VertexBuffer._UV6Kind;
  26570. },
  26571. enumerable: true,
  26572. configurable: true
  26573. });
  26574. Object.defineProperty(VertexBuffer, "ColorKind", {
  26575. get: function () {
  26576. return VertexBuffer._ColorKind;
  26577. },
  26578. enumerable: true,
  26579. configurable: true
  26580. });
  26581. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  26582. get: function () {
  26583. return VertexBuffer._MatricesIndicesKind;
  26584. },
  26585. enumerable: true,
  26586. configurable: true
  26587. });
  26588. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  26589. get: function () {
  26590. return VertexBuffer._MatricesWeightsKind;
  26591. },
  26592. enumerable: true,
  26593. configurable: true
  26594. });
  26595. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  26596. get: function () {
  26597. return VertexBuffer._MatricesIndicesExtraKind;
  26598. },
  26599. enumerable: true,
  26600. configurable: true
  26601. });
  26602. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  26603. get: function () {
  26604. return VertexBuffer._MatricesWeightsExtraKind;
  26605. },
  26606. enumerable: true,
  26607. configurable: true
  26608. });
  26609. /**
  26610. * Deduces the stride given a kind.
  26611. * @param kind The kind string to deduce
  26612. * @returns The deduced stride
  26613. */
  26614. VertexBuffer.DeduceStride = function (kind) {
  26615. switch (kind) {
  26616. case VertexBuffer.UVKind:
  26617. case VertexBuffer.UV2Kind:
  26618. case VertexBuffer.UV3Kind:
  26619. case VertexBuffer.UV4Kind:
  26620. case VertexBuffer.UV5Kind:
  26621. case VertexBuffer.UV6Kind:
  26622. return 2;
  26623. case VertexBuffer.NormalKind:
  26624. case VertexBuffer.PositionKind:
  26625. return 3;
  26626. case VertexBuffer.ColorKind:
  26627. case VertexBuffer.MatricesIndicesKind:
  26628. case VertexBuffer.MatricesIndicesExtraKind:
  26629. case VertexBuffer.MatricesWeightsKind:
  26630. case VertexBuffer.MatricesWeightsExtraKind:
  26631. case VertexBuffer.TangentKind:
  26632. return 4;
  26633. default:
  26634. throw new Error("Invalid kind '" + kind + "'");
  26635. }
  26636. };
  26637. // Enums
  26638. VertexBuffer._PositionKind = "position";
  26639. VertexBuffer._NormalKind = "normal";
  26640. VertexBuffer._TangentKind = "tangent";
  26641. VertexBuffer._UVKind = "uv";
  26642. VertexBuffer._UV2Kind = "uv2";
  26643. VertexBuffer._UV3Kind = "uv3";
  26644. VertexBuffer._UV4Kind = "uv4";
  26645. VertexBuffer._UV5Kind = "uv5";
  26646. VertexBuffer._UV6Kind = "uv6";
  26647. VertexBuffer._ColorKind = "color";
  26648. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  26649. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  26650. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  26651. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  26652. return VertexBuffer;
  26653. }());
  26654. BABYLON.VertexBuffer = VertexBuffer;
  26655. })(BABYLON || (BABYLON = {}));
  26656. //# sourceMappingURL=babylon.vertexBuffer.js.map
  26657. "use strict";
  26658. var BABYLON;
  26659. (function (BABYLON) {
  26660. /**
  26661. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  26662. */
  26663. var DummyInternalTextureTracker = /** @class */ (function () {
  26664. function DummyInternalTextureTracker() {
  26665. /**
  26666. * Gets or set the previous tracker in the list
  26667. */
  26668. this.previous = null;
  26669. /**
  26670. * Gets or set the next tracker in the list
  26671. */
  26672. this.next = null;
  26673. }
  26674. return DummyInternalTextureTracker;
  26675. }());
  26676. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  26677. })(BABYLON || (BABYLON = {}));
  26678. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  26679. "use strict";
  26680. var BABYLON;
  26681. (function (BABYLON) {
  26682. /**
  26683. * Class used to store data associated with WebGL texture data for the engine
  26684. * This class should not be used directly
  26685. */
  26686. var InternalTexture = /** @class */ (function () {
  26687. /**
  26688. * Creates a new InternalTexture
  26689. * @param engine defines the engine to use
  26690. * @param dataSource defines the type of data that will be used
  26691. */
  26692. function InternalTexture(engine, dataSource) {
  26693. /**
  26694. * Observable called when the texture is loaded
  26695. */
  26696. this.onLoadedObservable = new BABYLON.Observable();
  26697. /**
  26698. * Gets or set the previous tracker in the list
  26699. */
  26700. this.previous = null;
  26701. /**
  26702. * Gets or set the next tracker in the list
  26703. */
  26704. this.next = null;
  26705. // Private
  26706. /** @ignore */
  26707. this._initialSlot = -1;
  26708. /** @ignore */
  26709. this._designatedSlot = -1;
  26710. /** @ignore */
  26711. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  26712. /** @ignore */
  26713. this._comparisonFunction = 0;
  26714. /** @ignore */
  26715. this._references = 1;
  26716. this._engine = engine;
  26717. this._dataSource = dataSource;
  26718. this._webGLTexture = engine._createTexture();
  26719. }
  26720. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  26721. /**
  26722. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  26723. */
  26724. get: function () {
  26725. return this._dataSource;
  26726. },
  26727. enumerable: true,
  26728. configurable: true
  26729. });
  26730. /**
  26731. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  26732. */
  26733. InternalTexture.prototype.incrementReferences = function () {
  26734. this._references++;
  26735. };
  26736. /**
  26737. * Change the size of the texture (not the size of the content)
  26738. * @param width defines the new width
  26739. * @param height defines the new height
  26740. * @param depth defines the new depth (1 by default)
  26741. */
  26742. InternalTexture.prototype.updateSize = function (width, height, depth) {
  26743. if (depth === void 0) { depth = 1; }
  26744. this.width = width;
  26745. this.height = height;
  26746. this.depth = depth;
  26747. this.baseWidth = width;
  26748. this.baseHeight = height;
  26749. this.baseDepth = depth;
  26750. this._size = width * height * depth;
  26751. };
  26752. /** @ignore */
  26753. InternalTexture.prototype._rebuild = function () {
  26754. var _this = this;
  26755. var proxy;
  26756. this.isReady = false;
  26757. this._cachedCoordinatesMode = null;
  26758. this._cachedWrapU = null;
  26759. this._cachedWrapV = null;
  26760. this._cachedAnisotropicFilteringLevel = null;
  26761. switch (this._dataSource) {
  26762. case InternalTexture.DATASOURCE_TEMP:
  26763. return;
  26764. case InternalTexture.DATASOURCE_URL:
  26765. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  26766. _this.isReady = true;
  26767. }, null, this._buffer, undefined, this.format);
  26768. proxy._swapAndDie(this);
  26769. return;
  26770. case InternalTexture.DATASOURCE_RAW:
  26771. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26772. proxy._swapAndDie(this);
  26773. this.isReady = true;
  26774. return;
  26775. case InternalTexture.DATASOURCE_RAW3D:
  26776. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26777. proxy._swapAndDie(this);
  26778. this.isReady = true;
  26779. return;
  26780. case InternalTexture.DATASOURCE_DYNAMIC:
  26781. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  26782. proxy._swapAndDie(this);
  26783. // The engine will make sure to update content so no need to flag it as isReady = true
  26784. return;
  26785. case InternalTexture.DATASOURCE_RENDERTARGET:
  26786. var options = new BABYLON.RenderTargetCreationOptions();
  26787. options.generateDepthBuffer = this._generateDepthBuffer;
  26788. options.generateMipMaps = this.generateMipMaps;
  26789. options.generateStencilBuffer = this._generateStencilBuffer;
  26790. options.samplingMode = this.samplingMode;
  26791. options.type = this.type;
  26792. if (this.isCube) {
  26793. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  26794. }
  26795. else {
  26796. var size = {
  26797. width: this.width,
  26798. height: this.height
  26799. };
  26800. proxy = this._engine.createRenderTargetTexture(size, options);
  26801. }
  26802. proxy._swapAndDie(this);
  26803. this.isReady = true;
  26804. return;
  26805. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  26806. var depthTextureOptions = {
  26807. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  26808. comparisonFunction: this._comparisonFunction,
  26809. generateStencil: this._generateStencilBuffer,
  26810. isCube: this.isCube
  26811. };
  26812. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  26813. proxy._swapAndDie(this);
  26814. this.isReady = true;
  26815. return;
  26816. case InternalTexture.DATASOURCE_CUBE:
  26817. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  26818. _this.isReady = true;
  26819. }, null, this.format, this._extension);
  26820. proxy._swapAndDie(this);
  26821. return;
  26822. case InternalTexture.DATASOURCE_CUBERAW:
  26823. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26824. proxy._swapAndDie(this);
  26825. this.isReady = true;
  26826. return;
  26827. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  26828. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  26829. if (proxy) {
  26830. proxy._swapAndDie(_this);
  26831. }
  26832. _this.isReady = true;
  26833. }, null, this.format, this._extension);
  26834. return;
  26835. }
  26836. };
  26837. InternalTexture.prototype._swapAndDie = function (target) {
  26838. target._webGLTexture = this._webGLTexture;
  26839. if (this._framebuffer) {
  26840. target._framebuffer = this._framebuffer;
  26841. }
  26842. if (this._depthStencilBuffer) {
  26843. target._depthStencilBuffer = this._depthStencilBuffer;
  26844. }
  26845. if (this._lodTextureHigh) {
  26846. if (target._lodTextureHigh) {
  26847. target._lodTextureHigh.dispose();
  26848. }
  26849. target._lodTextureHigh = this._lodTextureHigh;
  26850. }
  26851. if (this._lodTextureMid) {
  26852. if (target._lodTextureMid) {
  26853. target._lodTextureMid.dispose();
  26854. }
  26855. target._lodTextureMid = this._lodTextureMid;
  26856. }
  26857. if (this._lodTextureLow) {
  26858. if (target._lodTextureLow) {
  26859. target._lodTextureLow.dispose();
  26860. }
  26861. target._lodTextureLow = this._lodTextureLow;
  26862. }
  26863. var cache = this._engine.getLoadedTexturesCache();
  26864. var index = cache.indexOf(this);
  26865. if (index !== -1) {
  26866. cache.splice(index, 1);
  26867. }
  26868. };
  26869. /**
  26870. * Dispose the current allocated resources
  26871. */
  26872. InternalTexture.prototype.dispose = function () {
  26873. if (!this._webGLTexture) {
  26874. return;
  26875. }
  26876. this._references--;
  26877. if (this._references === 0) {
  26878. this._engine._releaseTexture(this);
  26879. this._webGLTexture = null;
  26880. this.previous = null;
  26881. this.next = null;
  26882. }
  26883. };
  26884. /**
  26885. * The source of the texture data is unknown
  26886. */
  26887. InternalTexture.DATASOURCE_UNKNOWN = 0;
  26888. /**
  26889. * Texture data comes from an URL
  26890. */
  26891. InternalTexture.DATASOURCE_URL = 1;
  26892. /**
  26893. * Texture data is only used for temporary storage
  26894. */
  26895. InternalTexture.DATASOURCE_TEMP = 2;
  26896. /**
  26897. * Texture data comes from raw data (ArrayBuffer)
  26898. */
  26899. InternalTexture.DATASOURCE_RAW = 3;
  26900. /**
  26901. * Texture content is dynamic (video or dynamic texture)
  26902. */
  26903. InternalTexture.DATASOURCE_DYNAMIC = 4;
  26904. /**
  26905. * Texture content is generated by rendering to it
  26906. */
  26907. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  26908. /**
  26909. * Texture content is part of a multi render target process
  26910. */
  26911. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  26912. /**
  26913. * Texture data comes from a cube data file
  26914. */
  26915. InternalTexture.DATASOURCE_CUBE = 7;
  26916. /**
  26917. * Texture data comes from a raw cube data
  26918. */
  26919. InternalTexture.DATASOURCE_CUBERAW = 8;
  26920. /**
  26921. * Texture data come from a prefiltered cube data file
  26922. */
  26923. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  26924. /**
  26925. * Texture content is raw 3D data
  26926. */
  26927. InternalTexture.DATASOURCE_RAW3D = 10;
  26928. /**
  26929. * Texture content is a depth texture
  26930. */
  26931. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  26932. return InternalTexture;
  26933. }());
  26934. BABYLON.InternalTexture = InternalTexture;
  26935. })(BABYLON || (BABYLON = {}));
  26936. //# sourceMappingURL=babylon.internalTexture.js.map
  26937. "use strict";
  26938. var BABYLON;
  26939. (function (BABYLON) {
  26940. var BaseTexture = /** @class */ (function () {
  26941. function BaseTexture(scene) {
  26942. this._hasAlpha = false;
  26943. this.getAlphaFromRGB = false;
  26944. this.level = 1;
  26945. this.coordinatesIndex = 0;
  26946. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  26947. /**
  26948. * | Value | Type | Description |
  26949. * | ----- | ------------------ | ----------- |
  26950. * | 0 | CLAMP_ADDRESSMODE | |
  26951. * | 1 | WRAP_ADDRESSMODE | |
  26952. * | 2 | MIRROR_ADDRESSMODE | |
  26953. */
  26954. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  26955. /**
  26956. * | Value | Type | Description |
  26957. * | ----- | ------------------ | ----------- |
  26958. * | 0 | CLAMP_ADDRESSMODE | |
  26959. * | 1 | WRAP_ADDRESSMODE | |
  26960. * | 2 | MIRROR_ADDRESSMODE | |
  26961. */
  26962. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  26963. /**
  26964. * | Value | Type | Description |
  26965. * | ----- | ------------------ | ----------- |
  26966. * | 0 | CLAMP_ADDRESSMODE | |
  26967. * | 1 | WRAP_ADDRESSMODE | |
  26968. * | 2 | MIRROR_ADDRESSMODE | |
  26969. */
  26970. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  26971. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  26972. this.isCube = false;
  26973. this.is3D = false;
  26974. this.gammaSpace = true;
  26975. this.invertZ = false;
  26976. this.lodLevelInAlpha = false;
  26977. this.lodGenerationOffset = 0.0;
  26978. this.lodGenerationScale = 0.8;
  26979. this.isRenderTarget = false;
  26980. this.animations = new Array();
  26981. /**
  26982. * An event triggered when the texture is disposed.
  26983. * @type {BABYLON.Observable}
  26984. */
  26985. this.onDisposeObservable = new BABYLON.Observable();
  26986. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26987. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  26988. if (this._scene) {
  26989. this._scene.textures.push(this);
  26990. }
  26991. this._uid = null;
  26992. }
  26993. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  26994. get: function () {
  26995. return this._hasAlpha;
  26996. },
  26997. set: function (value) {
  26998. if (this._hasAlpha === value) {
  26999. return;
  27000. }
  27001. this._hasAlpha = value;
  27002. if (this._scene) {
  27003. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  27004. }
  27005. },
  27006. enumerable: true,
  27007. configurable: true
  27008. });
  27009. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  27010. get: function () {
  27011. return this._coordinatesMode;
  27012. },
  27013. /**
  27014. * How a texture is mapped.
  27015. *
  27016. * | Value | Type | Description |
  27017. * | ----- | ----------------------------------- | ----------- |
  27018. * | 0 | EXPLICIT_MODE | |
  27019. * | 1 | SPHERICAL_MODE | |
  27020. * | 2 | PLANAR_MODE | |
  27021. * | 3 | CUBIC_MODE | |
  27022. * | 4 | PROJECTION_MODE | |
  27023. * | 5 | SKYBOX_MODE | |
  27024. * | 6 | INVCUBIC_MODE | |
  27025. * | 7 | EQUIRECTANGULAR_MODE | |
  27026. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  27027. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  27028. */
  27029. set: function (value) {
  27030. if (this._coordinatesMode === value) {
  27031. return;
  27032. }
  27033. this._coordinatesMode = value;
  27034. if (this._scene) {
  27035. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  27036. }
  27037. },
  27038. enumerable: true,
  27039. configurable: true
  27040. });
  27041. Object.defineProperty(BaseTexture.prototype, "uid", {
  27042. get: function () {
  27043. if (!this._uid) {
  27044. this._uid = BABYLON.Tools.RandomId();
  27045. }
  27046. return this._uid;
  27047. },
  27048. enumerable: true,
  27049. configurable: true
  27050. });
  27051. BaseTexture.prototype.toString = function () {
  27052. return this.name;
  27053. };
  27054. BaseTexture.prototype.getClassName = function () {
  27055. return "BaseTexture";
  27056. };
  27057. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  27058. set: function (callback) {
  27059. if (this._onDisposeObserver) {
  27060. this.onDisposeObservable.remove(this._onDisposeObserver);
  27061. }
  27062. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  27063. },
  27064. enumerable: true,
  27065. configurable: true
  27066. });
  27067. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  27068. get: function () {
  27069. return true;
  27070. },
  27071. enumerable: true,
  27072. configurable: true
  27073. });
  27074. BaseTexture.prototype.getScene = function () {
  27075. return this._scene;
  27076. };
  27077. BaseTexture.prototype.getTextureMatrix = function () {
  27078. return BABYLON.Matrix.IdentityReadOnly;
  27079. };
  27080. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  27081. return BABYLON.Matrix.IdentityReadOnly;
  27082. };
  27083. BaseTexture.prototype.getInternalTexture = function () {
  27084. return this._texture;
  27085. };
  27086. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  27087. return !this.isBlocking || this.isReady();
  27088. };
  27089. BaseTexture.prototype.isReady = function () {
  27090. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  27091. this.delayLoad();
  27092. return false;
  27093. }
  27094. if (this._texture) {
  27095. return this._texture.isReady;
  27096. }
  27097. return false;
  27098. };
  27099. BaseTexture.prototype.getSize = function () {
  27100. if (this._texture && this._texture.width) {
  27101. return new BABYLON.Size(this._texture.width, this._texture.height);
  27102. }
  27103. if (this._texture && this._texture._size) {
  27104. return new BABYLON.Size(this._texture._size, this._texture._size);
  27105. }
  27106. return BABYLON.Size.Zero();
  27107. };
  27108. BaseTexture.prototype.getBaseSize = function () {
  27109. if (!this.isReady() || !this._texture)
  27110. return BABYLON.Size.Zero();
  27111. if (this._texture._size) {
  27112. return new BABYLON.Size(this._texture._size, this._texture._size);
  27113. }
  27114. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  27115. };
  27116. BaseTexture.prototype.scale = function (ratio) {
  27117. };
  27118. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  27119. get: function () {
  27120. return false;
  27121. },
  27122. enumerable: true,
  27123. configurable: true
  27124. });
  27125. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  27126. if (!this._scene) {
  27127. return null;
  27128. }
  27129. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  27130. for (var index = 0; index < texturesCache.length; index++) {
  27131. var texturesCacheEntry = texturesCache[index];
  27132. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  27133. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  27134. texturesCacheEntry.incrementReferences();
  27135. return texturesCacheEntry;
  27136. }
  27137. }
  27138. }
  27139. return null;
  27140. };
  27141. BaseTexture.prototype._rebuild = function () {
  27142. };
  27143. BaseTexture.prototype.delayLoad = function () {
  27144. };
  27145. BaseTexture.prototype.clone = function () {
  27146. return null;
  27147. };
  27148. Object.defineProperty(BaseTexture.prototype, "textureType", {
  27149. get: function () {
  27150. if (!this._texture) {
  27151. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  27152. }
  27153. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  27154. },
  27155. enumerable: true,
  27156. configurable: true
  27157. });
  27158. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  27159. get: function () {
  27160. if (!this._texture) {
  27161. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  27162. }
  27163. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  27164. },
  27165. enumerable: true,
  27166. configurable: true
  27167. });
  27168. BaseTexture.prototype.readPixels = function (faceIndex) {
  27169. if (faceIndex === void 0) { faceIndex = 0; }
  27170. if (!this._texture) {
  27171. return null;
  27172. }
  27173. var size = this.getSize();
  27174. var scene = this.getScene();
  27175. if (!scene) {
  27176. return null;
  27177. }
  27178. var engine = scene.getEngine();
  27179. if (this._texture.isCube) {
  27180. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  27181. }
  27182. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  27183. };
  27184. BaseTexture.prototype.releaseInternalTexture = function () {
  27185. if (this._texture) {
  27186. this._texture.dispose();
  27187. this._texture = null;
  27188. }
  27189. };
  27190. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  27191. get: function () {
  27192. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  27193. return null;
  27194. }
  27195. if (!this._texture._sphericalPolynomial) {
  27196. this._texture._sphericalPolynomial =
  27197. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  27198. }
  27199. return this._texture._sphericalPolynomial;
  27200. },
  27201. set: function (value) {
  27202. if (this._texture) {
  27203. this._texture._sphericalPolynomial = value;
  27204. }
  27205. },
  27206. enumerable: true,
  27207. configurable: true
  27208. });
  27209. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  27210. get: function () {
  27211. if (this._texture) {
  27212. return this._texture._lodTextureHigh;
  27213. }
  27214. return null;
  27215. },
  27216. enumerable: true,
  27217. configurable: true
  27218. });
  27219. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  27220. get: function () {
  27221. if (this._texture) {
  27222. return this._texture._lodTextureMid;
  27223. }
  27224. return null;
  27225. },
  27226. enumerable: true,
  27227. configurable: true
  27228. });
  27229. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  27230. get: function () {
  27231. if (this._texture) {
  27232. return this._texture._lodTextureLow;
  27233. }
  27234. return null;
  27235. },
  27236. enumerable: true,
  27237. configurable: true
  27238. });
  27239. BaseTexture.prototype.dispose = function () {
  27240. if (!this._scene) {
  27241. return;
  27242. }
  27243. // Animations
  27244. this._scene.stopAnimation(this);
  27245. // Remove from scene
  27246. this._scene._removePendingData(this);
  27247. var index = this._scene.textures.indexOf(this);
  27248. if (index >= 0) {
  27249. this._scene.textures.splice(index, 1);
  27250. }
  27251. if (this._texture === undefined) {
  27252. return;
  27253. }
  27254. // Release
  27255. this.releaseInternalTexture();
  27256. // Callback
  27257. this.onDisposeObservable.notifyObservers(this);
  27258. this.onDisposeObservable.clear();
  27259. };
  27260. BaseTexture.prototype.serialize = function () {
  27261. if (!this.name) {
  27262. return null;
  27263. }
  27264. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  27265. // Animations
  27266. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  27267. return serializationObject;
  27268. };
  27269. BaseTexture.WhenAllReady = function (textures, callback) {
  27270. var numRemaining = textures.length;
  27271. if (numRemaining === 0) {
  27272. callback();
  27273. return;
  27274. }
  27275. var _loop_1 = function () {
  27276. texture = textures[i];
  27277. if (texture.isReady()) {
  27278. if (--numRemaining === 0) {
  27279. callback();
  27280. }
  27281. }
  27282. else {
  27283. onLoadObservable = texture.onLoadObservable;
  27284. var onLoadCallback_1 = function () {
  27285. onLoadObservable.removeCallback(onLoadCallback_1);
  27286. if (--numRemaining === 0) {
  27287. callback();
  27288. }
  27289. };
  27290. onLoadObservable.add(onLoadCallback_1);
  27291. }
  27292. };
  27293. var texture, onLoadObservable;
  27294. for (var i = 0; i < textures.length; i++) {
  27295. _loop_1();
  27296. }
  27297. };
  27298. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  27299. __decorate([
  27300. BABYLON.serialize()
  27301. ], BaseTexture.prototype, "name", void 0);
  27302. __decorate([
  27303. BABYLON.serialize("hasAlpha")
  27304. ], BaseTexture.prototype, "_hasAlpha", void 0);
  27305. __decorate([
  27306. BABYLON.serialize()
  27307. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  27308. __decorate([
  27309. BABYLON.serialize()
  27310. ], BaseTexture.prototype, "level", void 0);
  27311. __decorate([
  27312. BABYLON.serialize()
  27313. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  27314. __decorate([
  27315. BABYLON.serialize("coordinatesMode")
  27316. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  27317. __decorate([
  27318. BABYLON.serialize()
  27319. ], BaseTexture.prototype, "wrapU", void 0);
  27320. __decorate([
  27321. BABYLON.serialize()
  27322. ], BaseTexture.prototype, "wrapV", void 0);
  27323. __decorate([
  27324. BABYLON.serialize()
  27325. ], BaseTexture.prototype, "wrapR", void 0);
  27326. __decorate([
  27327. BABYLON.serialize()
  27328. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  27329. __decorate([
  27330. BABYLON.serialize()
  27331. ], BaseTexture.prototype, "isCube", void 0);
  27332. __decorate([
  27333. BABYLON.serialize()
  27334. ], BaseTexture.prototype, "is3D", void 0);
  27335. __decorate([
  27336. BABYLON.serialize()
  27337. ], BaseTexture.prototype, "gammaSpace", void 0);
  27338. __decorate([
  27339. BABYLON.serialize()
  27340. ], BaseTexture.prototype, "invertZ", void 0);
  27341. __decorate([
  27342. BABYLON.serialize()
  27343. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  27344. __decorate([
  27345. BABYLON.serialize()
  27346. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  27347. __decorate([
  27348. BABYLON.serialize()
  27349. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  27350. __decorate([
  27351. BABYLON.serialize()
  27352. ], BaseTexture.prototype, "isRenderTarget", void 0);
  27353. return BaseTexture;
  27354. }());
  27355. BABYLON.BaseTexture = BaseTexture;
  27356. })(BABYLON || (BABYLON = {}));
  27357. //# sourceMappingURL=babylon.baseTexture.js.map
  27358. "use strict";
  27359. var BABYLON;
  27360. (function (BABYLON) {
  27361. var Texture = /** @class */ (function (_super) {
  27362. __extends(Texture, _super);
  27363. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  27364. if (noMipmap === void 0) { noMipmap = false; }
  27365. if (invertY === void 0) { invertY = true; }
  27366. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27367. if (onLoad === void 0) { onLoad = null; }
  27368. if (onError === void 0) { onError = null; }
  27369. if (buffer === void 0) { buffer = null; }
  27370. if (deleteBuffer === void 0) { deleteBuffer = false; }
  27371. var _this = _super.call(this, scene) || this;
  27372. _this.uOffset = 0;
  27373. _this.vOffset = 0;
  27374. _this.uScale = 1.0;
  27375. _this.vScale = 1.0;
  27376. _this.uAng = 0;
  27377. _this.vAng = 0;
  27378. _this.wAng = 0;
  27379. _this._isBlocking = true;
  27380. _this.name = url || "";
  27381. _this.url = url;
  27382. _this._noMipmap = noMipmap;
  27383. _this._invertY = invertY;
  27384. _this._samplingMode = samplingMode;
  27385. _this._buffer = buffer;
  27386. _this._deleteBuffer = deleteBuffer;
  27387. if (format) {
  27388. _this._format = format;
  27389. }
  27390. scene = _this.getScene();
  27391. if (!scene) {
  27392. return _this;
  27393. }
  27394. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  27395. var load = function () {
  27396. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  27397. _this.onLoadObservable.notifyObservers(_this);
  27398. }
  27399. if (onLoad) {
  27400. onLoad();
  27401. }
  27402. if (!_this.isBlocking && scene) {
  27403. scene.resetCachedMaterial();
  27404. }
  27405. };
  27406. if (!_this.url) {
  27407. _this._delayedOnLoad = load;
  27408. _this._delayedOnError = onError;
  27409. return _this;
  27410. }
  27411. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  27412. if (!_this._texture) {
  27413. if (!scene.useDelayedTextureLoading) {
  27414. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  27415. if (deleteBuffer) {
  27416. delete _this._buffer;
  27417. }
  27418. }
  27419. else {
  27420. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  27421. _this._delayedOnLoad = load;
  27422. _this._delayedOnError = onError;
  27423. }
  27424. }
  27425. else {
  27426. if (_this._texture.isReady) {
  27427. BABYLON.Tools.SetImmediate(function () { return load(); });
  27428. }
  27429. else {
  27430. _this._texture.onLoadedObservable.add(load);
  27431. }
  27432. }
  27433. return _this;
  27434. }
  27435. Object.defineProperty(Texture.prototype, "noMipmap", {
  27436. get: function () {
  27437. return this._noMipmap;
  27438. },
  27439. enumerable: true,
  27440. configurable: true
  27441. });
  27442. Object.defineProperty(Texture.prototype, "isBlocking", {
  27443. get: function () {
  27444. return this._isBlocking;
  27445. },
  27446. set: function (value) {
  27447. this._isBlocking = value;
  27448. },
  27449. enumerable: true,
  27450. configurable: true
  27451. });
  27452. Object.defineProperty(Texture.prototype, "samplingMode", {
  27453. get: function () {
  27454. return this._samplingMode;
  27455. },
  27456. enumerable: true,
  27457. configurable: true
  27458. });
  27459. Texture.prototype.updateURL = function (url) {
  27460. this.url = url;
  27461. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  27462. this.delayLoad();
  27463. };
  27464. Texture.prototype.delayLoad = function () {
  27465. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  27466. return;
  27467. }
  27468. var scene = this.getScene();
  27469. if (!scene) {
  27470. return;
  27471. }
  27472. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  27473. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  27474. if (!this._texture) {
  27475. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  27476. if (this._deleteBuffer) {
  27477. delete this._buffer;
  27478. }
  27479. }
  27480. else {
  27481. if (this._delayedOnLoad) {
  27482. if (this._texture.isReady) {
  27483. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  27484. }
  27485. else {
  27486. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  27487. }
  27488. }
  27489. }
  27490. this._delayedOnLoad = null;
  27491. this._delayedOnError = null;
  27492. };
  27493. Texture.prototype.updateSamplingMode = function (samplingMode) {
  27494. if (!this._texture) {
  27495. return;
  27496. }
  27497. var scene = this.getScene();
  27498. if (!scene) {
  27499. return;
  27500. }
  27501. this._samplingMode = samplingMode;
  27502. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  27503. };
  27504. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  27505. x *= this.uScale;
  27506. y *= this.vScale;
  27507. x -= 0.5 * this.uScale;
  27508. y -= 0.5 * this.vScale;
  27509. z -= 0.5;
  27510. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  27511. t.x += 0.5 * this.uScale + this.uOffset;
  27512. t.y += 0.5 * this.vScale + this.vOffset;
  27513. t.z += 0.5;
  27514. };
  27515. Texture.prototype.getTextureMatrix = function () {
  27516. var _this = this;
  27517. if (this.uOffset === this._cachedUOffset &&
  27518. this.vOffset === this._cachedVOffset &&
  27519. this.uScale === this._cachedUScale &&
  27520. this.vScale === this._cachedVScale &&
  27521. this.uAng === this._cachedUAng &&
  27522. this.vAng === this._cachedVAng &&
  27523. this.wAng === this._cachedWAng) {
  27524. return this._cachedTextureMatrix;
  27525. }
  27526. this._cachedUOffset = this.uOffset;
  27527. this._cachedVOffset = this.vOffset;
  27528. this._cachedUScale = this.uScale;
  27529. this._cachedVScale = this.vScale;
  27530. this._cachedUAng = this.uAng;
  27531. this._cachedVAng = this.vAng;
  27532. this._cachedWAng = this.wAng;
  27533. if (!this._cachedTextureMatrix) {
  27534. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  27535. this._rowGenerationMatrix = new BABYLON.Matrix();
  27536. this._t0 = BABYLON.Vector3.Zero();
  27537. this._t1 = BABYLON.Vector3.Zero();
  27538. this._t2 = BABYLON.Vector3.Zero();
  27539. }
  27540. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  27541. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  27542. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  27543. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  27544. this._t1.subtractInPlace(this._t0);
  27545. this._t2.subtractInPlace(this._t0);
  27546. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27547. this._cachedTextureMatrix.m[0] = this._t1.x;
  27548. this._cachedTextureMatrix.m[1] = this._t1.y;
  27549. this._cachedTextureMatrix.m[2] = this._t1.z;
  27550. this._cachedTextureMatrix.m[4] = this._t2.x;
  27551. this._cachedTextureMatrix.m[5] = this._t2.y;
  27552. this._cachedTextureMatrix.m[6] = this._t2.z;
  27553. this._cachedTextureMatrix.m[8] = this._t0.x;
  27554. this._cachedTextureMatrix.m[9] = this._t0.y;
  27555. this._cachedTextureMatrix.m[10] = this._t0.z;
  27556. var scene = this.getScene();
  27557. if (!scene) {
  27558. return this._cachedTextureMatrix;
  27559. }
  27560. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  27561. return mat.hasTexture(_this);
  27562. });
  27563. return this._cachedTextureMatrix;
  27564. };
  27565. Texture.prototype.getReflectionTextureMatrix = function () {
  27566. var _this = this;
  27567. var scene = this.getScene();
  27568. if (!scene) {
  27569. return this._cachedTextureMatrix;
  27570. }
  27571. if (this.uOffset === this._cachedUOffset &&
  27572. this.vOffset === this._cachedVOffset &&
  27573. this.uScale === this._cachedUScale &&
  27574. this.vScale === this._cachedVScale &&
  27575. this.coordinatesMode === this._cachedCoordinatesMode) {
  27576. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  27577. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  27578. return this._cachedTextureMatrix;
  27579. }
  27580. }
  27581. else {
  27582. return this._cachedTextureMatrix;
  27583. }
  27584. }
  27585. if (!this._cachedTextureMatrix) {
  27586. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  27587. }
  27588. if (!this._projectionModeMatrix) {
  27589. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  27590. }
  27591. this._cachedUOffset = this.uOffset;
  27592. this._cachedVOffset = this.vOffset;
  27593. this._cachedUScale = this.uScale;
  27594. this._cachedVScale = this.vScale;
  27595. this._cachedCoordinatesMode = this.coordinatesMode;
  27596. switch (this.coordinatesMode) {
  27597. case Texture.PLANAR_MODE:
  27598. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27599. this._cachedTextureMatrix[0] = this.uScale;
  27600. this._cachedTextureMatrix[5] = this.vScale;
  27601. this._cachedTextureMatrix[12] = this.uOffset;
  27602. this._cachedTextureMatrix[13] = this.vOffset;
  27603. break;
  27604. case Texture.PROJECTION_MODE:
  27605. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  27606. this._projectionModeMatrix.m[0] = 0.5;
  27607. this._projectionModeMatrix.m[5] = -0.5;
  27608. this._projectionModeMatrix.m[10] = 0.0;
  27609. this._projectionModeMatrix.m[12] = 0.5;
  27610. this._projectionModeMatrix.m[13] = 0.5;
  27611. this._projectionModeMatrix.m[14] = 1.0;
  27612. this._projectionModeMatrix.m[15] = 1.0;
  27613. var projectionMatrix = scene.getProjectionMatrix();
  27614. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  27615. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  27616. break;
  27617. default:
  27618. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27619. break;
  27620. }
  27621. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  27622. return (mat.getActiveTextures().indexOf(_this) !== -1);
  27623. });
  27624. return this._cachedTextureMatrix;
  27625. };
  27626. Texture.prototype.clone = function () {
  27627. var _this = this;
  27628. return BABYLON.SerializationHelper.Clone(function () {
  27629. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  27630. }, this);
  27631. };
  27632. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  27633. get: function () {
  27634. if (!this._onLoadObservable) {
  27635. this._onLoadObservable = new BABYLON.Observable();
  27636. }
  27637. return this._onLoadObservable;
  27638. },
  27639. enumerable: true,
  27640. configurable: true
  27641. });
  27642. Texture.prototype.serialize = function () {
  27643. var serializationObject = _super.prototype.serialize.call(this);
  27644. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  27645. serializationObject.base64String = this._buffer;
  27646. serializationObject.name = serializationObject.name.replace("data:", "");
  27647. }
  27648. return serializationObject;
  27649. };
  27650. Texture.prototype.getClassName = function () {
  27651. return "Texture";
  27652. };
  27653. Texture.prototype.dispose = function () {
  27654. _super.prototype.dispose.call(this);
  27655. if (this.onLoadObservable) {
  27656. this.onLoadObservable.clear();
  27657. this._onLoadObservable = null;
  27658. }
  27659. this._delayedOnLoad = null;
  27660. this._delayedOnError = null;
  27661. };
  27662. // Statics
  27663. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  27664. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27665. if (onLoad === void 0) { onLoad = null; }
  27666. if (onError === void 0) { onError = null; }
  27667. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27668. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  27669. };
  27670. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  27671. if (parsedTexture.customType) {
  27672. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  27673. // Update Sampling Mode
  27674. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  27675. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  27676. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  27677. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  27678. }
  27679. }
  27680. return parsedCustomTexture;
  27681. }
  27682. if (parsedTexture.isCube) {
  27683. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  27684. }
  27685. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  27686. return null;
  27687. }
  27688. var texture = BABYLON.SerializationHelper.Parse(function () {
  27689. var generateMipMaps = true;
  27690. if (parsedTexture.noMipmap) {
  27691. generateMipMaps = false;
  27692. }
  27693. if (parsedTexture.mirrorPlane) {
  27694. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  27695. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  27696. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  27697. return mirrorTexture;
  27698. }
  27699. else if (parsedTexture.isRenderTarget) {
  27700. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  27701. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  27702. return renderTargetTexture;
  27703. }
  27704. else {
  27705. var texture;
  27706. if (parsedTexture.base64String) {
  27707. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  27708. }
  27709. else {
  27710. var url = rootUrl + parsedTexture.name;
  27711. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  27712. url = parsedTexture.url;
  27713. }
  27714. texture = new Texture(url, scene, !generateMipMaps);
  27715. }
  27716. return texture;
  27717. }
  27718. }, parsedTexture, scene);
  27719. // Update Sampling Mode
  27720. if (parsedTexture.samplingMode) {
  27721. var sampling = parsedTexture.samplingMode;
  27722. if (texture._samplingMode !== sampling) {
  27723. texture.updateSamplingMode(sampling);
  27724. }
  27725. }
  27726. // Animations
  27727. if (parsedTexture.animations) {
  27728. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  27729. var parsedAnimation = parsedTexture.animations[animationIndex];
  27730. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  27731. }
  27732. }
  27733. return texture;
  27734. };
  27735. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  27736. if (deleteBuffer === void 0) { deleteBuffer = false; }
  27737. if (noMipmap === void 0) { noMipmap = false; }
  27738. if (invertY === void 0) { invertY = true; }
  27739. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27740. if (onLoad === void 0) { onLoad = null; }
  27741. if (onError === void 0) { onError = null; }
  27742. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27743. if (name.substr(0, 5) !== "data:") {
  27744. name = "data:" + name;
  27745. }
  27746. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  27747. };
  27748. // Constants
  27749. Texture.NEAREST_SAMPLINGMODE = 1;
  27750. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  27751. Texture.BILINEAR_SAMPLINGMODE = 2;
  27752. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  27753. Texture.TRILINEAR_SAMPLINGMODE = 3;
  27754. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  27755. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  27756. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  27757. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  27758. Texture.NEAREST_LINEAR = 7;
  27759. Texture.NEAREST_NEAREST = 8;
  27760. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  27761. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  27762. Texture.LINEAR_LINEAR = 11;
  27763. Texture.LINEAR_NEAREST = 12;
  27764. Texture.EXPLICIT_MODE = 0;
  27765. Texture.SPHERICAL_MODE = 1;
  27766. Texture.PLANAR_MODE = 2;
  27767. Texture.CUBIC_MODE = 3;
  27768. Texture.PROJECTION_MODE = 4;
  27769. Texture.SKYBOX_MODE = 5;
  27770. Texture.INVCUBIC_MODE = 6;
  27771. Texture.EQUIRECTANGULAR_MODE = 7;
  27772. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  27773. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  27774. Texture.CLAMP_ADDRESSMODE = 0;
  27775. Texture.WRAP_ADDRESSMODE = 1;
  27776. Texture.MIRROR_ADDRESSMODE = 2;
  27777. /**
  27778. * 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
  27779. */
  27780. Texture.UseSerializedUrlIfAny = false;
  27781. __decorate([
  27782. BABYLON.serialize()
  27783. ], Texture.prototype, "url", void 0);
  27784. __decorate([
  27785. BABYLON.serialize()
  27786. ], Texture.prototype, "uOffset", void 0);
  27787. __decorate([
  27788. BABYLON.serialize()
  27789. ], Texture.prototype, "vOffset", void 0);
  27790. __decorate([
  27791. BABYLON.serialize()
  27792. ], Texture.prototype, "uScale", void 0);
  27793. __decorate([
  27794. BABYLON.serialize()
  27795. ], Texture.prototype, "vScale", void 0);
  27796. __decorate([
  27797. BABYLON.serialize()
  27798. ], Texture.prototype, "uAng", void 0);
  27799. __decorate([
  27800. BABYLON.serialize()
  27801. ], Texture.prototype, "vAng", void 0);
  27802. __decorate([
  27803. BABYLON.serialize()
  27804. ], Texture.prototype, "wAng", void 0);
  27805. __decorate([
  27806. BABYLON.serialize()
  27807. ], Texture.prototype, "isBlocking", null);
  27808. return Texture;
  27809. }(BABYLON.BaseTexture));
  27810. BABYLON.Texture = Texture;
  27811. })(BABYLON || (BABYLON = {}));
  27812. //# sourceMappingURL=babylon.texture.js.map
  27813. "use strict";
  27814. var BABYLON;
  27815. (function (BABYLON) {
  27816. var _InstancesBatch = /** @class */ (function () {
  27817. function _InstancesBatch() {
  27818. this.mustReturn = false;
  27819. this.visibleInstances = new Array();
  27820. this.renderSelf = new Array();
  27821. }
  27822. return _InstancesBatch;
  27823. }());
  27824. BABYLON._InstancesBatch = _InstancesBatch;
  27825. var Mesh = /** @class */ (function (_super) {
  27826. __extends(Mesh, _super);
  27827. /**
  27828. * @constructor
  27829. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  27830. * @param {Scene} scene The scene to add this mesh to.
  27831. * @param {Node} parent The parent of this mesh, if it has one
  27832. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  27833. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  27834. * When false, achieved by calling a clone(), also passing False.
  27835. * This will make creation of children, recursive.
  27836. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  27837. */
  27838. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  27839. if (scene === void 0) { scene = null; }
  27840. if (parent === void 0) { parent = null; }
  27841. if (source === void 0) { source = null; }
  27842. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  27843. var _this = _super.call(this, name, scene) || this;
  27844. // Events
  27845. /**
  27846. * An event triggered before rendering the mesh
  27847. * @type {BABYLON.Observable}
  27848. */
  27849. _this.onBeforeRenderObservable = new BABYLON.Observable();
  27850. /**
  27851. * An event triggered after rendering the mesh
  27852. * @type {BABYLON.Observable}
  27853. */
  27854. _this.onAfterRenderObservable = new BABYLON.Observable();
  27855. /**
  27856. * An event triggered before drawing the mesh
  27857. * @type {BABYLON.Observable}
  27858. */
  27859. _this.onBeforeDrawObservable = new BABYLON.Observable();
  27860. // Members
  27861. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27862. _this.instances = new Array();
  27863. _this._LODLevels = new Array();
  27864. _this._visibleInstances = {};
  27865. _this._renderIdForInstances = new Array();
  27866. _this._batchCache = new _InstancesBatch();
  27867. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  27868. // Use by builder only to know what orientation were the mesh build in.
  27869. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  27870. _this.overrideMaterialSideOrientation = null;
  27871. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  27872. // Will be used to save a source mesh reference, If any
  27873. _this._source = null;
  27874. scene = _this.getScene();
  27875. if (source) {
  27876. // Source mesh
  27877. _this._source = source;
  27878. // Geometry
  27879. if (source._geometry) {
  27880. source._geometry.applyToMesh(_this);
  27881. }
  27882. // Deep copy
  27883. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  27884. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen"], ["_poseMatrix", "_source"]);
  27885. // Metadata
  27886. if (source.metadata && source.metadata.clone) {
  27887. _this.metadata = source.metadata.clone();
  27888. }
  27889. else {
  27890. _this.metadata = source.metadata;
  27891. }
  27892. // Tags
  27893. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  27894. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  27895. }
  27896. // Parent
  27897. _this.parent = source.parent;
  27898. // Pivot
  27899. _this.setPivotMatrix(source.getPivotMatrix());
  27900. _this.id = name + "." + source.id;
  27901. // Material
  27902. _this.material = source.material;
  27903. var index;
  27904. if (!doNotCloneChildren) {
  27905. // Children
  27906. var directDescendants = source.getDescendants(true);
  27907. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  27908. var child = directDescendants[index_1];
  27909. if (child.clone) {
  27910. child.clone(name + "." + child.name, _this);
  27911. }
  27912. }
  27913. }
  27914. // Physics clone
  27915. var physicsEngine = _this.getScene().getPhysicsEngine();
  27916. if (clonePhysicsImpostor && physicsEngine) {
  27917. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  27918. if (impostor) {
  27919. _this.physicsImpostor = impostor.clone(_this);
  27920. }
  27921. }
  27922. // Particles
  27923. for (index = 0; index < scene.particleSystems.length; index++) {
  27924. var system = scene.particleSystems[index];
  27925. if (system.emitter === source) {
  27926. system.clone(system.name, _this);
  27927. }
  27928. }
  27929. _this.computeWorldMatrix(true);
  27930. }
  27931. // Parent
  27932. if (parent !== null) {
  27933. _this.parent = parent;
  27934. }
  27935. return _this;
  27936. }
  27937. Object.defineProperty(Mesh, "FRONTSIDE", {
  27938. /**
  27939. * Mesh side orientation : usually the external or front surface
  27940. */
  27941. get: function () {
  27942. return Mesh._FRONTSIDE;
  27943. },
  27944. enumerable: true,
  27945. configurable: true
  27946. });
  27947. Object.defineProperty(Mesh, "BACKSIDE", {
  27948. /**
  27949. * Mesh side orientation : usually the internal or back surface
  27950. */
  27951. get: function () {
  27952. return Mesh._BACKSIDE;
  27953. },
  27954. enumerable: true,
  27955. configurable: true
  27956. });
  27957. Object.defineProperty(Mesh, "DOUBLESIDE", {
  27958. /**
  27959. * Mesh side orientation : both internal and external or front and back surfaces
  27960. */
  27961. get: function () {
  27962. return Mesh._DOUBLESIDE;
  27963. },
  27964. enumerable: true,
  27965. configurable: true
  27966. });
  27967. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  27968. /**
  27969. * Mesh side orientation : by default, `FRONTSIDE`
  27970. */
  27971. get: function () {
  27972. return Mesh._DEFAULTSIDE;
  27973. },
  27974. enumerable: true,
  27975. configurable: true
  27976. });
  27977. Object.defineProperty(Mesh, "NO_CAP", {
  27978. /**
  27979. * Mesh cap setting : no cap
  27980. */
  27981. get: function () {
  27982. return Mesh._NO_CAP;
  27983. },
  27984. enumerable: true,
  27985. configurable: true
  27986. });
  27987. Object.defineProperty(Mesh, "CAP_START", {
  27988. /**
  27989. * Mesh cap setting : one cap at the beginning of the mesh
  27990. */
  27991. get: function () {
  27992. return Mesh._CAP_START;
  27993. },
  27994. enumerable: true,
  27995. configurable: true
  27996. });
  27997. Object.defineProperty(Mesh, "CAP_END", {
  27998. /**
  27999. * Mesh cap setting : one cap at the end of the mesh
  28000. */
  28001. get: function () {
  28002. return Mesh._CAP_END;
  28003. },
  28004. enumerable: true,
  28005. configurable: true
  28006. });
  28007. Object.defineProperty(Mesh, "CAP_ALL", {
  28008. /**
  28009. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  28010. */
  28011. get: function () {
  28012. return Mesh._CAP_ALL;
  28013. },
  28014. enumerable: true,
  28015. configurable: true
  28016. });
  28017. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  28018. set: function (callback) {
  28019. if (this._onBeforeDrawObserver) {
  28020. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  28021. }
  28022. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  28023. },
  28024. enumerable: true,
  28025. configurable: true
  28026. });
  28027. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  28028. get: function () {
  28029. return this._morphTargetManager;
  28030. },
  28031. set: function (value) {
  28032. if (this._morphTargetManager === value) {
  28033. return;
  28034. }
  28035. this._morphTargetManager = value;
  28036. this._syncGeometryWithMorphTargetManager();
  28037. },
  28038. enumerable: true,
  28039. configurable: true
  28040. });
  28041. Object.defineProperty(Mesh.prototype, "source", {
  28042. get: function () {
  28043. return this._source;
  28044. },
  28045. enumerable: true,
  28046. configurable: true
  28047. });
  28048. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  28049. get: function () {
  28050. return this._unIndexed;
  28051. },
  28052. set: function (value) {
  28053. if (this._unIndexed !== value) {
  28054. this._unIndexed = value;
  28055. this._markSubMeshesAsAttributesDirty();
  28056. }
  28057. },
  28058. enumerable: true,
  28059. configurable: true
  28060. });
  28061. // Methods
  28062. /**
  28063. * Returns the string "Mesh".
  28064. */
  28065. Mesh.prototype.getClassName = function () {
  28066. return "Mesh";
  28067. };
  28068. /**
  28069. * Returns a string.
  28070. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  28071. */
  28072. Mesh.prototype.toString = function (fullDetails) {
  28073. var ret = _super.prototype.toString.call(this, fullDetails);
  28074. ret += ", n vertices: " + this.getTotalVertices();
  28075. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  28076. if (this.animations) {
  28077. for (var i = 0; i < this.animations.length; i++) {
  28078. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  28079. }
  28080. }
  28081. if (fullDetails) {
  28082. if (this._geometry) {
  28083. var ib = this.getIndices();
  28084. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28085. if (vb && ib) {
  28086. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  28087. }
  28088. }
  28089. else {
  28090. ret += ", flat shading: UNKNOWN";
  28091. }
  28092. }
  28093. return ret;
  28094. };
  28095. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  28096. /**
  28097. * True if the mesh has some Levels Of Details (LOD).
  28098. * Returns a boolean.
  28099. */
  28100. get: function () {
  28101. return this._LODLevels.length > 0;
  28102. },
  28103. enumerable: true,
  28104. configurable: true
  28105. });
  28106. /**
  28107. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  28108. * @returns an array of {BABYLON.MeshLODLevel}
  28109. */
  28110. Mesh.prototype.getLODLevels = function () {
  28111. return this._LODLevels;
  28112. };
  28113. Mesh.prototype._sortLODLevels = function () {
  28114. this._LODLevels.sort(function (a, b) {
  28115. if (a.distance < b.distance) {
  28116. return 1;
  28117. }
  28118. if (a.distance > b.distance) {
  28119. return -1;
  28120. }
  28121. return 0;
  28122. });
  28123. };
  28124. /**
  28125. * Add a mesh as LOD level triggered at the given distance.
  28126. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  28127. * @param {number} distance The distance from the center of the object to show this level
  28128. * @param {Mesh} mesh The mesh to be added as LOD level
  28129. * @return {Mesh} This mesh (for chaining)
  28130. */
  28131. Mesh.prototype.addLODLevel = function (distance, mesh) {
  28132. if (mesh && mesh._masterMesh) {
  28133. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  28134. return this;
  28135. }
  28136. var level = new BABYLON.MeshLODLevel(distance, mesh);
  28137. this._LODLevels.push(level);
  28138. if (mesh) {
  28139. mesh._masterMesh = this;
  28140. }
  28141. this._sortLODLevels();
  28142. return this;
  28143. };
  28144. /**
  28145. * Returns the LOD level mesh at the passed distance or null if not found.
  28146. * It is related to the method `addLODLevel(distance, mesh)`.
  28147. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  28148. * Returns an object Mesh or `null`.
  28149. */
  28150. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  28151. for (var index = 0; index < this._LODLevels.length; index++) {
  28152. var level = this._LODLevels[index];
  28153. if (level.distance === distance) {
  28154. return level.mesh;
  28155. }
  28156. }
  28157. return null;
  28158. };
  28159. /**
  28160. * Remove a mesh from the LOD array
  28161. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  28162. * @param {Mesh} mesh The mesh to be removed.
  28163. * @return {Mesh} This mesh (for chaining)
  28164. */
  28165. Mesh.prototype.removeLODLevel = function (mesh) {
  28166. for (var index = 0; index < this._LODLevels.length; index++) {
  28167. if (this._LODLevels[index].mesh === mesh) {
  28168. this._LODLevels.splice(index, 1);
  28169. if (mesh) {
  28170. mesh._masterMesh = null;
  28171. }
  28172. }
  28173. }
  28174. this._sortLODLevels();
  28175. return this;
  28176. };
  28177. /**
  28178. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  28179. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  28180. */
  28181. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  28182. if (!this._LODLevels || this._LODLevels.length === 0) {
  28183. return this;
  28184. }
  28185. var bSphere;
  28186. if (boundingSphere) {
  28187. bSphere = boundingSphere;
  28188. }
  28189. else {
  28190. var boundingInfo = this.getBoundingInfo();
  28191. bSphere = boundingInfo.boundingSphere;
  28192. }
  28193. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  28194. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  28195. if (this.onLODLevelSelection) {
  28196. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  28197. }
  28198. return this;
  28199. }
  28200. for (var index = 0; index < this._LODLevels.length; index++) {
  28201. var level = this._LODLevels[index];
  28202. if (level.distance < distanceToCamera) {
  28203. if (level.mesh) {
  28204. level.mesh._preActivate();
  28205. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  28206. }
  28207. if (this.onLODLevelSelection) {
  28208. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  28209. }
  28210. return level.mesh;
  28211. }
  28212. }
  28213. if (this.onLODLevelSelection) {
  28214. this.onLODLevelSelection(distanceToCamera, this, this);
  28215. }
  28216. return this;
  28217. };
  28218. Object.defineProperty(Mesh.prototype, "geometry", {
  28219. /**
  28220. * Returns the mesh internal Geometry object.
  28221. */
  28222. get: function () {
  28223. return this._geometry;
  28224. },
  28225. enumerable: true,
  28226. configurable: true
  28227. });
  28228. /**
  28229. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  28230. */
  28231. Mesh.prototype.getTotalVertices = function () {
  28232. if (this._geometry === null || this._geometry === undefined) {
  28233. return 0;
  28234. }
  28235. return this._geometry.getTotalVertices();
  28236. };
  28237. /**
  28238. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  28239. * 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.
  28240. * You can force the copy with forceCopy === true
  28241. * Returns null if the mesh has no geometry or no vertex buffer.
  28242. * Possible `kind` values :
  28243. * - BABYLON.VertexBuffer.PositionKind
  28244. * - BABYLON.VertexBuffer.UVKind
  28245. * - BABYLON.VertexBuffer.UV2Kind
  28246. * - BABYLON.VertexBuffer.UV3Kind
  28247. * - BABYLON.VertexBuffer.UV4Kind
  28248. * - BABYLON.VertexBuffer.UV5Kind
  28249. * - BABYLON.VertexBuffer.UV6Kind
  28250. * - BABYLON.VertexBuffer.ColorKind
  28251. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28252. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28253. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28254. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28255. */
  28256. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  28257. if (!this._geometry) {
  28258. return null;
  28259. }
  28260. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  28261. };
  28262. /**
  28263. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  28264. * Returns `null` if the mesh has no geometry.
  28265. * Possible `kind` values :
  28266. * - BABYLON.VertexBuffer.PositionKind
  28267. * - BABYLON.VertexBuffer.UVKind
  28268. * - BABYLON.VertexBuffer.UV2Kind
  28269. * - BABYLON.VertexBuffer.UV3Kind
  28270. * - BABYLON.VertexBuffer.UV4Kind
  28271. * - BABYLON.VertexBuffer.UV5Kind
  28272. * - BABYLON.VertexBuffer.UV6Kind
  28273. * - BABYLON.VertexBuffer.ColorKind
  28274. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28275. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28276. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28277. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28278. */
  28279. Mesh.prototype.getVertexBuffer = function (kind) {
  28280. if (!this._geometry) {
  28281. return null;
  28282. }
  28283. return this._geometry.getVertexBuffer(kind);
  28284. };
  28285. /**
  28286. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  28287. * Possible `kind` values :
  28288. * - BABYLON.VertexBuffer.PositionKind
  28289. * - BABYLON.VertexBuffer.UVKind
  28290. * - BABYLON.VertexBuffer.UV2Kind
  28291. * - BABYLON.VertexBuffer.UV3Kind
  28292. * - BABYLON.VertexBuffer.UV4Kind
  28293. * - BABYLON.VertexBuffer.UV5Kind
  28294. * - BABYLON.VertexBuffer.UV6Kind
  28295. * - BABYLON.VertexBuffer.ColorKind
  28296. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28297. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28298. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28299. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28300. */
  28301. Mesh.prototype.isVerticesDataPresent = function (kind) {
  28302. if (!this._geometry) {
  28303. if (this._delayInfo) {
  28304. return this._delayInfo.indexOf(kind) !== -1;
  28305. }
  28306. return false;
  28307. }
  28308. return this._geometry.isVerticesDataPresent(kind);
  28309. };
  28310. /**
  28311. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  28312. * Possible `kind` values :
  28313. * - BABYLON.VertexBuffer.PositionKind
  28314. * - BABYLON.VertexBuffer.UVKind
  28315. * - BABYLON.VertexBuffer.UV2Kind
  28316. * - BABYLON.VertexBuffer.UV3Kind
  28317. * - BABYLON.VertexBuffer.UV4Kind
  28318. * - BABYLON.VertexBuffer.UV5Kind
  28319. * - BABYLON.VertexBuffer.UV6Kind
  28320. * - BABYLON.VertexBuffer.ColorKind
  28321. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28322. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28323. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28324. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28325. */
  28326. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  28327. if (!this._geometry) {
  28328. if (this._delayInfo) {
  28329. return this._delayInfo.indexOf(kind) !== -1;
  28330. }
  28331. return false;
  28332. }
  28333. return this._geometry.isVertexBufferUpdatable(kind);
  28334. };
  28335. /**
  28336. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  28337. * Possible `kind` values :
  28338. * - BABYLON.VertexBuffer.PositionKind
  28339. * - BABYLON.VertexBuffer.UVKind
  28340. * - BABYLON.VertexBuffer.UV2Kind
  28341. * - BABYLON.VertexBuffer.UV3Kind
  28342. * - BABYLON.VertexBuffer.UV4Kind
  28343. * - BABYLON.VertexBuffer.UV5Kind
  28344. * - BABYLON.VertexBuffer.UV6Kind
  28345. * - BABYLON.VertexBuffer.ColorKind
  28346. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28347. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28348. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28349. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28350. */
  28351. Mesh.prototype.getVerticesDataKinds = function () {
  28352. if (!this._geometry) {
  28353. var result = new Array();
  28354. if (this._delayInfo) {
  28355. this._delayInfo.forEach(function (kind, index, array) {
  28356. result.push(kind);
  28357. });
  28358. }
  28359. return result;
  28360. }
  28361. return this._geometry.getVerticesDataKinds();
  28362. };
  28363. /**
  28364. * Returns a positive integer : the total number of indices in this mesh geometry.
  28365. * Returns zero if the mesh has no geometry.
  28366. */
  28367. Mesh.prototype.getTotalIndices = function () {
  28368. if (!this._geometry) {
  28369. return 0;
  28370. }
  28371. return this._geometry.getTotalIndices();
  28372. };
  28373. /**
  28374. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  28375. * 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.
  28376. * Returns an empty array if the mesh has no geometry.
  28377. */
  28378. Mesh.prototype.getIndices = function (copyWhenShared) {
  28379. if (!this._geometry) {
  28380. return [];
  28381. }
  28382. return this._geometry.getIndices(copyWhenShared);
  28383. };
  28384. Object.defineProperty(Mesh.prototype, "isBlocked", {
  28385. get: function () {
  28386. return this._masterMesh !== null && this._masterMesh !== undefined;
  28387. },
  28388. enumerable: true,
  28389. configurable: true
  28390. });
  28391. /**
  28392. * Determine if the current mesh is ready to be rendered
  28393. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  28394. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  28395. * @returns true if all associated assets are ready (material, textures, shaders)
  28396. */
  28397. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  28398. if (completeCheck === void 0) { completeCheck = false; }
  28399. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  28400. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  28401. return false;
  28402. }
  28403. if (!_super.prototype.isReady.call(this, completeCheck)) {
  28404. return false;
  28405. }
  28406. if (!this.subMeshes || this.subMeshes.length === 0) {
  28407. return true;
  28408. }
  28409. if (!completeCheck) {
  28410. return true;
  28411. }
  28412. var engine = this.getEngine();
  28413. var scene = this.getScene();
  28414. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  28415. this.computeWorldMatrix();
  28416. var mat = this.material || scene.defaultMaterial;
  28417. if (mat) {
  28418. if (mat.storeEffectOnSubMeshes) {
  28419. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  28420. var subMesh = _a[_i];
  28421. var effectiveMaterial = subMesh.getMaterial();
  28422. if (effectiveMaterial) {
  28423. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  28424. return false;
  28425. }
  28426. }
  28427. }
  28428. }
  28429. else {
  28430. if (!mat.isReady(this, hardwareInstancedRendering)) {
  28431. return false;
  28432. }
  28433. }
  28434. }
  28435. // Shadows
  28436. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  28437. var light = _c[_b];
  28438. var generator = light.getShadowGenerator();
  28439. if (generator) {
  28440. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  28441. var subMesh = _e[_d];
  28442. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  28443. return false;
  28444. }
  28445. }
  28446. }
  28447. }
  28448. // LOD
  28449. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  28450. var lod = _g[_f];
  28451. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  28452. return false;
  28453. }
  28454. }
  28455. return true;
  28456. };
  28457. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  28458. /**
  28459. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  28460. * This property is pertinent only for updatable parametric shapes.
  28461. */
  28462. get: function () {
  28463. return this._areNormalsFrozen;
  28464. },
  28465. enumerable: true,
  28466. configurable: true
  28467. });
  28468. /**
  28469. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  28470. * It has no effect at all on other shapes.
  28471. * It prevents the mesh normals from being recomputed on next `positions` array update.
  28472. * Returns the Mesh.
  28473. */
  28474. Mesh.prototype.freezeNormals = function () {
  28475. this._areNormalsFrozen = true;
  28476. return this;
  28477. };
  28478. /**
  28479. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  28480. * It has no effect at all on other shapes.
  28481. * It reactivates the mesh normals computation if it was previously frozen.
  28482. * Returns the Mesh.
  28483. */
  28484. Mesh.prototype.unfreezeNormals = function () {
  28485. this._areNormalsFrozen = false;
  28486. return this;
  28487. };
  28488. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  28489. /**
  28490. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  28491. */
  28492. set: function (count) {
  28493. this._overridenInstanceCount = count;
  28494. },
  28495. enumerable: true,
  28496. configurable: true
  28497. });
  28498. // Methods
  28499. Mesh.prototype._preActivate = function () {
  28500. var sceneRenderId = this.getScene().getRenderId();
  28501. if (this._preActivateId === sceneRenderId) {
  28502. return this;
  28503. }
  28504. this._preActivateId = sceneRenderId;
  28505. this._visibleInstances = null;
  28506. return this;
  28507. };
  28508. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  28509. if (this._visibleInstances) {
  28510. this._visibleInstances.intermediateDefaultRenderId = renderId;
  28511. }
  28512. return this;
  28513. };
  28514. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  28515. if (!this._visibleInstances) {
  28516. this._visibleInstances = {};
  28517. this._visibleInstances.defaultRenderId = renderId;
  28518. this._visibleInstances.selfDefaultRenderId = this._renderId;
  28519. }
  28520. if (!this._visibleInstances[renderId]) {
  28521. this._visibleInstances[renderId] = new Array();
  28522. }
  28523. this._visibleInstances[renderId].push(instance);
  28524. return this;
  28525. };
  28526. /**
  28527. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  28528. * This means the mesh underlying bounding box and sphere are recomputed.
  28529. * Returns the Mesh.
  28530. */
  28531. Mesh.prototype.refreshBoundingInfo = function () {
  28532. return this._refreshBoundingInfo(false);
  28533. };
  28534. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  28535. if (this._boundingInfo && this._boundingInfo.isLocked) {
  28536. return this;
  28537. }
  28538. var data = this._getPositionData(applySkeleton);
  28539. if (data) {
  28540. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  28541. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  28542. }
  28543. if (this.subMeshes) {
  28544. for (var index = 0; index < this.subMeshes.length; index++) {
  28545. this.subMeshes[index].refreshBoundingInfo();
  28546. }
  28547. }
  28548. this._updateBoundingInfo();
  28549. return this;
  28550. };
  28551. Mesh.prototype._getPositionData = function (applySkeleton) {
  28552. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28553. if (data && applySkeleton && this.skeleton) {
  28554. data = BABYLON.Tools.Slice(data);
  28555. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  28556. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  28557. if (matricesWeightsData && matricesIndicesData) {
  28558. var needExtras = this.numBoneInfluencers > 4;
  28559. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  28560. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  28561. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  28562. var tempVector = BABYLON.Tmp.Vector3[0];
  28563. var finalMatrix = BABYLON.Tmp.Matrix[0];
  28564. var tempMatrix = BABYLON.Tmp.Matrix[1];
  28565. var matWeightIdx = 0;
  28566. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  28567. finalMatrix.reset();
  28568. var inf;
  28569. var weight;
  28570. for (inf = 0; inf < 4; inf++) {
  28571. weight = matricesWeightsData[matWeightIdx + inf];
  28572. if (weight <= 0)
  28573. break;
  28574. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  28575. finalMatrix.addToSelf(tempMatrix);
  28576. }
  28577. if (needExtras) {
  28578. for (inf = 0; inf < 4; inf++) {
  28579. weight = matricesWeightsExtraData[matWeightIdx + inf];
  28580. if (weight <= 0)
  28581. break;
  28582. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  28583. finalMatrix.addToSelf(tempMatrix);
  28584. }
  28585. }
  28586. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  28587. tempVector.toArray(data, index);
  28588. }
  28589. }
  28590. }
  28591. return data;
  28592. };
  28593. Mesh.prototype._createGlobalSubMesh = function (force) {
  28594. var totalVertices = this.getTotalVertices();
  28595. if (!totalVertices || !this.getIndices()) {
  28596. return null;
  28597. }
  28598. // Check if we need to recreate the submeshes
  28599. if (this.subMeshes && this.subMeshes.length > 0) {
  28600. var ib = this.getIndices();
  28601. if (!ib) {
  28602. return null;
  28603. }
  28604. var totalIndices = ib.length;
  28605. var needToRecreate = false;
  28606. if (force) {
  28607. needToRecreate = true;
  28608. }
  28609. else {
  28610. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  28611. var submesh = _a[_i];
  28612. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  28613. needToRecreate = true;
  28614. break;
  28615. }
  28616. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  28617. needToRecreate = true;
  28618. break;
  28619. }
  28620. }
  28621. }
  28622. if (!needToRecreate) {
  28623. return this.subMeshes[0];
  28624. }
  28625. }
  28626. this.releaseSubMeshes();
  28627. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  28628. };
  28629. Mesh.prototype.subdivide = function (count) {
  28630. if (count < 1) {
  28631. return;
  28632. }
  28633. var totalIndices = this.getTotalIndices();
  28634. var subdivisionSize = (totalIndices / count) | 0;
  28635. var offset = 0;
  28636. // Ensure that subdivisionSize is a multiple of 3
  28637. while (subdivisionSize % 3 !== 0) {
  28638. subdivisionSize++;
  28639. }
  28640. this.releaseSubMeshes();
  28641. for (var index = 0; index < count; index++) {
  28642. if (offset >= totalIndices) {
  28643. break;
  28644. }
  28645. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  28646. offset += subdivisionSize;
  28647. }
  28648. this.synchronizeInstances();
  28649. };
  28650. /**
  28651. * Sets the vertex data of the mesh geometry for the requested `kind`.
  28652. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  28653. * The `data` are either a numeric array either a Float32Array.
  28654. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  28655. * 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).
  28656. * Note that a new underlying VertexBuffer object is created each call.
  28657. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  28658. *
  28659. * Possible `kind` values :
  28660. * - BABYLON.VertexBuffer.PositionKind
  28661. * - BABYLON.VertexBuffer.UVKind
  28662. * - BABYLON.VertexBuffer.UV2Kind
  28663. * - BABYLON.VertexBuffer.UV3Kind
  28664. * - BABYLON.VertexBuffer.UV4Kind
  28665. * - BABYLON.VertexBuffer.UV5Kind
  28666. * - BABYLON.VertexBuffer.UV6Kind
  28667. * - BABYLON.VertexBuffer.ColorKind
  28668. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28669. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28670. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28671. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28672. *
  28673. * Returns the Mesh.
  28674. */
  28675. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  28676. if (updatable === void 0) { updatable = false; }
  28677. if (!this._geometry) {
  28678. var vertexData = new BABYLON.VertexData();
  28679. vertexData.set(data, kind);
  28680. var scene = this.getScene();
  28681. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  28682. }
  28683. else {
  28684. this._geometry.setVerticesData(kind, data, updatable, stride);
  28685. }
  28686. return this;
  28687. };
  28688. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  28689. if (updatable === void 0) { updatable = true; }
  28690. var vb = this.getVertexBuffer(kind);
  28691. if (!vb || vb.isUpdatable() === updatable) {
  28692. return;
  28693. }
  28694. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  28695. };
  28696. /**
  28697. * Sets the mesh VertexBuffer.
  28698. * Returns the Mesh.
  28699. */
  28700. Mesh.prototype.setVerticesBuffer = function (buffer) {
  28701. if (!this._geometry) {
  28702. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  28703. }
  28704. this._geometry.setVerticesBuffer(buffer);
  28705. return this;
  28706. };
  28707. /**
  28708. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  28709. * If the mesh has no geometry, it is simply returned as it is.
  28710. * The `data` are either a numeric array either a Float32Array.
  28711. * No new underlying VertexBuffer object is created.
  28712. * 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.
  28713. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  28714. *
  28715. * Possible `kind` values :
  28716. * - BABYLON.VertexBuffer.PositionKind
  28717. * - BABYLON.VertexBuffer.UVKind
  28718. * - BABYLON.VertexBuffer.UV2Kind
  28719. * - BABYLON.VertexBuffer.UV3Kind
  28720. * - BABYLON.VertexBuffer.UV4Kind
  28721. * - BABYLON.VertexBuffer.UV5Kind
  28722. * - BABYLON.VertexBuffer.UV6Kind
  28723. * - BABYLON.VertexBuffer.ColorKind
  28724. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28725. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28726. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28727. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28728. *
  28729. * Returns the Mesh.
  28730. */
  28731. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  28732. if (!this._geometry) {
  28733. return this;
  28734. }
  28735. if (!makeItUnique) {
  28736. this._geometry.updateVerticesData(kind, data, updateExtends);
  28737. }
  28738. else {
  28739. this.makeGeometryUnique();
  28740. this.updateVerticesData(kind, data, updateExtends, false);
  28741. }
  28742. return this;
  28743. };
  28744. /**
  28745. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  28746. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  28747. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  28748. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  28749. * Returns the Mesh.
  28750. */
  28751. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  28752. if (computeNormals === void 0) { computeNormals = true; }
  28753. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28754. if (!positions) {
  28755. return this;
  28756. }
  28757. positionFunction(positions);
  28758. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  28759. if (computeNormals) {
  28760. var indices = this.getIndices();
  28761. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28762. if (!normals) {
  28763. return this;
  28764. }
  28765. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  28766. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  28767. }
  28768. return this;
  28769. };
  28770. /**
  28771. * Creates a un-shared specific occurence of the geometry for the mesh.
  28772. * Returns the Mesh.
  28773. */
  28774. Mesh.prototype.makeGeometryUnique = function () {
  28775. if (!this._geometry) {
  28776. return this;
  28777. }
  28778. var oldGeometry = this._geometry;
  28779. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  28780. oldGeometry.releaseForMesh(this, true);
  28781. geometry.applyToMesh(this);
  28782. return this;
  28783. };
  28784. /**
  28785. * Sets the mesh indices.
  28786. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  28787. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  28788. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  28789. * This method creates a new index buffer each call.
  28790. * Returns the Mesh.
  28791. */
  28792. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  28793. if (totalVertices === void 0) { totalVertices = null; }
  28794. if (updatable === void 0) { updatable = false; }
  28795. if (!this._geometry) {
  28796. var vertexData = new BABYLON.VertexData();
  28797. vertexData.indices = indices;
  28798. var scene = this.getScene();
  28799. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  28800. }
  28801. else {
  28802. this._geometry.setIndices(indices, totalVertices, updatable);
  28803. }
  28804. return this;
  28805. };
  28806. /**
  28807. * Update the current index buffer
  28808. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  28809. * Returns the Mesh.
  28810. */
  28811. Mesh.prototype.updateIndices = function (indices, offset) {
  28812. if (!this._geometry) {
  28813. return this;
  28814. }
  28815. this._geometry.updateIndices(indices, offset);
  28816. return this;
  28817. };
  28818. /**
  28819. * Invert the geometry to move from a right handed system to a left handed one.
  28820. * Returns the Mesh.
  28821. */
  28822. Mesh.prototype.toLeftHanded = function () {
  28823. if (!this._geometry) {
  28824. return this;
  28825. }
  28826. this._geometry.toLeftHanded();
  28827. return this;
  28828. };
  28829. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  28830. if (!this._geometry) {
  28831. return this;
  28832. }
  28833. var engine = this.getScene().getEngine();
  28834. // Wireframe
  28835. var indexToBind;
  28836. if (this._unIndexed) {
  28837. indexToBind = null;
  28838. }
  28839. else {
  28840. switch (fillMode) {
  28841. case BABYLON.Material.PointFillMode:
  28842. indexToBind = null;
  28843. break;
  28844. case BABYLON.Material.WireFrameFillMode:
  28845. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  28846. break;
  28847. default:
  28848. case BABYLON.Material.TriangleFillMode:
  28849. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  28850. break;
  28851. }
  28852. }
  28853. // VBOs
  28854. this._geometry._bind(effect, indexToBind);
  28855. return this;
  28856. };
  28857. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  28858. if (alternate === void 0) { alternate = false; }
  28859. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  28860. return this;
  28861. }
  28862. this.onBeforeDrawObservable.notifyObservers(this);
  28863. var scene = this.getScene();
  28864. var engine = scene.getEngine();
  28865. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  28866. // or triangles as points
  28867. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  28868. }
  28869. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  28870. // Triangles as wireframe
  28871. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  28872. }
  28873. else {
  28874. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  28875. }
  28876. if (scene._isAlternateRenderingEnabled && !alternate) {
  28877. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  28878. if (!effect || !scene.activeCamera) {
  28879. return this;
  28880. }
  28881. scene._switchToAlternateCameraConfiguration(true);
  28882. this._effectiveMaterial.bindView(effect);
  28883. this._effectiveMaterial.bindViewProjection(effect);
  28884. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  28885. this._draw(subMesh, fillMode, instancesCount, true);
  28886. engine.setViewport(scene.activeCamera.viewport);
  28887. scene._switchToAlternateCameraConfiguration(false);
  28888. this._effectiveMaterial.bindView(effect);
  28889. this._effectiveMaterial.bindViewProjection(effect);
  28890. }
  28891. return this;
  28892. };
  28893. /**
  28894. * Registers for this mesh a javascript function called just before the rendering process.
  28895. * This function is passed the current mesh.
  28896. * Return the Mesh.
  28897. */
  28898. Mesh.prototype.registerBeforeRender = function (func) {
  28899. this.onBeforeRenderObservable.add(func);
  28900. return this;
  28901. };
  28902. /**
  28903. * Disposes a previously registered javascript function called before the rendering.
  28904. * This function is passed the current mesh.
  28905. * Returns the Mesh.
  28906. */
  28907. Mesh.prototype.unregisterBeforeRender = function (func) {
  28908. this.onBeforeRenderObservable.removeCallback(func);
  28909. return this;
  28910. };
  28911. /**
  28912. * Registers for this mesh a javascript function called just after the rendering is complete.
  28913. * This function is passed the current mesh.
  28914. * Returns the Mesh.
  28915. */
  28916. Mesh.prototype.registerAfterRender = function (func) {
  28917. this.onAfterRenderObservable.add(func);
  28918. return this;
  28919. };
  28920. /**
  28921. * Disposes a previously registered javascript function called after the rendering.
  28922. * This function is passed the current mesh.
  28923. * Return the Mesh.
  28924. */
  28925. Mesh.prototype.unregisterAfterRender = function (func) {
  28926. this.onAfterRenderObservable.removeCallback(func);
  28927. return this;
  28928. };
  28929. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  28930. var scene = this.getScene();
  28931. this._batchCache.mustReturn = false;
  28932. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  28933. this._batchCache.visibleInstances[subMeshId] = null;
  28934. if (this._visibleInstances) {
  28935. var currentRenderId = scene.getRenderId();
  28936. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  28937. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  28938. var selfRenderId = this._renderId;
  28939. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  28940. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  28941. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  28942. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  28943. }
  28944. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  28945. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  28946. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  28947. this._batchCache.mustReturn = true;
  28948. return this._batchCache;
  28949. }
  28950. if (currentRenderId !== selfRenderId) {
  28951. this._batchCache.renderSelf[subMeshId] = false;
  28952. }
  28953. }
  28954. this._renderIdForInstances[subMeshId] = currentRenderId;
  28955. }
  28956. return this._batchCache;
  28957. };
  28958. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  28959. var visibleInstances = batch.visibleInstances[subMesh._id];
  28960. if (!visibleInstances) {
  28961. return this;
  28962. }
  28963. var matricesCount = visibleInstances.length + 1;
  28964. var bufferSize = matricesCount * 16 * 4;
  28965. var currentInstancesBufferSize = this._instancesBufferSize;
  28966. var instancesBuffer = this._instancesBuffer;
  28967. while (this._instancesBufferSize < bufferSize) {
  28968. this._instancesBufferSize *= 2;
  28969. }
  28970. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  28971. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  28972. }
  28973. var offset = 0;
  28974. var instancesCount = 0;
  28975. var world = this.getWorldMatrix();
  28976. if (batch.renderSelf[subMesh._id]) {
  28977. world.copyToArray(this._instancesData, offset);
  28978. offset += 16;
  28979. instancesCount++;
  28980. }
  28981. if (visibleInstances) {
  28982. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  28983. var instance = visibleInstances[instanceIndex];
  28984. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  28985. offset += 16;
  28986. instancesCount++;
  28987. }
  28988. }
  28989. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  28990. if (instancesBuffer) {
  28991. instancesBuffer.dispose();
  28992. }
  28993. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  28994. this._instancesBuffer = instancesBuffer;
  28995. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  28996. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  28997. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  28998. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  28999. }
  29000. else {
  29001. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  29002. }
  29003. this._bind(subMesh, effect, fillMode);
  29004. this._draw(subMesh, fillMode, instancesCount);
  29005. engine.unbindInstanceAttributes();
  29006. return this;
  29007. };
  29008. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  29009. var scene = this.getScene();
  29010. var engine = scene.getEngine();
  29011. if (hardwareInstancedRendering) {
  29012. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  29013. }
  29014. else {
  29015. if (batch.renderSelf[subMesh._id]) {
  29016. // Draw
  29017. if (onBeforeDraw) {
  29018. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  29019. }
  29020. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  29021. }
  29022. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  29023. if (visibleInstancesForSubMesh) {
  29024. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  29025. var instance = visibleInstancesForSubMesh[instanceIndex];
  29026. // World
  29027. var world = instance.getWorldMatrix();
  29028. if (onBeforeDraw) {
  29029. onBeforeDraw(true, world, effectiveMaterial);
  29030. }
  29031. // Draw
  29032. this._draw(subMesh, fillMode);
  29033. }
  29034. }
  29035. }
  29036. return this;
  29037. };
  29038. /**
  29039. * Triggers the draw call for the mesh.
  29040. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  29041. * Returns the Mesh.
  29042. */
  29043. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  29044. this.checkOcclusionQuery();
  29045. if (this._isOccluded) {
  29046. return this;
  29047. }
  29048. var scene = this.getScene();
  29049. // Managing instances
  29050. var batch = this._getInstancesRenderList(subMesh._id);
  29051. if (batch.mustReturn) {
  29052. return this;
  29053. }
  29054. // Checking geometry state
  29055. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  29056. return this;
  29057. }
  29058. this.onBeforeRenderObservable.notifyObservers(this);
  29059. var engine = scene.getEngine();
  29060. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  29061. // Material
  29062. var material = subMesh.getMaterial();
  29063. if (!material) {
  29064. return this;
  29065. }
  29066. this._effectiveMaterial = material;
  29067. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  29068. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  29069. return this;
  29070. }
  29071. }
  29072. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  29073. return this;
  29074. }
  29075. // Alpha mode
  29076. if (enableAlphaMode) {
  29077. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  29078. }
  29079. // Outline - step 1
  29080. var savedDepthWrite = engine.getDepthWrite();
  29081. if (this.renderOutline) {
  29082. engine.setDepthWrite(false);
  29083. scene.getOutlineRenderer().render(subMesh, batch);
  29084. engine.setDepthWrite(savedDepthWrite);
  29085. }
  29086. var effect;
  29087. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  29088. effect = subMesh.effect;
  29089. }
  29090. else {
  29091. effect = this._effectiveMaterial.getEffect();
  29092. }
  29093. if (!effect) {
  29094. return this;
  29095. }
  29096. var sideOrientation = this.overrideMaterialSideOrientation;
  29097. if (sideOrientation == null) {
  29098. sideOrientation = this._effectiveMaterial.sideOrientation;
  29099. if (this._getWorldMatrixDeterminant() < 0) {
  29100. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  29101. }
  29102. }
  29103. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  29104. if (this._effectiveMaterial.forceDepthWrite) {
  29105. engine.setDepthWrite(true);
  29106. }
  29107. // Bind
  29108. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  29109. if (!hardwareInstancedRendering) {
  29110. this._bind(subMesh, effect, fillMode);
  29111. }
  29112. var world = this.getWorldMatrix();
  29113. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  29114. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  29115. }
  29116. else {
  29117. this._effectiveMaterial.bind(world, this);
  29118. }
  29119. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  29120. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  29121. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  29122. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  29123. }
  29124. // Draw
  29125. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  29126. // Unbind
  29127. this._effectiveMaterial.unbind();
  29128. // Outline - step 2
  29129. if (this.renderOutline && savedDepthWrite) {
  29130. engine.setDepthWrite(true);
  29131. engine.setColorWrite(false);
  29132. scene.getOutlineRenderer().render(subMesh, batch);
  29133. engine.setColorWrite(true);
  29134. }
  29135. // Overlay
  29136. if (this.renderOverlay) {
  29137. var currentMode = engine.getAlphaMode();
  29138. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  29139. scene.getOutlineRenderer().render(subMesh, batch, true);
  29140. engine.setAlphaMode(currentMode);
  29141. }
  29142. this.onAfterRenderObservable.notifyObservers(this);
  29143. return this;
  29144. };
  29145. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  29146. if (isInstance && effectiveMaterial) {
  29147. effectiveMaterial.bindOnlyWorldMatrix(world);
  29148. }
  29149. };
  29150. /**
  29151. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  29152. */
  29153. Mesh.prototype.getEmittedParticleSystems = function () {
  29154. var results = new Array();
  29155. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  29156. var particleSystem = this.getScene().particleSystems[index];
  29157. if (particleSystem.emitter === this) {
  29158. results.push(particleSystem);
  29159. }
  29160. }
  29161. return results;
  29162. };
  29163. /**
  29164. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  29165. */
  29166. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  29167. var results = new Array();
  29168. var descendants = this.getDescendants();
  29169. descendants.push(this);
  29170. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  29171. var particleSystem = this.getScene().particleSystems[index];
  29172. var emitter = particleSystem.emitter;
  29173. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  29174. results.push(particleSystem);
  29175. }
  29176. }
  29177. return results;
  29178. };
  29179. Mesh.prototype._checkDelayState = function () {
  29180. var scene = this.getScene();
  29181. if (this._geometry) {
  29182. this._geometry.load(scene);
  29183. }
  29184. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  29185. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  29186. this._queueLoad(scene);
  29187. }
  29188. return this;
  29189. };
  29190. Mesh.prototype._queueLoad = function (scene) {
  29191. var _this = this;
  29192. scene._addPendingData(this);
  29193. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  29194. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  29195. if (data instanceof ArrayBuffer) {
  29196. _this._delayLoadingFunction(data, _this);
  29197. }
  29198. else {
  29199. _this._delayLoadingFunction(JSON.parse(data), _this);
  29200. }
  29201. _this.instances.forEach(function (instance) {
  29202. instance._syncSubMeshes();
  29203. });
  29204. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  29205. scene._removePendingData(_this);
  29206. }, function () { }, scene.database, getBinaryData);
  29207. return this;
  29208. };
  29209. /**
  29210. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  29211. */
  29212. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  29213. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  29214. return false;
  29215. }
  29216. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  29217. return false;
  29218. }
  29219. this._checkDelayState();
  29220. return true;
  29221. };
  29222. /**
  29223. * Sets the mesh material by the material or multiMaterial `id` property.
  29224. * The material `id` is a string identifying the material or the multiMaterial.
  29225. * This method returns the Mesh.
  29226. */
  29227. Mesh.prototype.setMaterialByID = function (id) {
  29228. var materials = this.getScene().materials;
  29229. var index;
  29230. for (index = materials.length - 1; index > -1; index--) {
  29231. if (materials[index].id === id) {
  29232. this.material = materials[index];
  29233. return this;
  29234. }
  29235. }
  29236. // Multi
  29237. var multiMaterials = this.getScene().multiMaterials;
  29238. for (index = multiMaterials.length - 1; index > -1; index--) {
  29239. if (multiMaterials[index].id === id) {
  29240. this.material = multiMaterials[index];
  29241. return this;
  29242. }
  29243. }
  29244. return this;
  29245. };
  29246. /**
  29247. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  29248. */
  29249. Mesh.prototype.getAnimatables = function () {
  29250. var results = new Array();
  29251. if (this.material) {
  29252. results.push(this.material);
  29253. }
  29254. if (this.skeleton) {
  29255. results.push(this.skeleton);
  29256. }
  29257. return results;
  29258. };
  29259. /**
  29260. * Modifies the mesh geometry according to the passed transformation matrix.
  29261. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  29262. * The mesh normals are modified accordingly the same transformation.
  29263. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  29264. * Note that, under the hood, this method sets a new VertexBuffer each call.
  29265. * Returns the Mesh.
  29266. */
  29267. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  29268. // Position
  29269. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  29270. return this;
  29271. }
  29272. var submeshes = this.subMeshes.splice(0);
  29273. this._resetPointsArrayCache();
  29274. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29275. var temp = new Array();
  29276. var index;
  29277. for (index = 0; index < data.length; index += 3) {
  29278. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  29279. }
  29280. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  29281. // Normals
  29282. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29283. return this;
  29284. }
  29285. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29286. temp = [];
  29287. for (index = 0; index < data.length; index += 3) {
  29288. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  29289. }
  29290. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  29291. // flip faces?
  29292. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  29293. this.flipFaces();
  29294. }
  29295. // Restore submeshes
  29296. this.releaseSubMeshes();
  29297. this.subMeshes = submeshes;
  29298. return this;
  29299. };
  29300. /**
  29301. * Modifies the mesh geometry according to its own current World Matrix.
  29302. * The mesh World Matrix is then reset.
  29303. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  29304. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  29305. * Note that, under the hood, this method sets a new VertexBuffer each call.
  29306. * Returns the Mesh.
  29307. */
  29308. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  29309. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  29310. this.scaling.copyFromFloats(1, 1, 1);
  29311. this.position.copyFromFloats(0, 0, 0);
  29312. this.rotation.copyFromFloats(0, 0, 0);
  29313. //only if quaternion is already set
  29314. if (this.rotationQuaternion) {
  29315. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  29316. }
  29317. this._worldMatrix = BABYLON.Matrix.Identity();
  29318. return this;
  29319. };
  29320. Object.defineProperty(Mesh.prototype, "_positions", {
  29321. // Cache
  29322. get: function () {
  29323. if (this._geometry) {
  29324. return this._geometry._positions;
  29325. }
  29326. return null;
  29327. },
  29328. enumerable: true,
  29329. configurable: true
  29330. });
  29331. Mesh.prototype._resetPointsArrayCache = function () {
  29332. if (this._geometry) {
  29333. this._geometry._resetPointsArrayCache();
  29334. }
  29335. return this;
  29336. };
  29337. Mesh.prototype._generatePointsArray = function () {
  29338. if (this._geometry) {
  29339. return this._geometry._generatePointsArray();
  29340. }
  29341. return false;
  29342. };
  29343. /**
  29344. * Returns a new Mesh object generated from the current mesh properties.
  29345. * This method must not get confused with createInstance().
  29346. * The parameter `name` is a string, the name given to the new mesh.
  29347. * The optional parameter `newParent` can be any Node object (default `null`).
  29348. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  29349. * 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.
  29350. */
  29351. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  29352. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  29353. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  29354. };
  29355. /**
  29356. * Releases resources associated with this mesh.
  29357. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  29358. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  29359. */
  29360. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  29361. var _this = this;
  29362. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  29363. this.morphTargetManager = null;
  29364. if (this._geometry) {
  29365. this._geometry.releaseForMesh(this, true);
  29366. }
  29367. // Sources
  29368. var meshes = this.getScene().meshes;
  29369. meshes.forEach(function (abstractMesh) {
  29370. var mesh = abstractMesh;
  29371. if (mesh._source && mesh._source === _this) {
  29372. mesh._source = null;
  29373. }
  29374. });
  29375. this._source = null;
  29376. // Instances
  29377. if (this._instancesBuffer) {
  29378. this._instancesBuffer.dispose();
  29379. this._instancesBuffer = null;
  29380. }
  29381. while (this.instances.length) {
  29382. this.instances[0].dispose();
  29383. }
  29384. // Effect layers.
  29385. var effectLayers = this.getScene().effectLayers;
  29386. for (var i = 0; i < effectLayers.length; i++) {
  29387. var effectLayer = effectLayers[i];
  29388. if (effectLayer) {
  29389. effectLayer._disposeMesh(this);
  29390. }
  29391. }
  29392. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  29393. };
  29394. /**
  29395. * Modifies the mesh geometry according to a displacement map.
  29396. * 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.
  29397. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  29398. * This method returns nothing.
  29399. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  29400. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  29401. * 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.
  29402. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  29403. * The parameter `uvScale` is an optional vector2 used to scale UV.
  29404. *
  29405. * Returns the Mesh.
  29406. */
  29407. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  29408. var _this = this;
  29409. var scene = this.getScene();
  29410. var onload = function (img) {
  29411. // Getting height map data
  29412. var canvas = document.createElement("canvas");
  29413. var context = canvas.getContext("2d");
  29414. var heightMapWidth = img.width;
  29415. var heightMapHeight = img.height;
  29416. canvas.width = heightMapWidth;
  29417. canvas.height = heightMapHeight;
  29418. context.drawImage(img, 0, 0);
  29419. // Create VertexData from map data
  29420. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  29421. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  29422. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  29423. //execute success callback, if set
  29424. if (onSuccess) {
  29425. onSuccess(_this);
  29426. }
  29427. };
  29428. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  29429. return this;
  29430. };
  29431. /**
  29432. * Modifies the mesh geometry according to a displacementMap buffer.
  29433. * 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.
  29434. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  29435. * This method returns nothing.
  29436. * 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.
  29437. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  29438. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  29439. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  29440. * The parameter `uvScale` is an optional vector2 used to scale UV.
  29441. *
  29442. * Returns the Mesh.
  29443. */
  29444. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  29445. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  29446. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  29447. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29448. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  29449. return this;
  29450. }
  29451. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29452. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29453. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  29454. var position = BABYLON.Vector3.Zero();
  29455. var normal = BABYLON.Vector3.Zero();
  29456. var uv = BABYLON.Vector2.Zero();
  29457. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  29458. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  29459. for (var index = 0; index < positions.length; index += 3) {
  29460. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  29461. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  29462. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  29463. // Compute height
  29464. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  29465. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  29466. var pos = (u + v * heightMapWidth) * 4;
  29467. var r = buffer[pos] / 255.0;
  29468. var g = buffer[pos + 1] / 255.0;
  29469. var b = buffer[pos + 2] / 255.0;
  29470. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  29471. normal.normalize();
  29472. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  29473. position = position.add(normal);
  29474. position.toArray(positions, index);
  29475. }
  29476. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  29477. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  29478. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  29479. return this;
  29480. };
  29481. /**
  29482. * Modify the mesh to get a flat shading rendering.
  29483. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  29484. * This method returns the Mesh.
  29485. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  29486. */
  29487. Mesh.prototype.convertToFlatShadedMesh = function () {
  29488. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  29489. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  29490. var kinds = this.getVerticesDataKinds();
  29491. var vbs = {};
  29492. var data = {};
  29493. var newdata = {};
  29494. var updatableNormals = false;
  29495. var kindIndex;
  29496. var kind;
  29497. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29498. kind = kinds[kindIndex];
  29499. var vertexBuffer = this.getVertexBuffer(kind);
  29500. if (kind === BABYLON.VertexBuffer.NormalKind) {
  29501. updatableNormals = vertexBuffer.isUpdatable();
  29502. kinds.splice(kindIndex, 1);
  29503. kindIndex--;
  29504. continue;
  29505. }
  29506. vbs[kind] = vertexBuffer;
  29507. data[kind] = vbs[kind].getData();
  29508. newdata[kind] = [];
  29509. }
  29510. // Save previous submeshes
  29511. var previousSubmeshes = this.subMeshes.slice(0);
  29512. var indices = this.getIndices();
  29513. var totalIndices = this.getTotalIndices();
  29514. // Generating unique vertices per face
  29515. var index;
  29516. for (index = 0; index < totalIndices; index++) {
  29517. var vertexIndex = indices[index];
  29518. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29519. kind = kinds[kindIndex];
  29520. var stride = vbs[kind].getStrideSize();
  29521. for (var offset = 0; offset < stride; offset++) {
  29522. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  29523. }
  29524. }
  29525. }
  29526. // Updating faces & normal
  29527. var normals = [];
  29528. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  29529. for (index = 0; index < totalIndices; index += 3) {
  29530. indices[index] = index;
  29531. indices[index + 1] = index + 1;
  29532. indices[index + 2] = index + 2;
  29533. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  29534. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  29535. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  29536. var p1p2 = p1.subtract(p2);
  29537. var p3p2 = p3.subtract(p2);
  29538. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  29539. // Store same normals for every vertex
  29540. for (var localIndex = 0; localIndex < 3; localIndex++) {
  29541. normals.push(normal.x);
  29542. normals.push(normal.y);
  29543. normals.push(normal.z);
  29544. }
  29545. }
  29546. this.setIndices(indices);
  29547. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  29548. // Updating vertex buffers
  29549. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29550. kind = kinds[kindIndex];
  29551. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  29552. }
  29553. // Updating submeshes
  29554. this.releaseSubMeshes();
  29555. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  29556. var previousOne = previousSubmeshes[submeshIndex];
  29557. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  29558. }
  29559. this.synchronizeInstances();
  29560. return this;
  29561. };
  29562. /**
  29563. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  29564. * In other words, more vertices, no more indices and a single bigger VBO.
  29565. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  29566. * Returns the Mesh.
  29567. */
  29568. Mesh.prototype.convertToUnIndexedMesh = function () {
  29569. /// <summary>Remove indices by unfolding faces into buffers</summary>
  29570. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  29571. var kinds = this.getVerticesDataKinds();
  29572. var vbs = {};
  29573. var data = {};
  29574. var newdata = {};
  29575. var kindIndex;
  29576. var kind;
  29577. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29578. kind = kinds[kindIndex];
  29579. var vertexBuffer = this.getVertexBuffer(kind);
  29580. vbs[kind] = vertexBuffer;
  29581. data[kind] = vbs[kind].getData();
  29582. newdata[kind] = [];
  29583. }
  29584. // Save previous submeshes
  29585. var previousSubmeshes = this.subMeshes.slice(0);
  29586. var indices = this.getIndices();
  29587. var totalIndices = this.getTotalIndices();
  29588. // Generating unique vertices per face
  29589. var index;
  29590. for (index = 0; index < totalIndices; index++) {
  29591. var vertexIndex = indices[index];
  29592. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29593. kind = kinds[kindIndex];
  29594. var stride = vbs[kind].getStrideSize();
  29595. for (var offset = 0; offset < stride; offset++) {
  29596. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  29597. }
  29598. }
  29599. }
  29600. // Updating indices
  29601. for (index = 0; index < totalIndices; index += 3) {
  29602. indices[index] = index;
  29603. indices[index + 1] = index + 1;
  29604. indices[index + 2] = index + 2;
  29605. }
  29606. this.setIndices(indices);
  29607. // Updating vertex buffers
  29608. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29609. kind = kinds[kindIndex];
  29610. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  29611. }
  29612. // Updating submeshes
  29613. this.releaseSubMeshes();
  29614. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  29615. var previousOne = previousSubmeshes[submeshIndex];
  29616. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  29617. }
  29618. this._unIndexed = true;
  29619. this.synchronizeInstances();
  29620. return this;
  29621. };
  29622. /**
  29623. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  29624. * This method returns the Mesh.
  29625. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  29626. */
  29627. Mesh.prototype.flipFaces = function (flipNormals) {
  29628. if (flipNormals === void 0) { flipNormals = false; }
  29629. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  29630. var i;
  29631. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  29632. for (i = 0; i < vertex_data.normals.length; i++) {
  29633. vertex_data.normals[i] *= -1;
  29634. }
  29635. }
  29636. if (vertex_data.indices) {
  29637. var temp;
  29638. for (i = 0; i < vertex_data.indices.length; i += 3) {
  29639. // reassign indices
  29640. temp = vertex_data.indices[i + 1];
  29641. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  29642. vertex_data.indices[i + 2] = temp;
  29643. }
  29644. }
  29645. vertex_data.applyToMesh(this);
  29646. return this;
  29647. };
  29648. // Instances
  29649. /**
  29650. * Creates a new InstancedMesh object from the mesh model.
  29651. * An instance shares the same properties and the same material than its model.
  29652. * Only these properties of each instance can then be set individually :
  29653. * - position
  29654. * - rotation
  29655. * - rotationQuaternion
  29656. * - setPivotMatrix
  29657. * - scaling
  29658. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  29659. * Warning : this method is not supported for Line mesh and LineSystem
  29660. */
  29661. Mesh.prototype.createInstance = function (name) {
  29662. return new BABYLON.InstancedMesh(name, this);
  29663. };
  29664. /**
  29665. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  29666. * After this call, all the mesh instances have the same submeshes than the current mesh.
  29667. * This method returns the Mesh.
  29668. */
  29669. Mesh.prototype.synchronizeInstances = function () {
  29670. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  29671. var instance = this.instances[instanceIndex];
  29672. instance._syncSubMeshes();
  29673. }
  29674. return this;
  29675. };
  29676. /**
  29677. * Simplify the mesh according to the given array of settings.
  29678. * Function will return immediately and will simplify async. It returns the Mesh.
  29679. * @param settings a collection of simplification settings.
  29680. * @param parallelProcessing should all levels calculate parallel or one after the other.
  29681. * @param type the type of simplification to run.
  29682. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  29683. */
  29684. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  29685. if (parallelProcessing === void 0) { parallelProcessing = true; }
  29686. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  29687. this.getScene().simplificationQueue.addTask({
  29688. settings: settings,
  29689. parallelProcessing: parallelProcessing,
  29690. mesh: this,
  29691. simplificationType: simplificationType,
  29692. successCallback: successCallback
  29693. });
  29694. return this;
  29695. };
  29696. /**
  29697. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  29698. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  29699. * This should be used together with the simplification to avoid disappearing triangles.
  29700. * Returns the Mesh.
  29701. * @param successCallback an optional success callback to be called after the optimization finished.
  29702. */
  29703. Mesh.prototype.optimizeIndices = function (successCallback) {
  29704. var _this = this;
  29705. var indices = this.getIndices();
  29706. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29707. if (!positions || !indices) {
  29708. return this;
  29709. }
  29710. var vectorPositions = new Array();
  29711. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  29712. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  29713. }
  29714. var dupes = new Array();
  29715. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  29716. var realPos = vectorPositions.length - 1 - iteration;
  29717. var testedPosition = vectorPositions[realPos];
  29718. for (var j = 0; j < realPos; ++j) {
  29719. var againstPosition = vectorPositions[j];
  29720. if (testedPosition.equals(againstPosition)) {
  29721. dupes[realPos] = j;
  29722. break;
  29723. }
  29724. }
  29725. }, function () {
  29726. for (var i = 0; i < indices.length; ++i) {
  29727. indices[i] = dupes[indices[i]] || indices[i];
  29728. }
  29729. //indices are now reordered
  29730. var originalSubMeshes = _this.subMeshes.slice(0);
  29731. _this.setIndices(indices);
  29732. _this.subMeshes = originalSubMeshes;
  29733. if (successCallback) {
  29734. successCallback(_this);
  29735. }
  29736. });
  29737. return this;
  29738. };
  29739. Mesh.prototype.serialize = function (serializationObject) {
  29740. serializationObject.name = this.name;
  29741. serializationObject.id = this.id;
  29742. serializationObject.type = this.getClassName();
  29743. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  29744. serializationObject.tags = BABYLON.Tags.GetTags(this);
  29745. }
  29746. serializationObject.position = this.position.asArray();
  29747. if (this.rotationQuaternion) {
  29748. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  29749. }
  29750. else if (this.rotation) {
  29751. serializationObject.rotation = this.rotation.asArray();
  29752. }
  29753. serializationObject.scaling = this.scaling.asArray();
  29754. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  29755. serializationObject.isEnabled = this.isEnabled(false);
  29756. serializationObject.isVisible = this.isVisible;
  29757. serializationObject.infiniteDistance = this.infiniteDistance;
  29758. serializationObject.pickable = this.isPickable;
  29759. serializationObject.receiveShadows = this.receiveShadows;
  29760. serializationObject.billboardMode = this.billboardMode;
  29761. serializationObject.visibility = this.visibility;
  29762. serializationObject.checkCollisions = this.checkCollisions;
  29763. serializationObject.isBlocker = this.isBlocker;
  29764. // Parent
  29765. if (this.parent) {
  29766. serializationObject.parentId = this.parent.id;
  29767. }
  29768. // Geometry
  29769. serializationObject.isUnIndexed = this.isUnIndexed;
  29770. var geometry = this._geometry;
  29771. if (geometry) {
  29772. var geometryId = geometry.id;
  29773. serializationObject.geometryId = geometryId;
  29774. // SubMeshes
  29775. serializationObject.subMeshes = [];
  29776. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  29777. var subMesh = this.subMeshes[subIndex];
  29778. serializationObject.subMeshes.push({
  29779. materialIndex: subMesh.materialIndex,
  29780. verticesStart: subMesh.verticesStart,
  29781. verticesCount: subMesh.verticesCount,
  29782. indexStart: subMesh.indexStart,
  29783. indexCount: subMesh.indexCount
  29784. });
  29785. }
  29786. }
  29787. // Material
  29788. if (this.material) {
  29789. serializationObject.materialId = this.material.id;
  29790. }
  29791. else {
  29792. this.material = null;
  29793. }
  29794. // Morph targets
  29795. if (this.morphTargetManager) {
  29796. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  29797. }
  29798. // Skeleton
  29799. if (this.skeleton) {
  29800. serializationObject.skeletonId = this.skeleton.id;
  29801. }
  29802. // Physics
  29803. //TODO implement correct serialization for physics impostors.
  29804. var impostor = this.getPhysicsImpostor();
  29805. if (impostor) {
  29806. serializationObject.physicsMass = impostor.getParam("mass");
  29807. serializationObject.physicsFriction = impostor.getParam("friction");
  29808. serializationObject.physicsRestitution = impostor.getParam("mass");
  29809. serializationObject.physicsImpostor = impostor.type;
  29810. }
  29811. // Metadata
  29812. if (this.metadata) {
  29813. serializationObject.metadata = this.metadata;
  29814. }
  29815. // Instances
  29816. serializationObject.instances = [];
  29817. for (var index = 0; index < this.instances.length; index++) {
  29818. var instance = this.instances[index];
  29819. var serializationInstance = {
  29820. name: instance.name,
  29821. id: instance.id,
  29822. position: instance.position.asArray(),
  29823. scaling: instance.scaling.asArray()
  29824. };
  29825. if (instance.rotationQuaternion) {
  29826. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  29827. }
  29828. else if (instance.rotation) {
  29829. serializationInstance.rotation = instance.rotation.asArray();
  29830. }
  29831. serializationObject.instances.push(serializationInstance);
  29832. // Animations
  29833. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  29834. serializationInstance.ranges = instance.serializeAnimationRanges();
  29835. }
  29836. //
  29837. // Animations
  29838. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  29839. serializationObject.ranges = this.serializeAnimationRanges();
  29840. // Layer mask
  29841. serializationObject.layerMask = this.layerMask;
  29842. // Alpha
  29843. serializationObject.alphaIndex = this.alphaIndex;
  29844. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  29845. // Overlay
  29846. serializationObject.overlayAlpha = this.overlayAlpha;
  29847. serializationObject.overlayColor = this.overlayColor.asArray();
  29848. serializationObject.renderOverlay = this.renderOverlay;
  29849. // Fog
  29850. serializationObject.applyFog = this.applyFog;
  29851. // Action Manager
  29852. if (this.actionManager) {
  29853. serializationObject.actions = this.actionManager.serialize(this.name);
  29854. }
  29855. };
  29856. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  29857. if (!this.geometry) {
  29858. return;
  29859. }
  29860. this._markSubMeshesAsAttributesDirty();
  29861. var morphTargetManager = this._morphTargetManager;
  29862. if (morphTargetManager && morphTargetManager.vertexCount) {
  29863. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  29864. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  29865. this.morphTargetManager = null;
  29866. return;
  29867. }
  29868. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  29869. var morphTarget = morphTargetManager.getActiveTarget(index);
  29870. var positions = morphTarget.getPositions();
  29871. if (!positions) {
  29872. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  29873. return;
  29874. }
  29875. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  29876. var normals = morphTarget.getNormals();
  29877. if (normals) {
  29878. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  29879. }
  29880. var tangents = morphTarget.getTangents();
  29881. if (tangents) {
  29882. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  29883. }
  29884. }
  29885. }
  29886. else {
  29887. var index = 0;
  29888. // Positions
  29889. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  29890. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  29891. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  29892. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  29893. }
  29894. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  29895. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  29896. }
  29897. index++;
  29898. }
  29899. }
  29900. };
  29901. // Statics
  29902. /**
  29903. * Returns a new Mesh object parsed from the source provided.
  29904. * The parameter `parsedMesh` is the source.
  29905. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  29906. */
  29907. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  29908. var mesh;
  29909. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  29910. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  29911. }
  29912. else {
  29913. mesh = new Mesh(parsedMesh.name, scene);
  29914. }
  29915. mesh.id = parsedMesh.id;
  29916. if (BABYLON.Tags) {
  29917. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  29918. }
  29919. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  29920. if (parsedMesh.metadata !== undefined) {
  29921. mesh.metadata = parsedMesh.metadata;
  29922. }
  29923. if (parsedMesh.rotationQuaternion) {
  29924. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  29925. }
  29926. else if (parsedMesh.rotation) {
  29927. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  29928. }
  29929. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  29930. if (parsedMesh.localMatrix) {
  29931. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  29932. }
  29933. else if (parsedMesh.pivotMatrix) {
  29934. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  29935. }
  29936. mesh.setEnabled(parsedMesh.isEnabled);
  29937. mesh.isVisible = parsedMesh.isVisible;
  29938. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  29939. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  29940. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  29941. if (parsedMesh.applyFog !== undefined) {
  29942. mesh.applyFog = parsedMesh.applyFog;
  29943. }
  29944. if (parsedMesh.pickable !== undefined) {
  29945. mesh.isPickable = parsedMesh.pickable;
  29946. }
  29947. if (parsedMesh.alphaIndex !== undefined) {
  29948. mesh.alphaIndex = parsedMesh.alphaIndex;
  29949. }
  29950. mesh.receiveShadows = parsedMesh.receiveShadows;
  29951. mesh.billboardMode = parsedMesh.billboardMode;
  29952. if (parsedMesh.visibility !== undefined) {
  29953. mesh.visibility = parsedMesh.visibility;
  29954. }
  29955. mesh.checkCollisions = parsedMesh.checkCollisions;
  29956. if (parsedMesh.isBlocker !== undefined) {
  29957. mesh.isBlocker = parsedMesh.isBlocker;
  29958. }
  29959. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  29960. // freezeWorldMatrix
  29961. if (parsedMesh.freezeWorldMatrix) {
  29962. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  29963. }
  29964. // Parent
  29965. if (parsedMesh.parentId) {
  29966. mesh._waitingParentId = parsedMesh.parentId;
  29967. }
  29968. // Actions
  29969. if (parsedMesh.actions !== undefined) {
  29970. mesh._waitingActions = parsedMesh.actions;
  29971. }
  29972. // Overlay
  29973. if (parsedMesh.overlayAlpha !== undefined) {
  29974. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  29975. }
  29976. if (parsedMesh.overlayColor !== undefined) {
  29977. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  29978. }
  29979. if (parsedMesh.renderOverlay !== undefined) {
  29980. mesh.renderOverlay = parsedMesh.renderOverlay;
  29981. }
  29982. // Geometry
  29983. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  29984. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  29985. if (parsedMesh.delayLoadingFile) {
  29986. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  29987. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  29988. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  29989. if (parsedMesh._binaryInfo) {
  29990. mesh._binaryInfo = parsedMesh._binaryInfo;
  29991. }
  29992. mesh._delayInfo = [];
  29993. if (parsedMesh.hasUVs) {
  29994. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  29995. }
  29996. if (parsedMesh.hasUVs2) {
  29997. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  29998. }
  29999. if (parsedMesh.hasUVs3) {
  30000. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  30001. }
  30002. if (parsedMesh.hasUVs4) {
  30003. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  30004. }
  30005. if (parsedMesh.hasUVs5) {
  30006. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  30007. }
  30008. if (parsedMesh.hasUVs6) {
  30009. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  30010. }
  30011. if (parsedMesh.hasColors) {
  30012. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  30013. }
  30014. if (parsedMesh.hasMatricesIndices) {
  30015. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  30016. }
  30017. if (parsedMesh.hasMatricesWeights) {
  30018. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  30019. }
  30020. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  30021. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  30022. mesh._checkDelayState();
  30023. }
  30024. }
  30025. else {
  30026. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  30027. }
  30028. // Material
  30029. if (parsedMesh.materialId) {
  30030. mesh.setMaterialByID(parsedMesh.materialId);
  30031. }
  30032. else {
  30033. mesh.material = null;
  30034. }
  30035. // Morph targets
  30036. if (parsedMesh.morphTargetManagerId > -1) {
  30037. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  30038. }
  30039. // Skeleton
  30040. if (parsedMesh.skeletonId > -1) {
  30041. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  30042. if (parsedMesh.numBoneInfluencers) {
  30043. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  30044. }
  30045. }
  30046. // Animations
  30047. if (parsedMesh.animations) {
  30048. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  30049. var parsedAnimation = parsedMesh.animations[animationIndex];
  30050. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  30051. }
  30052. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  30053. }
  30054. if (parsedMesh.autoAnimate) {
  30055. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  30056. }
  30057. // Layer Mask
  30058. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  30059. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  30060. }
  30061. else {
  30062. mesh.layerMask = 0x0FFFFFFF;
  30063. }
  30064. // Physics
  30065. if (parsedMesh.physicsImpostor) {
  30066. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  30067. mass: parsedMesh.physicsMass,
  30068. friction: parsedMesh.physicsFriction,
  30069. restitution: parsedMesh.physicsRestitution
  30070. }, scene);
  30071. }
  30072. // Instances
  30073. if (parsedMesh.instances) {
  30074. for (var index = 0; index < parsedMesh.instances.length; index++) {
  30075. var parsedInstance = parsedMesh.instances[index];
  30076. var instance = mesh.createInstance(parsedInstance.name);
  30077. if (parsedInstance.id) {
  30078. instance.id = parsedInstance.id;
  30079. }
  30080. if (BABYLON.Tags) {
  30081. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  30082. }
  30083. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  30084. if (parsedInstance.parentId) {
  30085. instance._waitingParentId = parsedInstance.parentId;
  30086. }
  30087. if (parsedInstance.rotationQuaternion) {
  30088. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  30089. }
  30090. else if (parsedInstance.rotation) {
  30091. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  30092. }
  30093. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  30094. instance.checkCollisions = mesh.checkCollisions;
  30095. if (parsedMesh.animations) {
  30096. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  30097. parsedAnimation = parsedMesh.animations[animationIndex];
  30098. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  30099. }
  30100. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  30101. }
  30102. }
  30103. }
  30104. return mesh;
  30105. };
  30106. /**
  30107. * Creates a ribbon mesh.
  30108. * Please consider using the same method from the MeshBuilder class instead.
  30109. * 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.
  30110. *
  30111. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  30112. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  30113. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  30114. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  30115. * 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.
  30116. * 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.
  30117. * 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
  30118. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30119. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30120. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30121. */
  30122. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  30123. if (closeArray === void 0) { closeArray = false; }
  30124. if (updatable === void 0) { updatable = false; }
  30125. return BABYLON.MeshBuilder.CreateRibbon(name, {
  30126. pathArray: pathArray,
  30127. closeArray: closeArray,
  30128. closePath: closePath,
  30129. offset: offset,
  30130. updatable: updatable,
  30131. sideOrientation: sideOrientation,
  30132. instance: instance
  30133. }, scene);
  30134. };
  30135. /**
  30136. * Creates a plane polygonal mesh. By default, this is a disc.
  30137. * Please consider using the same method from the MeshBuilder class instead.
  30138. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  30139. * 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.
  30140. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30141. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30142. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30143. */
  30144. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  30145. if (scene === void 0) { scene = null; }
  30146. var options = {
  30147. radius: radius,
  30148. tessellation: tessellation,
  30149. sideOrientation: sideOrientation,
  30150. updatable: updatable
  30151. };
  30152. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  30153. };
  30154. /**
  30155. * Creates a box mesh.
  30156. * Please consider using the same method from the MeshBuilder class instead.
  30157. * The parameter `size` sets the size (float) of each box side (default 1).
  30158. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30159. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30160. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30161. */
  30162. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  30163. if (scene === void 0) { scene = null; }
  30164. var options = {
  30165. size: size,
  30166. sideOrientation: sideOrientation,
  30167. updatable: updatable
  30168. };
  30169. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  30170. };
  30171. /**
  30172. * Creates a sphere mesh.
  30173. * Please consider using the same method from the MeshBuilder class instead.
  30174. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  30175. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  30176. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30177. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30178. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30179. */
  30180. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  30181. var options = {
  30182. segments: segments,
  30183. diameterX: diameter,
  30184. diameterY: diameter,
  30185. diameterZ: diameter,
  30186. sideOrientation: sideOrientation,
  30187. updatable: updatable
  30188. };
  30189. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  30190. };
  30191. /**
  30192. * Creates a cylinder or a cone mesh.
  30193. * Please consider using the same method from the MeshBuilder class instead.
  30194. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  30195. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  30196. * 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.
  30197. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  30198. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  30199. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30200. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30201. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30202. */
  30203. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  30204. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  30205. if (scene !== undefined) {
  30206. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  30207. updatable = scene;
  30208. }
  30209. scene = subdivisions;
  30210. subdivisions = 1;
  30211. }
  30212. var options = {
  30213. height: height,
  30214. diameterTop: diameterTop,
  30215. diameterBottom: diameterBottom,
  30216. tessellation: tessellation,
  30217. subdivisions: subdivisions,
  30218. sideOrientation: sideOrientation,
  30219. updatable: updatable
  30220. };
  30221. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  30222. };
  30223. // Torus (Code from SharpDX.org)
  30224. /**
  30225. * Creates a torus mesh.
  30226. * Please consider using the same method from the MeshBuilder class instead.
  30227. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  30228. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  30229. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  30230. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30231. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30232. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30233. */
  30234. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  30235. var options = {
  30236. diameter: diameter,
  30237. thickness: thickness,
  30238. tessellation: tessellation,
  30239. sideOrientation: sideOrientation,
  30240. updatable: updatable
  30241. };
  30242. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  30243. };
  30244. /**
  30245. * Creates a torus knot mesh.
  30246. * Please consider using the same method from the MeshBuilder class instead.
  30247. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  30248. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  30249. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  30250. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  30251. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30252. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30253. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30254. */
  30255. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  30256. var options = {
  30257. radius: radius,
  30258. tube: tube,
  30259. radialSegments: radialSegments,
  30260. tubularSegments: tubularSegments,
  30261. p: p,
  30262. q: q,
  30263. sideOrientation: sideOrientation,
  30264. updatable: updatable
  30265. };
  30266. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  30267. };
  30268. /**
  30269. * Creates a line mesh.
  30270. * Please consider using the same method from the MeshBuilder class instead.
  30271. * 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.
  30272. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  30273. * The parameter `points` is an array successive Vector3.
  30274. * 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
  30275. * When updating an instance, remember that only point positions can change, not the number of points.
  30276. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30277. */
  30278. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  30279. if (scene === void 0) { scene = null; }
  30280. if (updatable === void 0) { updatable = false; }
  30281. if (instance === void 0) { instance = null; }
  30282. var options = {
  30283. points: points,
  30284. updatable: updatable,
  30285. instance: instance
  30286. };
  30287. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  30288. };
  30289. /**
  30290. * Creates a dashed line mesh.
  30291. * Please consider using the same method from the MeshBuilder class instead.
  30292. * 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.
  30293. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  30294. * The parameter `points` is an array successive Vector3.
  30295. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  30296. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  30297. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  30298. * 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
  30299. * When updating an instance, remember that only point positions can change, not the number of points.
  30300. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30301. */
  30302. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  30303. if (scene === void 0) { scene = null; }
  30304. var options = {
  30305. points: points,
  30306. dashSize: dashSize,
  30307. gapSize: gapSize,
  30308. dashNb: dashNb,
  30309. updatable: updatable,
  30310. instance: instance
  30311. };
  30312. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  30313. };
  30314. /**
  30315. * Creates a polygon mesh.
  30316. * Please consider using the same method from the MeshBuilder class instead.
  30317. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  30318. * 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.
  30319. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30320. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30321. * Remember you can only change the shape positions, not their number when updating a polygon.
  30322. */
  30323. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  30324. var options = {
  30325. shape: shape,
  30326. holes: holes,
  30327. updatable: updatable,
  30328. sideOrientation: sideOrientation
  30329. };
  30330. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  30331. };
  30332. /**
  30333. * Creates an extruded polygon mesh, with depth in the Y direction.
  30334. * Please consider using the same method from the MeshBuilder class instead.
  30335. */
  30336. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  30337. var options = {
  30338. shape: shape,
  30339. holes: holes,
  30340. depth: depth,
  30341. updatable: updatable,
  30342. sideOrientation: sideOrientation
  30343. };
  30344. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  30345. };
  30346. /**
  30347. * Creates an extruded shape mesh.
  30348. * 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.
  30349. * Please consider using the same method from the MeshBuilder class instead.
  30350. *
  30351. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  30352. * 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
  30353. * extruded along the Z axis.
  30354. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  30355. * 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.
  30356. * The parameter `scale` (float, default 1) is the value to scale the shape.
  30357. * 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
  30358. * 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
  30359. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  30360. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30361. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30362. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30363. */
  30364. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  30365. if (scene === void 0) { scene = null; }
  30366. var options = {
  30367. shape: shape,
  30368. path: path,
  30369. scale: scale,
  30370. rotation: rotation,
  30371. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  30372. sideOrientation: sideOrientation,
  30373. instance: instance,
  30374. updatable: updatable
  30375. };
  30376. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  30377. };
  30378. /**
  30379. * Creates an custom extruded shape mesh.
  30380. * 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.
  30381. * Please consider using the same method from the MeshBuilder class instead.
  30382. *
  30383. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  30384. * 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
  30385. * extruded along the Z axis.
  30386. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  30387. * 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
  30388. * and the distance of this point from the begining of the path :
  30389. * ```javascript
  30390. * var rotationFunction = function(i, distance) {
  30391. * // do things
  30392. * return rotationValue; }
  30393. * ```
  30394. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  30395. * 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
  30396. * and the distance of this point from the begining of the path :
  30397. * ```javascript
  30398. * var scaleFunction = function(i, distance) {
  30399. * // do things
  30400. * return scaleValue;}
  30401. * ```
  30402. * It must returns a float value that will be the scale value applied to the shape on each path point.
  30403. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  30404. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  30405. * 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
  30406. * 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
  30407. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  30408. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30409. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30410. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30411. */
  30412. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  30413. var options = {
  30414. shape: shape,
  30415. path: path,
  30416. scaleFunction: scaleFunction,
  30417. rotationFunction: rotationFunction,
  30418. ribbonCloseArray: ribbonCloseArray,
  30419. ribbonClosePath: ribbonClosePath,
  30420. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  30421. sideOrientation: sideOrientation,
  30422. instance: instance,
  30423. updatable: updatable
  30424. };
  30425. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  30426. };
  30427. /**
  30428. * Creates lathe mesh.
  30429. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  30430. * Please consider using the same method from the MeshBuilder class instead.
  30431. * 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
  30432. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  30433. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  30434. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  30435. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30436. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30437. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30438. */
  30439. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  30440. var options = {
  30441. shape: shape,
  30442. radius: radius,
  30443. tessellation: tessellation,
  30444. sideOrientation: sideOrientation,
  30445. updatable: updatable
  30446. };
  30447. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  30448. };
  30449. /**
  30450. * Creates a plane mesh.
  30451. * Please consider using the same method from the MeshBuilder class instead.
  30452. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  30453. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30454. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30455. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30456. */
  30457. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  30458. var options = {
  30459. size: size,
  30460. width: size,
  30461. height: size,
  30462. sideOrientation: sideOrientation,
  30463. updatable: updatable
  30464. };
  30465. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  30466. };
  30467. /**
  30468. * Creates a ground mesh.
  30469. * Please consider using the same method from the MeshBuilder class instead.
  30470. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  30471. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  30472. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30473. */
  30474. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  30475. var options = {
  30476. width: width,
  30477. height: height,
  30478. subdivisions: subdivisions,
  30479. updatable: updatable
  30480. };
  30481. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  30482. };
  30483. /**
  30484. * Creates a tiled ground mesh.
  30485. * Please consider using the same method from the MeshBuilder class instead.
  30486. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  30487. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  30488. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  30489. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  30490. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  30491. * numbers of subdivisions on the ground width and height of each tile.
  30492. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30493. */
  30494. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  30495. var options = {
  30496. xmin: xmin,
  30497. zmin: zmin,
  30498. xmax: xmax,
  30499. zmax: zmax,
  30500. subdivisions: subdivisions,
  30501. precision: precision,
  30502. updatable: updatable
  30503. };
  30504. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  30505. };
  30506. /**
  30507. * Creates a ground mesh from a height map.
  30508. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  30509. * Please consider using the same method from the MeshBuilder class instead.
  30510. * The parameter `url` sets the URL of the height map image resource.
  30511. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  30512. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  30513. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  30514. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  30515. * 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).
  30516. * This function is passed the newly built mesh :
  30517. * ```javascript
  30518. * function(mesh) { // do things
  30519. * return; }
  30520. * ```
  30521. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30522. */
  30523. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  30524. var options = {
  30525. width: width,
  30526. height: height,
  30527. subdivisions: subdivisions,
  30528. minHeight: minHeight,
  30529. maxHeight: maxHeight,
  30530. updatable: updatable,
  30531. onReady: onReady
  30532. };
  30533. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  30534. };
  30535. /**
  30536. * Creates a tube mesh.
  30537. * 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.
  30538. * Please consider using the same method from the MeshBuilder class instead.
  30539. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  30540. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  30541. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  30542. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  30543. * 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.
  30544. * It must return a radius value (positive float) :
  30545. * ```javascript
  30546. * var radiusFunction = function(i, distance) {
  30547. * // do things
  30548. * return radius; }
  30549. * ```
  30550. * 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
  30551. * 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
  30552. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30553. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30554. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30555. */
  30556. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  30557. var options = {
  30558. path: path,
  30559. radius: radius,
  30560. tessellation: tessellation,
  30561. radiusFunction: radiusFunction,
  30562. arc: 1,
  30563. cap: cap,
  30564. updatable: updatable,
  30565. sideOrientation: sideOrientation,
  30566. instance: instance
  30567. };
  30568. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  30569. };
  30570. /**
  30571. * Creates a polyhedron mesh.
  30572. * Please consider using the same method from the MeshBuilder class instead.
  30573. * 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
  30574. * to choose the wanted type.
  30575. * The parameter `size` (positive float, default 1) sets the polygon size.
  30576. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  30577. * 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`.
  30578. * 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
  30579. * 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)`).
  30580. * 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
  30581. * 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.
  30582. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30583. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30584. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30585. */
  30586. Mesh.CreatePolyhedron = function (name, options, scene) {
  30587. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  30588. };
  30589. /**
  30590. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  30591. * Please consider using the same method from the MeshBuilder class instead.
  30592. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  30593. * 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`).
  30594. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  30595. * 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.
  30596. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30597. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30598. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30599. */
  30600. Mesh.CreateIcoSphere = function (name, options, scene) {
  30601. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  30602. };
  30603. /**
  30604. * Creates a decal mesh.
  30605. * Please consider using the same method from the MeshBuilder class instead.
  30606. * 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.
  30607. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  30608. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  30609. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  30610. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  30611. */
  30612. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  30613. var options = {
  30614. position: position,
  30615. normal: normal,
  30616. size: size,
  30617. angle: angle
  30618. };
  30619. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  30620. };
  30621. // Skeletons
  30622. /**
  30623. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  30624. */
  30625. Mesh.prototype.setPositionsForCPUSkinning = function () {
  30626. if (!this._sourcePositions) {
  30627. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30628. if (!source) {
  30629. return this._sourcePositions;
  30630. }
  30631. this._sourcePositions = new Float32Array(source);
  30632. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  30633. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  30634. }
  30635. }
  30636. return this._sourcePositions;
  30637. };
  30638. /**
  30639. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  30640. */
  30641. Mesh.prototype.setNormalsForCPUSkinning = function () {
  30642. if (!this._sourceNormals) {
  30643. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30644. if (!source) {
  30645. return this._sourceNormals;
  30646. }
  30647. this._sourceNormals = new Float32Array(source);
  30648. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  30649. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  30650. }
  30651. }
  30652. return this._sourceNormals;
  30653. };
  30654. /**
  30655. * Updates the vertex buffer by applying transformation from the bones.
  30656. * Returns the Mesh.
  30657. *
  30658. * @param {skeleton} skeleton to apply
  30659. */
  30660. Mesh.prototype.applySkeleton = function (skeleton) {
  30661. if (!this.geometry) {
  30662. return this;
  30663. }
  30664. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  30665. return this;
  30666. }
  30667. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  30668. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  30669. return this;
  30670. }
  30671. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  30672. return this;
  30673. }
  30674. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  30675. return this;
  30676. }
  30677. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  30678. return this;
  30679. }
  30680. if (!this._sourcePositions) {
  30681. var submeshes = this.subMeshes.slice();
  30682. this.setPositionsForCPUSkinning();
  30683. this.subMeshes = submeshes;
  30684. }
  30685. if (!this._sourceNormals) {
  30686. this.setNormalsForCPUSkinning();
  30687. }
  30688. // positionsData checks for not being Float32Array will only pass at most once
  30689. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30690. if (!positionsData) {
  30691. return this;
  30692. }
  30693. if (!(positionsData instanceof Float32Array)) {
  30694. positionsData = new Float32Array(positionsData);
  30695. }
  30696. // normalsData checks for not being Float32Array will only pass at most once
  30697. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30698. if (!normalsData) {
  30699. return this;
  30700. }
  30701. if (!(normalsData instanceof Float32Array)) {
  30702. normalsData = new Float32Array(normalsData);
  30703. }
  30704. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  30705. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  30706. if (!matricesWeightsData || !matricesIndicesData) {
  30707. return this;
  30708. }
  30709. var needExtras = this.numBoneInfluencers > 4;
  30710. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  30711. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  30712. var skeletonMatrices = skeleton.getTransformMatrices(this);
  30713. var tempVector3 = BABYLON.Vector3.Zero();
  30714. var finalMatrix = new BABYLON.Matrix();
  30715. var tempMatrix = new BABYLON.Matrix();
  30716. var matWeightIdx = 0;
  30717. var inf;
  30718. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  30719. var weight;
  30720. for (inf = 0; inf < 4; inf++) {
  30721. weight = matricesWeightsData[matWeightIdx + inf];
  30722. if (weight > 0) {
  30723. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  30724. finalMatrix.addToSelf(tempMatrix);
  30725. }
  30726. else
  30727. break;
  30728. }
  30729. if (needExtras) {
  30730. for (inf = 0; inf < 4; inf++) {
  30731. weight = matricesWeightsExtraData[matWeightIdx + inf];
  30732. if (weight > 0) {
  30733. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  30734. finalMatrix.addToSelf(tempMatrix);
  30735. }
  30736. else
  30737. break;
  30738. }
  30739. }
  30740. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  30741. tempVector3.toArray(positionsData, index);
  30742. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  30743. tempVector3.toArray(normalsData, index);
  30744. finalMatrix.reset();
  30745. }
  30746. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  30747. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  30748. return this;
  30749. };
  30750. // Tools
  30751. /**
  30752. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  30753. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  30754. */
  30755. Mesh.MinMax = function (meshes) {
  30756. var minVector = null;
  30757. var maxVector = null;
  30758. meshes.forEach(function (mesh, index, array) {
  30759. var boundingInfo = mesh.getBoundingInfo();
  30760. var boundingBox = boundingInfo.boundingBox;
  30761. if (!minVector || !maxVector) {
  30762. minVector = boundingBox.minimumWorld;
  30763. maxVector = boundingBox.maximumWorld;
  30764. }
  30765. else {
  30766. minVector.minimizeInPlace(boundingBox.minimumWorld);
  30767. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  30768. }
  30769. });
  30770. if (!minVector || !maxVector) {
  30771. return {
  30772. min: BABYLON.Vector3.Zero(),
  30773. max: BABYLON.Vector3.Zero()
  30774. };
  30775. }
  30776. return {
  30777. min: minVector,
  30778. max: maxVector
  30779. };
  30780. };
  30781. /**
  30782. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  30783. */
  30784. Mesh.Center = function (meshesOrMinMaxVector) {
  30785. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  30786. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  30787. };
  30788. /**
  30789. * Merge the array of meshes into a single mesh for performance reasons.
  30790. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  30791. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  30792. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  30793. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  30794. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  30795. */
  30796. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  30797. if (disposeSource === void 0) { disposeSource = true; }
  30798. var index;
  30799. if (!allow32BitsIndices) {
  30800. var totalVertices = 0;
  30801. // Counting vertices
  30802. for (index = 0; index < meshes.length; index++) {
  30803. if (meshes[index]) {
  30804. totalVertices += meshes[index].getTotalVertices();
  30805. if (totalVertices > 65536) {
  30806. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  30807. return null;
  30808. }
  30809. }
  30810. }
  30811. }
  30812. // Merge
  30813. var vertexData = null;
  30814. var otherVertexData;
  30815. var indiceArray = new Array();
  30816. var source = null;
  30817. for (index = 0; index < meshes.length; index++) {
  30818. if (meshes[index]) {
  30819. meshes[index].computeWorldMatrix(true);
  30820. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  30821. otherVertexData.transform(meshes[index].getWorldMatrix());
  30822. if (vertexData) {
  30823. vertexData.merge(otherVertexData);
  30824. }
  30825. else {
  30826. vertexData = otherVertexData;
  30827. source = meshes[index];
  30828. }
  30829. if (subdivideWithSubMeshes) {
  30830. indiceArray.push(meshes[index].getTotalIndices());
  30831. }
  30832. }
  30833. }
  30834. source = source;
  30835. if (!meshSubclass) {
  30836. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  30837. }
  30838. vertexData.applyToMesh(meshSubclass);
  30839. // Setting properties
  30840. meshSubclass.material = source.material;
  30841. meshSubclass.checkCollisions = source.checkCollisions;
  30842. // Cleaning
  30843. if (disposeSource) {
  30844. for (index = 0; index < meshes.length; index++) {
  30845. if (meshes[index]) {
  30846. meshes[index].dispose();
  30847. }
  30848. }
  30849. }
  30850. // Subdivide
  30851. if (subdivideWithSubMeshes) {
  30852. //-- Suppresions du submesh global
  30853. meshSubclass.releaseSubMeshes();
  30854. index = 0;
  30855. var offset = 0;
  30856. //-- aplique la subdivision en fonction du tableau d'indices
  30857. while (index < indiceArray.length) {
  30858. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  30859. offset += indiceArray[index];
  30860. index++;
  30861. }
  30862. }
  30863. return meshSubclass;
  30864. };
  30865. // Consts
  30866. Mesh._FRONTSIDE = 0;
  30867. Mesh._BACKSIDE = 1;
  30868. Mesh._DOUBLESIDE = 2;
  30869. Mesh._DEFAULTSIDE = 0;
  30870. Mesh._NO_CAP = 0;
  30871. Mesh._CAP_START = 1;
  30872. Mesh._CAP_END = 2;
  30873. Mesh._CAP_ALL = 3;
  30874. return Mesh;
  30875. }(BABYLON.AbstractMesh));
  30876. BABYLON.Mesh = Mesh;
  30877. })(BABYLON || (BABYLON = {}));
  30878. //# sourceMappingURL=babylon.mesh.js.map
  30879. "use strict";
  30880. var BABYLON;
  30881. (function (BABYLON) {
  30882. var BaseSubMesh = /** @class */ (function () {
  30883. function BaseSubMesh() {
  30884. }
  30885. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  30886. get: function () {
  30887. return this._materialEffect;
  30888. },
  30889. enumerable: true,
  30890. configurable: true
  30891. });
  30892. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  30893. if (defines === void 0) { defines = null; }
  30894. if (this._materialEffect === effect) {
  30895. if (!effect) {
  30896. this._materialDefines = null;
  30897. }
  30898. return;
  30899. }
  30900. this._materialDefines = defines;
  30901. this._materialEffect = effect;
  30902. };
  30903. return BaseSubMesh;
  30904. }());
  30905. BABYLON.BaseSubMesh = BaseSubMesh;
  30906. var SubMesh = /** @class */ (function (_super) {
  30907. __extends(SubMesh, _super);
  30908. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  30909. if (createBoundingBox === void 0) { createBoundingBox = true; }
  30910. var _this = _super.call(this) || this;
  30911. _this.materialIndex = materialIndex;
  30912. _this.verticesStart = verticesStart;
  30913. _this.verticesCount = verticesCount;
  30914. _this.indexStart = indexStart;
  30915. _this.indexCount = indexCount;
  30916. _this._renderId = 0;
  30917. _this._mesh = mesh;
  30918. _this._renderingMesh = renderingMesh || mesh;
  30919. mesh.subMeshes.push(_this);
  30920. _this._trianglePlanes = [];
  30921. _this._id = mesh.subMeshes.length - 1;
  30922. if (createBoundingBox) {
  30923. _this.refreshBoundingInfo();
  30924. mesh.computeWorldMatrix(true);
  30925. }
  30926. return _this;
  30927. }
  30928. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  30929. if (createBoundingBox === void 0) { createBoundingBox = true; }
  30930. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  30931. };
  30932. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  30933. get: function () {
  30934. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  30935. },
  30936. enumerable: true,
  30937. configurable: true
  30938. });
  30939. /**
  30940. * Returns the submesh BoudingInfo object.
  30941. */
  30942. SubMesh.prototype.getBoundingInfo = function () {
  30943. if (this.IsGlobal) {
  30944. return this._mesh.getBoundingInfo();
  30945. }
  30946. return this._boundingInfo;
  30947. };
  30948. /**
  30949. * Sets the submesh BoundingInfo.
  30950. * Return the SubMesh.
  30951. */
  30952. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  30953. this._boundingInfo = boundingInfo;
  30954. return this;
  30955. };
  30956. /**
  30957. * Returns the mesh of the current submesh.
  30958. */
  30959. SubMesh.prototype.getMesh = function () {
  30960. return this._mesh;
  30961. };
  30962. /**
  30963. * Returns the rendering mesh of the submesh.
  30964. */
  30965. SubMesh.prototype.getRenderingMesh = function () {
  30966. return this._renderingMesh;
  30967. };
  30968. /**
  30969. * Returns the submesh material.
  30970. */
  30971. SubMesh.prototype.getMaterial = function () {
  30972. var rootMaterial = this._renderingMesh.material;
  30973. if (rootMaterial === null || rootMaterial === undefined) {
  30974. return this._mesh.getScene().defaultMaterial;
  30975. }
  30976. else if (rootMaterial.getSubMaterial) {
  30977. var multiMaterial = rootMaterial;
  30978. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  30979. if (this._currentMaterial !== effectiveMaterial) {
  30980. this._currentMaterial = effectiveMaterial;
  30981. this._materialDefines = null;
  30982. }
  30983. return effectiveMaterial;
  30984. }
  30985. return rootMaterial;
  30986. };
  30987. // Methods
  30988. /**
  30989. * Sets a new updated BoundingInfo object to the submesh.
  30990. * Returns the SubMesh.
  30991. */
  30992. SubMesh.prototype.refreshBoundingInfo = function () {
  30993. this._lastColliderWorldVertices = null;
  30994. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  30995. return this;
  30996. }
  30997. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30998. if (!data) {
  30999. this._boundingInfo = this._mesh.getBoundingInfo();
  31000. return this;
  31001. }
  31002. var indices = this._renderingMesh.getIndices();
  31003. var extend;
  31004. //is this the only submesh?
  31005. if (this.indexStart === 0 && this.indexCount === indices.length) {
  31006. var boundingInfo = this._renderingMesh.getBoundingInfo();
  31007. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  31008. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  31009. }
  31010. else {
  31011. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  31012. }
  31013. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  31014. return this;
  31015. };
  31016. SubMesh.prototype._checkCollision = function (collider) {
  31017. var boundingInfo = this.getBoundingInfo();
  31018. return boundingInfo._checkCollision(collider);
  31019. };
  31020. /**
  31021. * Updates the submesh BoundingInfo.
  31022. * Returns the Submesh.
  31023. */
  31024. SubMesh.prototype.updateBoundingInfo = function (world) {
  31025. var boundingInfo = this.getBoundingInfo();
  31026. if (!boundingInfo) {
  31027. this.refreshBoundingInfo();
  31028. boundingInfo = this.getBoundingInfo();
  31029. }
  31030. boundingInfo.update(world);
  31031. return this;
  31032. };
  31033. /**
  31034. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  31035. * Boolean returned.
  31036. */
  31037. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  31038. var boundingInfo = this.getBoundingInfo();
  31039. if (!boundingInfo) {
  31040. return false;
  31041. }
  31042. return boundingInfo.isInFrustum(frustumPlanes);
  31043. };
  31044. /**
  31045. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  31046. * Boolean returned.
  31047. */
  31048. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  31049. var boundingInfo = this.getBoundingInfo();
  31050. if (!boundingInfo) {
  31051. return false;
  31052. }
  31053. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  31054. };
  31055. /**
  31056. * Renders the submesh.
  31057. * Returns it.
  31058. */
  31059. SubMesh.prototype.render = function (enableAlphaMode) {
  31060. this._renderingMesh.render(this, enableAlphaMode);
  31061. return this;
  31062. };
  31063. /**
  31064. * Returns a new Index Buffer.
  31065. * Type returned : WebGLBuffer.
  31066. */
  31067. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  31068. if (!this._linesIndexBuffer) {
  31069. var linesIndices = [];
  31070. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  31071. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  31072. }
  31073. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  31074. this.linesIndexCount = linesIndices.length;
  31075. }
  31076. return this._linesIndexBuffer;
  31077. };
  31078. /**
  31079. * True is the passed Ray intersects the submesh bounding box.
  31080. * Boolean returned.
  31081. */
  31082. SubMesh.prototype.canIntersects = function (ray) {
  31083. var boundingInfo = this.getBoundingInfo();
  31084. if (!boundingInfo) {
  31085. return false;
  31086. }
  31087. return ray.intersectsBox(boundingInfo.boundingBox);
  31088. };
  31089. /**
  31090. * Returns an object IntersectionInfo.
  31091. */
  31092. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  31093. var intersectInfo = null;
  31094. var material = this.getMaterial();
  31095. if (!material) {
  31096. return null;
  31097. }
  31098. switch (material.fillMode) {
  31099. case BABYLON.Material.PointListDrawMode:
  31100. case BABYLON.Material.LineListDrawMode:
  31101. case BABYLON.Material.LineLoopDrawMode:
  31102. case BABYLON.Material.LineStripDrawMode:
  31103. case BABYLON.Material.TriangleFanDrawMode:
  31104. case BABYLON.Material.TriangleStripDrawMode:
  31105. return null;
  31106. }
  31107. // LineMesh first as it's also a Mesh...
  31108. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  31109. var lineMesh = this._mesh;
  31110. // Line test
  31111. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  31112. var p0 = positions[indices[index]];
  31113. var p1 = positions[indices[index + 1]];
  31114. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  31115. if (length < 0) {
  31116. continue;
  31117. }
  31118. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  31119. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  31120. if (fastCheck) {
  31121. break;
  31122. }
  31123. }
  31124. }
  31125. }
  31126. else {
  31127. // Triangles test
  31128. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  31129. var p0 = positions[indices[index]];
  31130. var p1 = positions[indices[index + 1]];
  31131. var p2 = positions[indices[index + 2]];
  31132. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  31133. if (currentIntersectInfo) {
  31134. if (currentIntersectInfo.distance < 0) {
  31135. continue;
  31136. }
  31137. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  31138. intersectInfo = currentIntersectInfo;
  31139. intersectInfo.faceId = index / 3;
  31140. if (fastCheck) {
  31141. break;
  31142. }
  31143. }
  31144. }
  31145. }
  31146. }
  31147. return intersectInfo;
  31148. };
  31149. SubMesh.prototype._rebuild = function () {
  31150. if (this._linesIndexBuffer) {
  31151. this._linesIndexBuffer = null;
  31152. }
  31153. };
  31154. // Clone
  31155. /**
  31156. * Creates a new Submesh from the passed Mesh.
  31157. */
  31158. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  31159. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  31160. if (!this.IsGlobal) {
  31161. var boundingInfo = this.getBoundingInfo();
  31162. if (!boundingInfo) {
  31163. return result;
  31164. }
  31165. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  31166. }
  31167. return result;
  31168. };
  31169. // Dispose
  31170. /**
  31171. * Disposes the Submesh.
  31172. * Returns nothing.
  31173. */
  31174. SubMesh.prototype.dispose = function () {
  31175. if (this._linesIndexBuffer) {
  31176. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  31177. this._linesIndexBuffer = null;
  31178. }
  31179. // Remove from mesh
  31180. var index = this._mesh.subMeshes.indexOf(this);
  31181. this._mesh.subMeshes.splice(index, 1);
  31182. };
  31183. // Statics
  31184. /**
  31185. * Creates a new Submesh from the passed parameters :
  31186. * - materialIndex (integer) : the index of the main mesh material.
  31187. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  31188. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  31189. * - mesh (Mesh) : the main mesh to create the submesh from.
  31190. * - renderingMesh (optional Mesh) : rendering mesh.
  31191. */
  31192. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  31193. var minVertexIndex = Number.MAX_VALUE;
  31194. var maxVertexIndex = -Number.MAX_VALUE;
  31195. renderingMesh = (renderingMesh || mesh);
  31196. var indices = renderingMesh.getIndices();
  31197. for (var index = startIndex; index < startIndex + indexCount; index++) {
  31198. var vertexIndex = indices[index];
  31199. if (vertexIndex < minVertexIndex)
  31200. minVertexIndex = vertexIndex;
  31201. if (vertexIndex > maxVertexIndex)
  31202. maxVertexIndex = vertexIndex;
  31203. }
  31204. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  31205. };
  31206. return SubMesh;
  31207. }(BaseSubMesh));
  31208. BABYLON.SubMesh = SubMesh;
  31209. })(BABYLON || (BABYLON = {}));
  31210. //# sourceMappingURL=babylon.subMesh.js.map
  31211. "use strict";
  31212. var __assign = (this && this.__assign) || Object.assign || function(t) {
  31213. for (var s, i = 1, n = arguments.length; i < n; i++) {
  31214. s = arguments[i];
  31215. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  31216. t[p] = s[p];
  31217. }
  31218. return t;
  31219. };
  31220. var BABYLON;
  31221. (function (BABYLON) {
  31222. /**
  31223. * Manages the defines for the Material.
  31224. */
  31225. var MaterialDefines = /** @class */ (function () {
  31226. function MaterialDefines() {
  31227. this._isDirty = true;
  31228. this._areLightsDirty = true;
  31229. this._areAttributesDirty = true;
  31230. this._areTexturesDirty = true;
  31231. this._areFresnelDirty = true;
  31232. this._areMiscDirty = true;
  31233. this._areImageProcessingDirty = true;
  31234. this._normals = false;
  31235. this._uvs = false;
  31236. this._needNormals = false;
  31237. this._needUVs = false;
  31238. }
  31239. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  31240. /**
  31241. * Specifies if the material needs to be re-calculated.
  31242. */
  31243. get: function () {
  31244. return this._isDirty;
  31245. },
  31246. enumerable: true,
  31247. configurable: true
  31248. });
  31249. /**
  31250. * Marks the material to indicate that it has been re-calculated.
  31251. */
  31252. MaterialDefines.prototype.markAsProcessed = function () {
  31253. this._isDirty = false;
  31254. this._areAttributesDirty = false;
  31255. this._areTexturesDirty = false;
  31256. this._areFresnelDirty = false;
  31257. this._areLightsDirty = false;
  31258. this._areMiscDirty = false;
  31259. this._areImageProcessingDirty = false;
  31260. };
  31261. /**
  31262. * Marks the material to indicate that it needs to be re-calculated.
  31263. */
  31264. MaterialDefines.prototype.markAsUnprocessed = function () {
  31265. this._isDirty = true;
  31266. };
  31267. /**
  31268. * Marks the material to indicate all of its defines need to be re-calculated.
  31269. */
  31270. MaterialDefines.prototype.markAllAsDirty = function () {
  31271. this._areTexturesDirty = true;
  31272. this._areAttributesDirty = true;
  31273. this._areLightsDirty = true;
  31274. this._areFresnelDirty = true;
  31275. this._areMiscDirty = true;
  31276. this._areImageProcessingDirty = true;
  31277. this._isDirty = true;
  31278. };
  31279. /**
  31280. * Marks the material to indicate that image processing needs to be re-calculated.
  31281. */
  31282. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  31283. this._areImageProcessingDirty = true;
  31284. this._isDirty = true;
  31285. };
  31286. /**
  31287. * Marks the material to indicate the lights need to be re-calculated.
  31288. */
  31289. MaterialDefines.prototype.markAsLightDirty = function () {
  31290. this._areLightsDirty = true;
  31291. this._isDirty = true;
  31292. };
  31293. /**
  31294. * Marks the attribute state as changed.
  31295. */
  31296. MaterialDefines.prototype.markAsAttributesDirty = function () {
  31297. this._areAttributesDirty = true;
  31298. this._isDirty = true;
  31299. };
  31300. /**
  31301. * Marks the texture state as changed.
  31302. */
  31303. MaterialDefines.prototype.markAsTexturesDirty = function () {
  31304. this._areTexturesDirty = true;
  31305. this._isDirty = true;
  31306. };
  31307. /**
  31308. * Marks the fresnel state as changed.
  31309. */
  31310. MaterialDefines.prototype.markAsFresnelDirty = function () {
  31311. this._areFresnelDirty = true;
  31312. this._isDirty = true;
  31313. };
  31314. /**
  31315. * Marks the misc state as changed.
  31316. */
  31317. MaterialDefines.prototype.markAsMiscDirty = function () {
  31318. this._areMiscDirty = true;
  31319. this._isDirty = true;
  31320. };
  31321. /**
  31322. * Rebuilds the material defines.
  31323. */
  31324. MaterialDefines.prototype.rebuild = function () {
  31325. if (this._keys) {
  31326. delete this._keys;
  31327. }
  31328. this._keys = [];
  31329. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  31330. var key = _a[_i];
  31331. if (key[0] === "_") {
  31332. continue;
  31333. }
  31334. this._keys.push(key);
  31335. }
  31336. };
  31337. /**
  31338. * Specifies if two material defines are equal.
  31339. * @param other - A material define instance to compare to.
  31340. * @returns - Boolean indicating if the material defines are equal (true) or not (false).
  31341. */
  31342. MaterialDefines.prototype.isEqual = function (other) {
  31343. if (this._keys.length !== other._keys.length) {
  31344. return false;
  31345. }
  31346. for (var index = 0; index < this._keys.length; index++) {
  31347. var prop = this._keys[index];
  31348. if (this[prop] !== other[prop]) {
  31349. return false;
  31350. }
  31351. }
  31352. return true;
  31353. };
  31354. /**
  31355. * Clones this instance's defines to another instance.
  31356. * @param other - material defines to clone values to.
  31357. */
  31358. MaterialDefines.prototype.cloneTo = function (other) {
  31359. if (this._keys.length !== other._keys.length) {
  31360. other._keys = this._keys.slice(0);
  31361. }
  31362. for (var index = 0; index < this._keys.length; index++) {
  31363. var prop = this._keys[index];
  31364. other[prop] = this[prop];
  31365. }
  31366. };
  31367. /**
  31368. * Resets the material define values.
  31369. */
  31370. MaterialDefines.prototype.reset = function () {
  31371. for (var index = 0; index < this._keys.length; index++) {
  31372. var prop = this._keys[index];
  31373. var type = typeof this[prop];
  31374. switch (type) {
  31375. case "number":
  31376. this[prop] = 0;
  31377. break;
  31378. case "string":
  31379. this[prop] = "";
  31380. break;
  31381. default:
  31382. this[prop] = false;
  31383. break;
  31384. }
  31385. }
  31386. };
  31387. /**
  31388. * Converts the material define values to a string.
  31389. * @returns - String of material define information.
  31390. */
  31391. MaterialDefines.prototype.toString = function () {
  31392. var result = "";
  31393. for (var index = 0; index < this._keys.length; index++) {
  31394. var prop = this._keys[index];
  31395. var value = this[prop];
  31396. var type = typeof value;
  31397. switch (type) {
  31398. case "number":
  31399. case "string":
  31400. result += "#define " + prop + " " + value + "\n";
  31401. break;
  31402. default:
  31403. if (value) {
  31404. result += "#define " + prop + "\n";
  31405. }
  31406. break;
  31407. }
  31408. }
  31409. return result;
  31410. };
  31411. return MaterialDefines;
  31412. }());
  31413. BABYLON.MaterialDefines = MaterialDefines;
  31414. /**
  31415. * This offers the main features of a material in BJS.
  31416. */
  31417. var Material = /** @class */ (function () {
  31418. /**
  31419. * Creates a material instance.
  31420. * @param name - The name of the material.
  31421. * @param scene - The BJS scene to reference.
  31422. * @param doNotAdd - Specifies if the material should be added to the scene.
  31423. */
  31424. function Material(name, scene, doNotAdd) {
  31425. /**
  31426. * Specifies if the ready state should be checked on each call.
  31427. */
  31428. this.checkReadyOnEveryCall = false;
  31429. /**
  31430. * Specifies if the ready state should be checked once.
  31431. */
  31432. this.checkReadyOnlyOnce = false;
  31433. /**
  31434. * The state of the material.
  31435. */
  31436. this.state = "";
  31437. /**
  31438. * The alpha value of the material.
  31439. */
  31440. this._alpha = 1.0;
  31441. /**
  31442. * Specifies if back face culling is enabled.
  31443. */
  31444. this._backFaceCulling = true;
  31445. /**
  31446. * Specifies if the material should be serialized.
  31447. */
  31448. this.doNotSerialize = false;
  31449. /**
  31450. * Specifies if the effect should be stored on sub meshes.
  31451. */
  31452. this.storeEffectOnSubMeshes = false;
  31453. /**
  31454. * An event triggered when the material is disposed.
  31455. * @type {BABYLON.Observable}
  31456. */
  31457. this.onDisposeObservable = new BABYLON.Observable();
  31458. /**
  31459. * An event triggered when the material is bound.
  31460. * @type {BABYLON.Observable}
  31461. */
  31462. this.onBindObservable = new BABYLON.Observable();
  31463. /**
  31464. * An event triggered when the material is unbound.
  31465. * @type {BABYLON.Observable}
  31466. */
  31467. this.onUnBindObservable = new BABYLON.Observable();
  31468. /**
  31469. * Stores the value of the alpha mode.
  31470. */
  31471. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  31472. /**
  31473. * Stores the state of the need depth pre-pass value.
  31474. */
  31475. this._needDepthPrePass = false;
  31476. /**
  31477. * Specifies if depth writing should be disabled.
  31478. */
  31479. this.disableDepthWrite = false;
  31480. /**
  31481. * Specifies if depth writing should be forced.
  31482. */
  31483. this.forceDepthWrite = false;
  31484. /**
  31485. * Specifies if there should be a separate pass for culling.
  31486. */
  31487. this.separateCullingPass = false;
  31488. /**
  31489. * Stores the state specifing if fog should be enabled.
  31490. */
  31491. this._fogEnabled = true;
  31492. /**
  31493. * Stores the size of points.
  31494. */
  31495. this.pointSize = 1.0;
  31496. /**
  31497. * Stores the z offset value.
  31498. */
  31499. this.zOffset = 0;
  31500. /**
  31501. * Specifies if the material was previously ready.
  31502. */
  31503. this._wasPreviouslyReady = false;
  31504. /**
  31505. * Stores the fill mode state.
  31506. */
  31507. this._fillMode = Material.TriangleFillMode;
  31508. this.name = name;
  31509. this.id = name || BABYLON.Tools.RandomId();
  31510. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  31511. if (this._scene.useRightHandedSystem) {
  31512. this.sideOrientation = Material.ClockWiseSideOrientation;
  31513. }
  31514. else {
  31515. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  31516. }
  31517. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  31518. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  31519. if (!doNotAdd) {
  31520. this._scene.materials.push(this);
  31521. }
  31522. }
  31523. Object.defineProperty(Material, "TriangleFillMode", {
  31524. /**
  31525. * Returns the triangle fill mode.
  31526. */
  31527. get: function () {
  31528. return Material._TriangleFillMode;
  31529. },
  31530. enumerable: true,
  31531. configurable: true
  31532. });
  31533. Object.defineProperty(Material, "WireFrameFillMode", {
  31534. /**
  31535. * Returns the wireframe mode.
  31536. */
  31537. get: function () {
  31538. return Material._WireFrameFillMode;
  31539. },
  31540. enumerable: true,
  31541. configurable: true
  31542. });
  31543. Object.defineProperty(Material, "PointFillMode", {
  31544. /**
  31545. * Returns the point fill mode.
  31546. */
  31547. get: function () {
  31548. return Material._PointFillMode;
  31549. },
  31550. enumerable: true,
  31551. configurable: true
  31552. });
  31553. Object.defineProperty(Material, "PointListDrawMode", {
  31554. /**
  31555. * Returns the point list draw mode.
  31556. */
  31557. get: function () {
  31558. return Material._PointListDrawMode;
  31559. },
  31560. enumerable: true,
  31561. configurable: true
  31562. });
  31563. Object.defineProperty(Material, "LineListDrawMode", {
  31564. /**
  31565. * Returns the line list draw mode.
  31566. */
  31567. get: function () {
  31568. return Material._LineListDrawMode;
  31569. },
  31570. enumerable: true,
  31571. configurable: true
  31572. });
  31573. Object.defineProperty(Material, "LineLoopDrawMode", {
  31574. /**
  31575. * Returns the line loop draw mode.
  31576. */
  31577. get: function () {
  31578. return Material._LineLoopDrawMode;
  31579. },
  31580. enumerable: true,
  31581. configurable: true
  31582. });
  31583. Object.defineProperty(Material, "LineStripDrawMode", {
  31584. /**
  31585. * Returns the line strip draw mode.
  31586. */
  31587. get: function () {
  31588. return Material._LineStripDrawMode;
  31589. },
  31590. enumerable: true,
  31591. configurable: true
  31592. });
  31593. Object.defineProperty(Material, "TriangleStripDrawMode", {
  31594. /**
  31595. * Returns the triangle strip draw mode.
  31596. */
  31597. get: function () {
  31598. return Material._TriangleStripDrawMode;
  31599. },
  31600. enumerable: true,
  31601. configurable: true
  31602. });
  31603. Object.defineProperty(Material, "TriangleFanDrawMode", {
  31604. /**
  31605. * Returns the triangle fan draw mode.
  31606. */
  31607. get: function () {
  31608. return Material._TriangleFanDrawMode;
  31609. },
  31610. enumerable: true,
  31611. configurable: true
  31612. });
  31613. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  31614. /**
  31615. * Returns the clock-wise side orientation.
  31616. */
  31617. get: function () {
  31618. return Material._ClockWiseSideOrientation;
  31619. },
  31620. enumerable: true,
  31621. configurable: true
  31622. });
  31623. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  31624. /**
  31625. * Returns the counter clock-wise side orientation.
  31626. */
  31627. get: function () {
  31628. return Material._CounterClockWiseSideOrientation;
  31629. },
  31630. enumerable: true,
  31631. configurable: true
  31632. });
  31633. Object.defineProperty(Material, "TextureDirtyFlag", {
  31634. /**
  31635. * Returns the dirty texture flag value.
  31636. */
  31637. get: function () {
  31638. return Material._TextureDirtyFlag;
  31639. },
  31640. enumerable: true,
  31641. configurable: true
  31642. });
  31643. Object.defineProperty(Material, "LightDirtyFlag", {
  31644. /**
  31645. * Returns the dirty light flag value.
  31646. */
  31647. get: function () {
  31648. return Material._LightDirtyFlag;
  31649. },
  31650. enumerable: true,
  31651. configurable: true
  31652. });
  31653. Object.defineProperty(Material, "FresnelDirtyFlag", {
  31654. /**
  31655. * Returns the dirty fresnel flag value.
  31656. */
  31657. get: function () {
  31658. return Material._FresnelDirtyFlag;
  31659. },
  31660. enumerable: true,
  31661. configurable: true
  31662. });
  31663. Object.defineProperty(Material, "AttributesDirtyFlag", {
  31664. /**
  31665. * Returns the dirty attributes flag value.
  31666. */
  31667. get: function () {
  31668. return Material._AttributesDirtyFlag;
  31669. },
  31670. enumerable: true,
  31671. configurable: true
  31672. });
  31673. Object.defineProperty(Material, "MiscDirtyFlag", {
  31674. /**
  31675. * Returns the dirty misc flag value.
  31676. */
  31677. get: function () {
  31678. return Material._MiscDirtyFlag;
  31679. },
  31680. enumerable: true,
  31681. configurable: true
  31682. });
  31683. Object.defineProperty(Material.prototype, "alpha", {
  31684. /**
  31685. * Gets the alpha value of the material.
  31686. */
  31687. get: function () {
  31688. return this._alpha;
  31689. },
  31690. /**
  31691. * Sets the alpha value of the material.
  31692. */
  31693. set: function (value) {
  31694. if (this._alpha === value) {
  31695. return;
  31696. }
  31697. this._alpha = value;
  31698. this.markAsDirty(Material.MiscDirtyFlag);
  31699. },
  31700. enumerable: true,
  31701. configurable: true
  31702. });
  31703. Object.defineProperty(Material.prototype, "backFaceCulling", {
  31704. /**
  31705. * Gets the back-face culling state.
  31706. */
  31707. get: function () {
  31708. return this._backFaceCulling;
  31709. },
  31710. /**
  31711. * Sets the back-face culling state.
  31712. */
  31713. set: function (value) {
  31714. if (this._backFaceCulling === value) {
  31715. return;
  31716. }
  31717. this._backFaceCulling = value;
  31718. this.markAsDirty(Material.TextureDirtyFlag);
  31719. },
  31720. enumerable: true,
  31721. configurable: true
  31722. });
  31723. Object.defineProperty(Material.prototype, "onDispose", {
  31724. /**
  31725. * Called during a dispose event.
  31726. */
  31727. set: function (callback) {
  31728. if (this._onDisposeObserver) {
  31729. this.onDisposeObservable.remove(this._onDisposeObserver);
  31730. }
  31731. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  31732. },
  31733. enumerable: true,
  31734. configurable: true
  31735. });
  31736. Object.defineProperty(Material.prototype, "onBind", {
  31737. /**
  31738. * Called during a bind event.
  31739. */
  31740. set: function (callback) {
  31741. if (this._onBindObserver) {
  31742. this.onBindObservable.remove(this._onBindObserver);
  31743. }
  31744. this._onBindObserver = this.onBindObservable.add(callback);
  31745. },
  31746. enumerable: true,
  31747. configurable: true
  31748. });
  31749. Object.defineProperty(Material.prototype, "alphaMode", {
  31750. /**
  31751. * Gets the value of the alpha mode.
  31752. */
  31753. get: function () {
  31754. return this._alphaMode;
  31755. },
  31756. /**
  31757. * Sets the value of the alpha mode.
  31758. */
  31759. set: function (value) {
  31760. if (this._alphaMode === value) {
  31761. return;
  31762. }
  31763. this._alphaMode = value;
  31764. this.markAsDirty(Material.TextureDirtyFlag);
  31765. },
  31766. enumerable: true,
  31767. configurable: true
  31768. });
  31769. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  31770. /**
  31771. * Gets the depth pre-pass value.
  31772. */
  31773. get: function () {
  31774. return this._needDepthPrePass;
  31775. },
  31776. /**
  31777. * Sets the need depth pre-pass value.
  31778. */
  31779. set: function (value) {
  31780. if (this._needDepthPrePass === value) {
  31781. return;
  31782. }
  31783. this._needDepthPrePass = value;
  31784. if (this._needDepthPrePass) {
  31785. this.checkReadyOnEveryCall = true;
  31786. }
  31787. },
  31788. enumerable: true,
  31789. configurable: true
  31790. });
  31791. Object.defineProperty(Material.prototype, "fogEnabled", {
  31792. /**
  31793. * Gets the value of the fog enabled state.
  31794. */
  31795. get: function () {
  31796. return this._fogEnabled;
  31797. },
  31798. /**
  31799. * Sets the state for enabling fog.
  31800. */
  31801. set: function (value) {
  31802. if (this._fogEnabled === value) {
  31803. return;
  31804. }
  31805. this._fogEnabled = value;
  31806. this.markAsDirty(Material.MiscDirtyFlag);
  31807. },
  31808. enumerable: true,
  31809. configurable: true
  31810. });
  31811. Object.defineProperty(Material.prototype, "wireframe", {
  31812. /**
  31813. * Gets a value specifying if wireframe mode is enabled.
  31814. */
  31815. get: function () {
  31816. switch (this._fillMode) {
  31817. case Material.WireFrameFillMode:
  31818. case Material.LineListDrawMode:
  31819. case Material.LineLoopDrawMode:
  31820. case Material.LineStripDrawMode:
  31821. return true;
  31822. }
  31823. return this._scene.forceWireframe;
  31824. },
  31825. /**
  31826. * Sets the state of wireframe mode.
  31827. */
  31828. set: function (value) {
  31829. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  31830. },
  31831. enumerable: true,
  31832. configurable: true
  31833. });
  31834. Object.defineProperty(Material.prototype, "pointsCloud", {
  31835. /**
  31836. * Gets the value specifying if point clouds are enabled.
  31837. */
  31838. get: function () {
  31839. switch (this._fillMode) {
  31840. case Material.PointFillMode:
  31841. case Material.PointListDrawMode:
  31842. return true;
  31843. }
  31844. return this._scene.forcePointsCloud;
  31845. },
  31846. /**
  31847. * Sets the state of point cloud mode.
  31848. */
  31849. set: function (value) {
  31850. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  31851. },
  31852. enumerable: true,
  31853. configurable: true
  31854. });
  31855. Object.defineProperty(Material.prototype, "fillMode", {
  31856. /**
  31857. * Gets the material fill mode.
  31858. */
  31859. get: function () {
  31860. return this._fillMode;
  31861. },
  31862. /**
  31863. * Sets the material fill mode.
  31864. */
  31865. set: function (value) {
  31866. if (this._fillMode === value) {
  31867. return;
  31868. }
  31869. this._fillMode = value;
  31870. this.markAsDirty(Material.MiscDirtyFlag);
  31871. },
  31872. enumerable: true,
  31873. configurable: true
  31874. });
  31875. /**
  31876. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31877. * subclasses should override adding information pertainent to themselves.
  31878. * @returns - String with material information.
  31879. */
  31880. Material.prototype.toString = function (fullDetails) {
  31881. var ret = "Name: " + this.name;
  31882. if (fullDetails) {
  31883. }
  31884. return ret;
  31885. };
  31886. /**
  31887. * Gets the class name of the material.
  31888. * @returns - String with the class name of the material.
  31889. */
  31890. Material.prototype.getClassName = function () {
  31891. return "Material";
  31892. };
  31893. Object.defineProperty(Material.prototype, "isFrozen", {
  31894. /**
  31895. * Specifies if updates for the material been locked.
  31896. */
  31897. get: function () {
  31898. return this.checkReadyOnlyOnce;
  31899. },
  31900. enumerable: true,
  31901. configurable: true
  31902. });
  31903. /**
  31904. * Locks updates for the material.
  31905. */
  31906. Material.prototype.freeze = function () {
  31907. this.checkReadyOnlyOnce = true;
  31908. };
  31909. /**
  31910. * Unlocks updates for the material.
  31911. */
  31912. Material.prototype.unfreeze = function () {
  31913. this.checkReadyOnlyOnce = false;
  31914. };
  31915. /**
  31916. * Specifies if the material is ready to be used.
  31917. * @param mesh - BJS mesh.
  31918. * @param useInstances - Specifies if instances should be used.
  31919. * @returns - Boolean indicating if the material is ready to be used.
  31920. */
  31921. Material.prototype.isReady = function (mesh, useInstances) {
  31922. return true;
  31923. };
  31924. /**
  31925. * Specifies that the submesh is ready to be used.
  31926. * @param mesh - BJS mesh.
  31927. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  31928. * @param useInstances - Specifies that instances should be used.
  31929. * @returns - boolean indicating that the submesh is ready or not.
  31930. */
  31931. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  31932. return false;
  31933. };
  31934. /**
  31935. * Returns the material effect.
  31936. * @returns - Nullable material effect.
  31937. */
  31938. Material.prototype.getEffect = function () {
  31939. return this._effect;
  31940. };
  31941. /**
  31942. * Returns the BJS scene.
  31943. * @returns - BJS Scene.
  31944. */
  31945. Material.prototype.getScene = function () {
  31946. return this._scene;
  31947. };
  31948. /**
  31949. * Specifies if the material will require alpha blending
  31950. * @returns - Boolean specifying if alpha blending is needed.
  31951. */
  31952. Material.prototype.needAlphaBlending = function () {
  31953. return (this.alpha < 1.0);
  31954. };
  31955. /**
  31956. * Specifies if the mesh will require alpha blending.
  31957. * @param mesh - BJS mesh.
  31958. * @returns - Boolean specifying if alpha blending is needed for the mesh.
  31959. */
  31960. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  31961. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  31962. };
  31963. /**
  31964. * Specifies if this material should be rendered in alpha test mode.
  31965. * @returns - Boolean specifying if an alpha test is needed.
  31966. */
  31967. Material.prototype.needAlphaTesting = function () {
  31968. return false;
  31969. };
  31970. /**
  31971. * Gets the texture used for the alpha test.
  31972. * @returns - Nullable alpha test texture.
  31973. */
  31974. Material.prototype.getAlphaTestTexture = function () {
  31975. return null;
  31976. };
  31977. /**
  31978. * Marks the material to indicate that it needs to be re-calculated.
  31979. */
  31980. Material.prototype.markDirty = function () {
  31981. this._wasPreviouslyReady = false;
  31982. };
  31983. Material.prototype._preBind = function (effect, overrideOrientation) {
  31984. if (overrideOrientation === void 0) { overrideOrientation = null; }
  31985. var engine = this._scene.getEngine();
  31986. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  31987. var reverse = orientation === Material.ClockWiseSideOrientation;
  31988. engine.enableEffect(effect ? effect : this._effect);
  31989. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  31990. return reverse;
  31991. };
  31992. /**
  31993. * Binds the material to the mesh.
  31994. * @param world - World transformation matrix.
  31995. * @param mesh - Mesh to bind the material to.
  31996. */
  31997. Material.prototype.bind = function (world, mesh) {
  31998. };
  31999. /**
  32000. * Binds the submesh to the material.
  32001. * @param world - World transformation matrix.
  32002. * @param mesh - Mesh containing the submesh.
  32003. * @param subMesh - Submesh to bind the material to.
  32004. */
  32005. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  32006. };
  32007. /**
  32008. * Binds the world matrix to the material.
  32009. * @param world - World transformation matrix.
  32010. */
  32011. Material.prototype.bindOnlyWorldMatrix = function (world) {
  32012. };
  32013. /**
  32014. * Binds the scene's uniform buffer to the effect.
  32015. * @param effect - Effect to bind to the scene uniform buffer.
  32016. * @param sceneUbo - Scene uniform buffer.
  32017. */
  32018. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  32019. sceneUbo.bindToEffect(effect, "Scene");
  32020. };
  32021. /**
  32022. * Binds the view matrix to the effect.
  32023. * @param effect - Effect to bind the view matrix to.
  32024. */
  32025. Material.prototype.bindView = function (effect) {
  32026. if (!this._useUBO) {
  32027. effect.setMatrix("view", this.getScene().getViewMatrix());
  32028. }
  32029. else {
  32030. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  32031. }
  32032. };
  32033. /**
  32034. * Binds the view projection matrix to the effect.
  32035. * @param effect - Effect to bind the view projection matrix to.
  32036. */
  32037. Material.prototype.bindViewProjection = function (effect) {
  32038. if (!this._useUBO) {
  32039. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  32040. }
  32041. else {
  32042. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  32043. }
  32044. };
  32045. /**
  32046. * Specifies if material alpha testing should be turned on for the mesh.
  32047. * @param mesh - BJS mesh.
  32048. */
  32049. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  32050. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  32051. };
  32052. /**
  32053. * Processes to execute after binding the material to a mesh.
  32054. * @param mesh - BJS mesh.
  32055. */
  32056. Material.prototype._afterBind = function (mesh) {
  32057. this._scene._cachedMaterial = this;
  32058. if (mesh) {
  32059. this._scene._cachedVisibility = mesh.visibility;
  32060. }
  32061. else {
  32062. this._scene._cachedVisibility = 1;
  32063. }
  32064. if (mesh) {
  32065. this.onBindObservable.notifyObservers(mesh);
  32066. }
  32067. if (this.disableDepthWrite) {
  32068. var engine = this._scene.getEngine();
  32069. this._cachedDepthWriteState = engine.getDepthWrite();
  32070. engine.setDepthWrite(false);
  32071. }
  32072. };
  32073. /**
  32074. * Unbinds the material from the mesh.
  32075. */
  32076. Material.prototype.unbind = function () {
  32077. this.onUnBindObservable.notifyObservers(this);
  32078. if (this.disableDepthWrite) {
  32079. var engine = this._scene.getEngine();
  32080. engine.setDepthWrite(this._cachedDepthWriteState);
  32081. }
  32082. };
  32083. /**
  32084. * Gets the active textures from the material.
  32085. * @returns - Array of textures.
  32086. */
  32087. Material.prototype.getActiveTextures = function () {
  32088. return [];
  32089. };
  32090. /**
  32091. * Specifies if the material uses a texture.
  32092. * @param texture - Texture to check against the material.
  32093. * @returns - Boolean specifying if the material uses the texture.
  32094. */
  32095. Material.prototype.hasTexture = function (texture) {
  32096. return false;
  32097. };
  32098. /**
  32099. * Makes a duplicate of the material, and gives it a new name.
  32100. * @param name - Name to call the duplicated material.
  32101. * @returns - Nullable cloned material
  32102. */
  32103. Material.prototype.clone = function (name) {
  32104. return null;
  32105. };
  32106. /**
  32107. * Gets the meshes bound to the material.
  32108. * @returns - Array of meshes bound to the material.
  32109. */
  32110. Material.prototype.getBindedMeshes = function () {
  32111. var result = new Array();
  32112. for (var index = 0; index < this._scene.meshes.length; index++) {
  32113. var mesh = this._scene.meshes[index];
  32114. if (mesh.material === this) {
  32115. result.push(mesh);
  32116. }
  32117. }
  32118. return result;
  32119. };
  32120. /**
  32121. * Force shader compilation
  32122. * @param mesh - BJS mesh.
  32123. * @param onCompiled - function to execute once the material is compiled.
  32124. * @param options - options to pass to this function.
  32125. */
  32126. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  32127. var _this = this;
  32128. var localOptions = __assign({ clipPlane: false }, options);
  32129. var subMesh = new BABYLON.BaseSubMesh();
  32130. var scene = this.getScene();
  32131. var checkReady = function () {
  32132. if (!_this._scene || !_this._scene.getEngine()) {
  32133. return;
  32134. }
  32135. if (subMesh._materialDefines) {
  32136. subMesh._materialDefines._renderId = -1;
  32137. }
  32138. var clipPlaneState = scene.clipPlane;
  32139. if (localOptions.clipPlane) {
  32140. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  32141. }
  32142. if (_this.storeEffectOnSubMeshes) {
  32143. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  32144. if (onCompiled) {
  32145. onCompiled(_this);
  32146. }
  32147. }
  32148. else {
  32149. setTimeout(checkReady, 16);
  32150. }
  32151. }
  32152. else {
  32153. if (_this.isReady(mesh)) {
  32154. if (onCompiled) {
  32155. onCompiled(_this);
  32156. }
  32157. }
  32158. else {
  32159. setTimeout(checkReady, 16);
  32160. }
  32161. }
  32162. if (localOptions.clipPlane) {
  32163. scene.clipPlane = clipPlaneState;
  32164. }
  32165. };
  32166. checkReady();
  32167. };
  32168. /**
  32169. * Force shader compilation.
  32170. * @param mesh The mesh that will use this material
  32171. * @param options Additional options for compiling the shaders
  32172. * @returns A promise that resolves when the compilation completes
  32173. */
  32174. Material.prototype.forceCompilationAsync = function (mesh, options) {
  32175. var _this = this;
  32176. return new Promise(function (resolve) {
  32177. _this.forceCompilation(mesh, function () {
  32178. resolve();
  32179. }, options);
  32180. });
  32181. };
  32182. /**
  32183. * Marks a define in the material to indicate that it needs to be re-computed.
  32184. * @param flag - Material define flag.
  32185. */
  32186. Material.prototype.markAsDirty = function (flag) {
  32187. if (flag & Material.TextureDirtyFlag) {
  32188. this._markAllSubMeshesAsTexturesDirty();
  32189. }
  32190. if (flag & Material.LightDirtyFlag) {
  32191. this._markAllSubMeshesAsLightsDirty();
  32192. }
  32193. if (flag & Material.FresnelDirtyFlag) {
  32194. this._markAllSubMeshesAsFresnelDirty();
  32195. }
  32196. if (flag & Material.AttributesDirtyFlag) {
  32197. this._markAllSubMeshesAsAttributesDirty();
  32198. }
  32199. if (flag & Material.MiscDirtyFlag) {
  32200. this._markAllSubMeshesAsMiscDirty();
  32201. }
  32202. this.getScene().resetCachedMaterial();
  32203. };
  32204. /**
  32205. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated.
  32206. * @param func - function which checks material defines against the submeshes.
  32207. */
  32208. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  32209. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  32210. var mesh = _a[_i];
  32211. if (!mesh.subMeshes) {
  32212. continue;
  32213. }
  32214. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  32215. var subMesh = _c[_b];
  32216. if (subMesh.getMaterial() !== this) {
  32217. continue;
  32218. }
  32219. if (!subMesh._materialDefines) {
  32220. continue;
  32221. }
  32222. func(subMesh._materialDefines);
  32223. }
  32224. }
  32225. };
  32226. /**
  32227. * Indicates that image processing needs to be re-calculated for all submeshes.
  32228. */
  32229. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  32230. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  32231. };
  32232. /**
  32233. * Indicates that textures need to be re-calculated for all submeshes.
  32234. */
  32235. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  32236. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  32237. };
  32238. /**
  32239. * Indicates that fresnel needs to be re-calculated for all submeshes.
  32240. */
  32241. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  32242. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  32243. };
  32244. /**
  32245. * Indicates that fresnel and misc need to be re-calculated for all submeshes.
  32246. */
  32247. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  32248. this._markAllSubMeshesAsDirty(function (defines) {
  32249. defines.markAsFresnelDirty();
  32250. defines.markAsMiscDirty();
  32251. });
  32252. };
  32253. /**
  32254. * Indicates that lights need to be re-calculated for all submeshes.
  32255. */
  32256. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  32257. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  32258. };
  32259. /**
  32260. * Indicates that attributes need to be re-calculated for all submeshes.
  32261. */
  32262. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  32263. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  32264. };
  32265. /**
  32266. * Indicates that misc needs to be re-calculated for all submeshes.
  32267. */
  32268. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  32269. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  32270. };
  32271. /**
  32272. * Indicates that textures and misc need to be re-calculated for all submeshes.
  32273. */
  32274. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  32275. this._markAllSubMeshesAsDirty(function (defines) {
  32276. defines.markAsTexturesDirty();
  32277. defines.markAsMiscDirty();
  32278. });
  32279. };
  32280. /**
  32281. * Disposes the material.
  32282. * @param forceDisposeEffect - Specifies if effects should be force disposed.
  32283. * @param forceDisposeTextures - Specifies if textures should be force disposed.
  32284. */
  32285. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  32286. // Animations
  32287. this.getScene().stopAnimation(this);
  32288. this.getScene().freeProcessedMaterials();
  32289. // Remove from scene
  32290. var index = this._scene.materials.indexOf(this);
  32291. if (index >= 0) {
  32292. this._scene.materials.splice(index, 1);
  32293. }
  32294. // Remove from meshes
  32295. for (index = 0; index < this._scene.meshes.length; index++) {
  32296. var mesh = this._scene.meshes[index];
  32297. if (mesh.material === this) {
  32298. mesh.material = null;
  32299. if (mesh.geometry) {
  32300. var geometry = (mesh.geometry);
  32301. if (this.storeEffectOnSubMeshes) {
  32302. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  32303. var subMesh = _a[_i];
  32304. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  32305. if (forceDisposeEffect && subMesh._materialEffect) {
  32306. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  32307. }
  32308. }
  32309. }
  32310. else {
  32311. geometry._releaseVertexArrayObject(this._effect);
  32312. }
  32313. }
  32314. }
  32315. }
  32316. this._uniformBuffer.dispose();
  32317. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  32318. if (forceDisposeEffect && this._effect) {
  32319. if (!this.storeEffectOnSubMeshes) {
  32320. this._scene.getEngine()._releaseEffect(this._effect);
  32321. }
  32322. this._effect = null;
  32323. }
  32324. // Callback
  32325. this.onDisposeObservable.notifyObservers(this);
  32326. this.onDisposeObservable.clear();
  32327. this.onBindObservable.clear();
  32328. this.onUnBindObservable.clear();
  32329. };
  32330. /**
  32331. * Serializes this material.
  32332. * @returns - serialized material object.
  32333. */
  32334. Material.prototype.serialize = function () {
  32335. return BABYLON.SerializationHelper.Serialize(this);
  32336. };
  32337. /**
  32338. * Creates a MultiMaterial from parse MultiMaterial data.
  32339. * @param parsedMultiMaterial - Parsed MultiMaterial data.
  32340. * @param scene - BJS scene.
  32341. * @returns - MultiMaterial.
  32342. */
  32343. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  32344. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  32345. multiMaterial.id = parsedMultiMaterial.id;
  32346. if (BABYLON.Tags) {
  32347. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  32348. }
  32349. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  32350. var subMatId = parsedMultiMaterial.materials[matIndex];
  32351. if (subMatId) {
  32352. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  32353. }
  32354. else {
  32355. multiMaterial.subMaterials.push(null);
  32356. }
  32357. }
  32358. return multiMaterial;
  32359. };
  32360. /**
  32361. * Creates a material from parsed material data.
  32362. * @param parsedMaterial - Parsed material data.
  32363. * @param scene - BJS scene.
  32364. * @param rootUrl - Root URL containing the material information.
  32365. * @returns - Parsed material.
  32366. */
  32367. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  32368. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  32369. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  32370. }
  32371. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  32372. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  32373. if (!BABYLON.LegacyPBRMaterial) {
  32374. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  32375. return;
  32376. }
  32377. }
  32378. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  32379. return materialType.Parse(parsedMaterial, scene, rootUrl);
  32380. ;
  32381. };
  32382. // Triangle views
  32383. Material._TriangleFillMode = 0;
  32384. Material._WireFrameFillMode = 1;
  32385. Material._PointFillMode = 2;
  32386. // Draw modes
  32387. Material._PointListDrawMode = 3;
  32388. Material._LineListDrawMode = 4;
  32389. Material._LineLoopDrawMode = 5;
  32390. Material._LineStripDrawMode = 6;
  32391. Material._TriangleStripDrawMode = 7;
  32392. Material._TriangleFanDrawMode = 8;
  32393. /**
  32394. * Stores the clock-wise side orientation.
  32395. */
  32396. Material._ClockWiseSideOrientation = 0;
  32397. /**
  32398. * Stores the counter clock-wise side orientation.
  32399. */
  32400. Material._CounterClockWiseSideOrientation = 1;
  32401. /**
  32402. * The dirty texture flag value.
  32403. */
  32404. Material._TextureDirtyFlag = 1;
  32405. /**
  32406. * The dirty light flag value.
  32407. */
  32408. Material._LightDirtyFlag = 2;
  32409. /**
  32410. * The dirty fresnel flag value.
  32411. */
  32412. Material._FresnelDirtyFlag = 4;
  32413. /**
  32414. * The dirty attribute flag value.
  32415. */
  32416. Material._AttributesDirtyFlag = 8;
  32417. /**
  32418. * The dirty misc flag value.
  32419. */
  32420. Material._MiscDirtyFlag = 16;
  32421. __decorate([
  32422. BABYLON.serialize()
  32423. ], Material.prototype, "id", void 0);
  32424. __decorate([
  32425. BABYLON.serialize()
  32426. ], Material.prototype, "name", void 0);
  32427. __decorate([
  32428. BABYLON.serialize()
  32429. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  32430. __decorate([
  32431. BABYLON.serialize()
  32432. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  32433. __decorate([
  32434. BABYLON.serialize()
  32435. ], Material.prototype, "state", void 0);
  32436. __decorate([
  32437. BABYLON.serialize("alpha")
  32438. ], Material.prototype, "_alpha", void 0);
  32439. __decorate([
  32440. BABYLON.serialize("backFaceCulling")
  32441. ], Material.prototype, "_backFaceCulling", void 0);
  32442. __decorate([
  32443. BABYLON.serialize()
  32444. ], Material.prototype, "sideOrientation", void 0);
  32445. __decorate([
  32446. BABYLON.serialize("alphaMode")
  32447. ], Material.prototype, "_alphaMode", void 0);
  32448. __decorate([
  32449. BABYLON.serialize()
  32450. ], Material.prototype, "_needDepthPrePass", void 0);
  32451. __decorate([
  32452. BABYLON.serialize()
  32453. ], Material.prototype, "disableDepthWrite", void 0);
  32454. __decorate([
  32455. BABYLON.serialize()
  32456. ], Material.prototype, "forceDepthWrite", void 0);
  32457. __decorate([
  32458. BABYLON.serialize()
  32459. ], Material.prototype, "separateCullingPass", void 0);
  32460. __decorate([
  32461. BABYLON.serialize("fogEnabled")
  32462. ], Material.prototype, "_fogEnabled", void 0);
  32463. __decorate([
  32464. BABYLON.serialize()
  32465. ], Material.prototype, "pointSize", void 0);
  32466. __decorate([
  32467. BABYLON.serialize()
  32468. ], Material.prototype, "zOffset", void 0);
  32469. __decorate([
  32470. BABYLON.serialize()
  32471. ], Material.prototype, "wireframe", null);
  32472. __decorate([
  32473. BABYLON.serialize()
  32474. ], Material.prototype, "pointsCloud", null);
  32475. __decorate([
  32476. BABYLON.serialize()
  32477. ], Material.prototype, "fillMode", null);
  32478. return Material;
  32479. }());
  32480. BABYLON.Material = Material;
  32481. })(BABYLON || (BABYLON = {}));
  32482. //# sourceMappingURL=babylon.material.js.map
  32483. "use strict";
  32484. var BABYLON;
  32485. (function (BABYLON) {
  32486. var UniformBuffer = /** @class */ (function () {
  32487. /**
  32488. * Uniform buffer objects.
  32489. *
  32490. * Handles blocks of uniform on the GPU.
  32491. *
  32492. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  32493. *
  32494. * For more information, please refer to :
  32495. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  32496. */
  32497. function UniformBuffer(engine, data, dynamic) {
  32498. this._engine = engine;
  32499. this._noUBO = !engine.supportsUniformBuffers;
  32500. this._dynamic = dynamic;
  32501. this._data = data || [];
  32502. this._uniformLocations = {};
  32503. this._uniformSizes = {};
  32504. this._uniformLocationPointer = 0;
  32505. this._needSync = false;
  32506. if (this._noUBO) {
  32507. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  32508. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  32509. this.updateFloat = this._updateFloatForEffect;
  32510. this.updateFloat2 = this._updateFloat2ForEffect;
  32511. this.updateFloat3 = this._updateFloat3ForEffect;
  32512. this.updateFloat4 = this._updateFloat4ForEffect;
  32513. this.updateMatrix = this._updateMatrixForEffect;
  32514. this.updateVector3 = this._updateVector3ForEffect;
  32515. this.updateVector4 = this._updateVector4ForEffect;
  32516. this.updateColor3 = this._updateColor3ForEffect;
  32517. this.updateColor4 = this._updateColor4ForEffect;
  32518. }
  32519. else {
  32520. this._engine._uniformBuffers.push(this);
  32521. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  32522. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  32523. this.updateFloat = this._updateFloatForUniform;
  32524. this.updateFloat2 = this._updateFloat2ForUniform;
  32525. this.updateFloat3 = this._updateFloat3ForUniform;
  32526. this.updateFloat4 = this._updateFloat4ForUniform;
  32527. this.updateMatrix = this._updateMatrixForUniform;
  32528. this.updateVector3 = this._updateVector3ForUniform;
  32529. this.updateVector4 = this._updateVector4ForUniform;
  32530. this.updateColor3 = this._updateColor3ForUniform;
  32531. this.updateColor4 = this._updateColor4ForUniform;
  32532. }
  32533. }
  32534. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  32535. // Properties
  32536. /**
  32537. * Indicates if the buffer is using the WebGL2 UBO implementation,
  32538. * or just falling back on setUniformXXX calls.
  32539. */
  32540. get: function () {
  32541. return !this._noUBO;
  32542. },
  32543. enumerable: true,
  32544. configurable: true
  32545. });
  32546. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  32547. /**
  32548. * Indicates if the WebGL underlying uniform buffer is in sync
  32549. * with the javascript cache data.
  32550. */
  32551. get: function () {
  32552. return !this._needSync;
  32553. },
  32554. enumerable: true,
  32555. configurable: true
  32556. });
  32557. /**
  32558. * Indicates if the WebGL underlying uniform buffer is dynamic.
  32559. * Also, a dynamic UniformBuffer will disable cache verification and always
  32560. * update the underlying WebGL uniform buffer to the GPU.
  32561. */
  32562. UniformBuffer.prototype.isDynamic = function () {
  32563. return this._dynamic !== undefined;
  32564. };
  32565. /**
  32566. * The data cache on JS side.
  32567. */
  32568. UniformBuffer.prototype.getData = function () {
  32569. return this._bufferData;
  32570. };
  32571. /**
  32572. * The underlying WebGL Uniform buffer.
  32573. */
  32574. UniformBuffer.prototype.getBuffer = function () {
  32575. return this._buffer;
  32576. };
  32577. /**
  32578. * std140 layout specifies how to align data within an UBO structure.
  32579. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  32580. * for specs.
  32581. */
  32582. UniformBuffer.prototype._fillAlignment = function (size) {
  32583. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  32584. // and 4x4 matrices
  32585. // TODO : change if other types are used
  32586. var alignment;
  32587. if (size <= 2) {
  32588. alignment = size;
  32589. }
  32590. else {
  32591. alignment = 4;
  32592. }
  32593. if ((this._uniformLocationPointer % alignment) !== 0) {
  32594. var oldPointer = this._uniformLocationPointer;
  32595. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  32596. var diff = this._uniformLocationPointer - oldPointer;
  32597. for (var i = 0; i < diff; i++) {
  32598. this._data.push(0);
  32599. }
  32600. }
  32601. };
  32602. /**
  32603. * Adds an uniform in the buffer.
  32604. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  32605. * for the layout to be correct !
  32606. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32607. * @param {number|number[]} size Data size, or data directly.
  32608. */
  32609. UniformBuffer.prototype.addUniform = function (name, size) {
  32610. if (this._noUBO) {
  32611. return;
  32612. }
  32613. if (this._uniformLocations[name] !== undefined) {
  32614. // Already existing uniform
  32615. return;
  32616. }
  32617. // This function must be called in the order of the shader layout !
  32618. // size can be the size of the uniform, or data directly
  32619. var data;
  32620. if (size instanceof Array) {
  32621. data = size;
  32622. size = data.length;
  32623. }
  32624. else {
  32625. size = size;
  32626. data = [];
  32627. // Fill with zeros
  32628. for (var i = 0; i < size; i++) {
  32629. data.push(0);
  32630. }
  32631. }
  32632. this._fillAlignment(size);
  32633. this._uniformSizes[name] = size;
  32634. this._uniformLocations[name] = this._uniformLocationPointer;
  32635. this._uniformLocationPointer += size;
  32636. for (var i = 0; i < size; i++) {
  32637. this._data.push(data[i]);
  32638. }
  32639. this._needSync = true;
  32640. };
  32641. /**
  32642. * Wrapper for addUniform.
  32643. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32644. * @param {Matrix} mat A 4x4 matrix.
  32645. */
  32646. UniformBuffer.prototype.addMatrix = function (name, mat) {
  32647. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  32648. };
  32649. /**
  32650. * Wrapper for addUniform.
  32651. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32652. * @param {number} x
  32653. * @param {number} y
  32654. */
  32655. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  32656. var temp = [x, y];
  32657. this.addUniform(name, temp);
  32658. };
  32659. /**
  32660. * Wrapper for addUniform.
  32661. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32662. * @param {number} x
  32663. * @param {number} y
  32664. * @param {number} z
  32665. */
  32666. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  32667. var temp = [x, y, z];
  32668. this.addUniform(name, temp);
  32669. };
  32670. /**
  32671. * Wrapper for addUniform.
  32672. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32673. * @param {Color3} color
  32674. */
  32675. UniformBuffer.prototype.addColor3 = function (name, color) {
  32676. var temp = new Array();
  32677. color.toArray(temp);
  32678. this.addUniform(name, temp);
  32679. };
  32680. /**
  32681. * Wrapper for addUniform.
  32682. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32683. * @param {Color3} color
  32684. * @param {number} alpha
  32685. */
  32686. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  32687. var temp = new Array();
  32688. color.toArray(temp);
  32689. temp.push(alpha);
  32690. this.addUniform(name, temp);
  32691. };
  32692. /**
  32693. * Wrapper for addUniform.
  32694. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32695. * @param {Vector3} vector
  32696. */
  32697. UniformBuffer.prototype.addVector3 = function (name, vector) {
  32698. var temp = new Array();
  32699. vector.toArray(temp);
  32700. this.addUniform(name, temp);
  32701. };
  32702. /**
  32703. * Wrapper for addUniform.
  32704. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32705. */
  32706. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  32707. this.addUniform(name, 12);
  32708. };
  32709. /**
  32710. * Wrapper for addUniform.
  32711. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32712. */
  32713. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  32714. this.addUniform(name, 8);
  32715. };
  32716. /**
  32717. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  32718. */
  32719. UniformBuffer.prototype.create = function () {
  32720. if (this._noUBO) {
  32721. return;
  32722. }
  32723. if (this._buffer) {
  32724. return; // nothing to do
  32725. }
  32726. // See spec, alignment must be filled as a vec4
  32727. this._fillAlignment(4);
  32728. this._bufferData = new Float32Array(this._data);
  32729. this._rebuild();
  32730. this._needSync = true;
  32731. };
  32732. UniformBuffer.prototype._rebuild = function () {
  32733. if (this._noUBO) {
  32734. return;
  32735. }
  32736. if (this._dynamic) {
  32737. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  32738. }
  32739. else {
  32740. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  32741. }
  32742. };
  32743. /**
  32744. * Updates the WebGL Uniform Buffer on the GPU.
  32745. * If the `dynamic` flag is set to true, no cache comparison is done.
  32746. * Otherwise, the buffer will be updated only if the cache differs.
  32747. */
  32748. UniformBuffer.prototype.update = function () {
  32749. if (!this._buffer) {
  32750. this.create();
  32751. return;
  32752. }
  32753. if (!this._dynamic && !this._needSync) {
  32754. return;
  32755. }
  32756. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  32757. this._needSync = false;
  32758. };
  32759. /**
  32760. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  32761. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  32762. * @param {number[]|Float32Array} data Flattened data
  32763. * @param {number} size Size of the data.
  32764. */
  32765. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  32766. var location = this._uniformLocations[uniformName];
  32767. if (location === undefined) {
  32768. if (this._buffer) {
  32769. // Cannot add an uniform if the buffer is already created
  32770. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  32771. return;
  32772. }
  32773. this.addUniform(uniformName, size);
  32774. location = this._uniformLocations[uniformName];
  32775. }
  32776. if (!this._buffer) {
  32777. this.create();
  32778. }
  32779. if (!this._dynamic) {
  32780. // Cache for static uniform buffers
  32781. var changed = false;
  32782. for (var i = 0; i < size; i++) {
  32783. if (this._bufferData[location + i] !== data[i]) {
  32784. changed = true;
  32785. this._bufferData[location + i] = data[i];
  32786. }
  32787. }
  32788. this._needSync = this._needSync || changed;
  32789. }
  32790. else {
  32791. // No cache for dynamic
  32792. for (var i = 0; i < size; i++) {
  32793. this._bufferData[location + i] = data[i];
  32794. }
  32795. }
  32796. };
  32797. // Update methods
  32798. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  32799. // To match std140, matrix must be realigned
  32800. for (var i = 0; i < 3; i++) {
  32801. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  32802. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  32803. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  32804. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  32805. }
  32806. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  32807. };
  32808. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  32809. this._currentEffect.setMatrix3x3(name, matrix);
  32810. };
  32811. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  32812. this._currentEffect.setMatrix2x2(name, matrix);
  32813. };
  32814. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  32815. // To match std140, matrix must be realigned
  32816. for (var i = 0; i < 2; i++) {
  32817. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  32818. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  32819. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  32820. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  32821. }
  32822. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  32823. };
  32824. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  32825. this._currentEffect.setFloat(name, x);
  32826. };
  32827. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  32828. UniformBuffer._tempBuffer[0] = x;
  32829. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  32830. };
  32831. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  32832. if (suffix === void 0) { suffix = ""; }
  32833. this._currentEffect.setFloat2(name + suffix, x, y);
  32834. };
  32835. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  32836. if (suffix === void 0) { suffix = ""; }
  32837. UniformBuffer._tempBuffer[0] = x;
  32838. UniformBuffer._tempBuffer[1] = y;
  32839. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  32840. };
  32841. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  32842. if (suffix === void 0) { suffix = ""; }
  32843. this._currentEffect.setFloat3(name + suffix, x, y, z);
  32844. };
  32845. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  32846. if (suffix === void 0) { suffix = ""; }
  32847. UniformBuffer._tempBuffer[0] = x;
  32848. UniformBuffer._tempBuffer[1] = y;
  32849. UniformBuffer._tempBuffer[2] = z;
  32850. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32851. };
  32852. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  32853. if (suffix === void 0) { suffix = ""; }
  32854. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  32855. };
  32856. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  32857. if (suffix === void 0) { suffix = ""; }
  32858. UniformBuffer._tempBuffer[0] = x;
  32859. UniformBuffer._tempBuffer[1] = y;
  32860. UniformBuffer._tempBuffer[2] = z;
  32861. UniformBuffer._tempBuffer[3] = w;
  32862. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32863. };
  32864. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  32865. this._currentEffect.setMatrix(name, mat);
  32866. };
  32867. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  32868. this.updateUniform(name, mat.toArray(), 16);
  32869. };
  32870. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  32871. this._currentEffect.setVector3(name, vector);
  32872. };
  32873. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  32874. vector.toArray(UniformBuffer._tempBuffer);
  32875. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32876. };
  32877. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  32878. this._currentEffect.setVector4(name, vector);
  32879. };
  32880. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  32881. vector.toArray(UniformBuffer._tempBuffer);
  32882. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32883. };
  32884. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  32885. if (suffix === void 0) { suffix = ""; }
  32886. this._currentEffect.setColor3(name + suffix, color);
  32887. };
  32888. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  32889. if (suffix === void 0) { suffix = ""; }
  32890. color.toArray(UniformBuffer._tempBuffer);
  32891. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32892. };
  32893. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  32894. if (suffix === void 0) { suffix = ""; }
  32895. this._currentEffect.setColor4(name + suffix, color, alpha);
  32896. };
  32897. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  32898. if (suffix === void 0) { suffix = ""; }
  32899. color.toArray(UniformBuffer._tempBuffer);
  32900. UniformBuffer._tempBuffer[3] = alpha;
  32901. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32902. };
  32903. /**
  32904. * Sets a sampler uniform on the effect.
  32905. * @param {string} name Name of the sampler.
  32906. * @param {Texture} texture
  32907. */
  32908. UniformBuffer.prototype.setTexture = function (name, texture) {
  32909. this._currentEffect.setTexture(name, texture);
  32910. };
  32911. /**
  32912. * Directly updates the value of the uniform in the cache AND on the GPU.
  32913. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  32914. * @param {number[]|Float32Array} data Flattened data
  32915. */
  32916. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  32917. this.updateUniform(uniformName, data, data.length);
  32918. this.update();
  32919. };
  32920. /**
  32921. * Binds this uniform buffer to an effect.
  32922. * @param {Effect} effect
  32923. * @param {string} name Name of the uniform block in the shader.
  32924. */
  32925. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  32926. this._currentEffect = effect;
  32927. if (this._noUBO || !this._buffer) {
  32928. return;
  32929. }
  32930. effect.bindUniformBuffer(this._buffer, name);
  32931. };
  32932. /**
  32933. * Disposes the uniform buffer.
  32934. */
  32935. UniformBuffer.prototype.dispose = function () {
  32936. if (this._noUBO) {
  32937. return;
  32938. }
  32939. var index = this._engine._uniformBuffers.indexOf(this);
  32940. if (index !== -1) {
  32941. this._engine._uniformBuffers.splice(index, 1);
  32942. }
  32943. if (!this._buffer) {
  32944. return;
  32945. }
  32946. if (this._engine._releaseBuffer(this._buffer)) {
  32947. this._buffer = null;
  32948. }
  32949. };
  32950. // Pool for avoiding memory leaks
  32951. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  32952. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  32953. return UniformBuffer;
  32954. }());
  32955. BABYLON.UniformBuffer = UniformBuffer;
  32956. })(BABYLON || (BABYLON = {}));
  32957. //# sourceMappingURL=babylon.uniformBuffer.js.map
  32958. "use strict";
  32959. var BABYLON;
  32960. (function (BABYLON) {
  32961. var VertexData = /** @class */ (function () {
  32962. function VertexData() {
  32963. }
  32964. VertexData.prototype.set = function (data, kind) {
  32965. switch (kind) {
  32966. case BABYLON.VertexBuffer.PositionKind:
  32967. this.positions = data;
  32968. break;
  32969. case BABYLON.VertexBuffer.NormalKind:
  32970. this.normals = data;
  32971. break;
  32972. case BABYLON.VertexBuffer.TangentKind:
  32973. this.tangents = data;
  32974. break;
  32975. case BABYLON.VertexBuffer.UVKind:
  32976. this.uvs = data;
  32977. break;
  32978. case BABYLON.VertexBuffer.UV2Kind:
  32979. this.uvs2 = data;
  32980. break;
  32981. case BABYLON.VertexBuffer.UV3Kind:
  32982. this.uvs3 = data;
  32983. break;
  32984. case BABYLON.VertexBuffer.UV4Kind:
  32985. this.uvs4 = data;
  32986. break;
  32987. case BABYLON.VertexBuffer.UV5Kind:
  32988. this.uvs5 = data;
  32989. break;
  32990. case BABYLON.VertexBuffer.UV6Kind:
  32991. this.uvs6 = data;
  32992. break;
  32993. case BABYLON.VertexBuffer.ColorKind:
  32994. this.colors = data;
  32995. break;
  32996. case BABYLON.VertexBuffer.MatricesIndicesKind:
  32997. this.matricesIndices = data;
  32998. break;
  32999. case BABYLON.VertexBuffer.MatricesWeightsKind:
  33000. this.matricesWeights = data;
  33001. break;
  33002. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  33003. this.matricesIndicesExtra = data;
  33004. break;
  33005. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  33006. this.matricesWeightsExtra = data;
  33007. break;
  33008. }
  33009. };
  33010. /**
  33011. * Associates the vertexData to the passed Mesh.
  33012. * Sets it as updatable or not (default `false`).
  33013. * Returns the VertexData.
  33014. */
  33015. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  33016. this._applyTo(mesh, updatable);
  33017. return this;
  33018. };
  33019. /**
  33020. * Associates the vertexData to the passed Geometry.
  33021. * Sets it as updatable or not (default `false`).
  33022. * Returns the VertexData.
  33023. */
  33024. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  33025. this._applyTo(geometry, updatable);
  33026. return this;
  33027. };
  33028. /**
  33029. * Updates the associated mesh.
  33030. * Returns the VertexData.
  33031. */
  33032. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  33033. this._update(mesh);
  33034. return this;
  33035. };
  33036. /**
  33037. * Updates the associated geometry.
  33038. * Returns the VertexData.
  33039. */
  33040. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  33041. this._update(geometry);
  33042. return this;
  33043. };
  33044. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  33045. if (updatable === void 0) { updatable = false; }
  33046. if (this.positions) {
  33047. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  33048. }
  33049. if (this.normals) {
  33050. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  33051. }
  33052. if (this.tangents) {
  33053. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  33054. }
  33055. if (this.uvs) {
  33056. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  33057. }
  33058. if (this.uvs2) {
  33059. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  33060. }
  33061. if (this.uvs3) {
  33062. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  33063. }
  33064. if (this.uvs4) {
  33065. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  33066. }
  33067. if (this.uvs5) {
  33068. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  33069. }
  33070. if (this.uvs6) {
  33071. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  33072. }
  33073. if (this.colors) {
  33074. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  33075. }
  33076. if (this.matricesIndices) {
  33077. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  33078. }
  33079. if (this.matricesWeights) {
  33080. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  33081. }
  33082. if (this.matricesIndicesExtra) {
  33083. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  33084. }
  33085. if (this.matricesWeightsExtra) {
  33086. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  33087. }
  33088. if (this.indices) {
  33089. meshOrGeometry.setIndices(this.indices, null, updatable);
  33090. }
  33091. return this;
  33092. };
  33093. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  33094. if (this.positions) {
  33095. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  33096. }
  33097. if (this.normals) {
  33098. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  33099. }
  33100. if (this.tangents) {
  33101. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  33102. }
  33103. if (this.uvs) {
  33104. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  33105. }
  33106. if (this.uvs2) {
  33107. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  33108. }
  33109. if (this.uvs3) {
  33110. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  33111. }
  33112. if (this.uvs4) {
  33113. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  33114. }
  33115. if (this.uvs5) {
  33116. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  33117. }
  33118. if (this.uvs6) {
  33119. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  33120. }
  33121. if (this.colors) {
  33122. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  33123. }
  33124. if (this.matricesIndices) {
  33125. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  33126. }
  33127. if (this.matricesWeights) {
  33128. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  33129. }
  33130. if (this.matricesIndicesExtra) {
  33131. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  33132. }
  33133. if (this.matricesWeightsExtra) {
  33134. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  33135. }
  33136. if (this.indices) {
  33137. meshOrGeometry.setIndices(this.indices, null);
  33138. }
  33139. return this;
  33140. };
  33141. /**
  33142. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  33143. * Returns the VertexData.
  33144. */
  33145. VertexData.prototype.transform = function (matrix) {
  33146. var transformed = BABYLON.Vector3.Zero();
  33147. var index;
  33148. if (this.positions) {
  33149. var position = BABYLON.Vector3.Zero();
  33150. for (index = 0; index < this.positions.length; index += 3) {
  33151. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  33152. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  33153. this.positions[index] = transformed.x;
  33154. this.positions[index + 1] = transformed.y;
  33155. this.positions[index + 2] = transformed.z;
  33156. }
  33157. }
  33158. if (this.normals) {
  33159. var normal = BABYLON.Vector3.Zero();
  33160. for (index = 0; index < this.normals.length; index += 3) {
  33161. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  33162. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  33163. this.normals[index] = transformed.x;
  33164. this.normals[index + 1] = transformed.y;
  33165. this.normals[index + 2] = transformed.z;
  33166. }
  33167. }
  33168. if (this.tangents) {
  33169. var tangent = BABYLON.Vector4.Zero();
  33170. var tangentTransformed = BABYLON.Vector4.Zero();
  33171. for (index = 0; index < this.tangents.length; index += 4) {
  33172. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  33173. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  33174. this.tangents[index] = tangentTransformed.x;
  33175. this.tangents[index + 1] = tangentTransformed.y;
  33176. this.tangents[index + 2] = tangentTransformed.z;
  33177. this.tangents[index + 3] = tangentTransformed.w;
  33178. }
  33179. }
  33180. return this;
  33181. };
  33182. /**
  33183. * Merges the passed VertexData into the current one.
  33184. * Returns the modified VertexData.
  33185. */
  33186. VertexData.prototype.merge = function (other) {
  33187. this._validate();
  33188. other._validate();
  33189. if (!this.normals !== !other.normals ||
  33190. !this.tangents !== !other.tangents ||
  33191. !this.uvs !== !other.uvs ||
  33192. !this.uvs2 !== !other.uvs2 ||
  33193. !this.uvs3 !== !other.uvs3 ||
  33194. !this.uvs4 !== !other.uvs4 ||
  33195. !this.uvs5 !== !other.uvs5 ||
  33196. !this.uvs6 !== !other.uvs6 ||
  33197. !this.colors !== !other.colors ||
  33198. !this.matricesIndices !== !other.matricesIndices ||
  33199. !this.matricesWeights !== !other.matricesWeights ||
  33200. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  33201. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  33202. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  33203. }
  33204. if (other.indices) {
  33205. if (!this.indices) {
  33206. this.indices = [];
  33207. }
  33208. var offset = this.positions ? this.positions.length / 3 : 0;
  33209. for (var index = 0; index < other.indices.length; index++) {
  33210. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  33211. this.indices.push(other.indices[index] + offset);
  33212. }
  33213. }
  33214. this.positions = this._mergeElement(this.positions, other.positions);
  33215. this.normals = this._mergeElement(this.normals, other.normals);
  33216. this.tangents = this._mergeElement(this.tangents, other.tangents);
  33217. this.uvs = this._mergeElement(this.uvs, other.uvs);
  33218. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  33219. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  33220. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  33221. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  33222. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  33223. this.colors = this._mergeElement(this.colors, other.colors);
  33224. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  33225. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  33226. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  33227. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  33228. return this;
  33229. };
  33230. VertexData.prototype._mergeElement = function (source, other) {
  33231. if (!source) {
  33232. return other;
  33233. }
  33234. if (!other) {
  33235. return source;
  33236. }
  33237. var len = other.length + source.length;
  33238. var isSrcTypedArray = source instanceof Float32Array;
  33239. var isOthTypedArray = other instanceof Float32Array;
  33240. // use non-loop method when the source is Float32Array
  33241. if (isSrcTypedArray) {
  33242. var ret32 = new Float32Array(len);
  33243. ret32.set(source);
  33244. ret32.set(other, source.length);
  33245. return ret32;
  33246. // source is number[], when other is also use concat
  33247. }
  33248. else if (!isOthTypedArray) {
  33249. return source.concat(other);
  33250. // source is a number[], but other is a Float32Array, loop required
  33251. }
  33252. else {
  33253. var ret = source.slice(0); // copy source to a separate array
  33254. for (var i = 0, len = other.length; i < len; i++) {
  33255. ret.push(other[i]);
  33256. }
  33257. return ret;
  33258. }
  33259. };
  33260. VertexData.prototype._validate = function () {
  33261. if (!this.positions) {
  33262. throw new Error("Positions are required");
  33263. }
  33264. var getElementCount = function (kind, values) {
  33265. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  33266. if ((values.length % stride) !== 0) {
  33267. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  33268. }
  33269. return values.length / stride;
  33270. };
  33271. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  33272. var validateElementCount = function (kind, values) {
  33273. var elementCount = getElementCount(kind, values);
  33274. if (elementCount !== positionsElementCount) {
  33275. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  33276. }
  33277. };
  33278. if (this.normals)
  33279. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  33280. if (this.tangents)
  33281. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  33282. if (this.uvs)
  33283. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  33284. if (this.uvs2)
  33285. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  33286. if (this.uvs3)
  33287. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  33288. if (this.uvs4)
  33289. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  33290. if (this.uvs5)
  33291. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  33292. if (this.uvs6)
  33293. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  33294. if (this.colors)
  33295. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  33296. if (this.matricesIndices)
  33297. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  33298. if (this.matricesWeights)
  33299. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  33300. if (this.matricesIndicesExtra)
  33301. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  33302. if (this.matricesWeightsExtra)
  33303. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  33304. };
  33305. /**
  33306. * Serializes the VertexData.
  33307. * Returns a serialized object.
  33308. */
  33309. VertexData.prototype.serialize = function () {
  33310. var serializationObject = this.serialize();
  33311. if (this.positions) {
  33312. serializationObject.positions = this.positions;
  33313. }
  33314. if (this.normals) {
  33315. serializationObject.normals = this.normals;
  33316. }
  33317. if (this.tangents) {
  33318. serializationObject.tangents = this.tangents;
  33319. }
  33320. if (this.uvs) {
  33321. serializationObject.uvs = this.uvs;
  33322. }
  33323. if (this.uvs2) {
  33324. serializationObject.uvs2 = this.uvs2;
  33325. }
  33326. if (this.uvs3) {
  33327. serializationObject.uvs3 = this.uvs3;
  33328. }
  33329. if (this.uvs4) {
  33330. serializationObject.uvs4 = this.uvs4;
  33331. }
  33332. if (this.uvs5) {
  33333. serializationObject.uvs5 = this.uvs5;
  33334. }
  33335. if (this.uvs6) {
  33336. serializationObject.uvs6 = this.uvs6;
  33337. }
  33338. if (this.colors) {
  33339. serializationObject.colors = this.colors;
  33340. }
  33341. if (this.matricesIndices) {
  33342. serializationObject.matricesIndices = this.matricesIndices;
  33343. serializationObject.matricesIndices._isExpanded = true;
  33344. }
  33345. if (this.matricesWeights) {
  33346. serializationObject.matricesWeights = this.matricesWeights;
  33347. }
  33348. if (this.matricesIndicesExtra) {
  33349. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  33350. serializationObject.matricesIndicesExtra._isExpanded = true;
  33351. }
  33352. if (this.matricesWeightsExtra) {
  33353. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  33354. }
  33355. serializationObject.indices = this.indices;
  33356. return serializationObject;
  33357. };
  33358. // Statics
  33359. /**
  33360. * Returns the object VertexData associated to the passed mesh.
  33361. */
  33362. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  33363. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  33364. };
  33365. /**
  33366. * Returns the object VertexData associated to the passed geometry.
  33367. */
  33368. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  33369. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  33370. };
  33371. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  33372. var result = new VertexData();
  33373. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33374. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  33375. }
  33376. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33377. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  33378. }
  33379. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  33380. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  33381. }
  33382. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  33383. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  33384. }
  33385. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  33386. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  33387. }
  33388. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  33389. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  33390. }
  33391. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  33392. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  33393. }
  33394. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  33395. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  33396. }
  33397. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  33398. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  33399. }
  33400. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  33401. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  33402. }
  33403. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33404. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  33405. }
  33406. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33407. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  33408. }
  33409. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  33410. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  33411. }
  33412. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  33413. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  33414. }
  33415. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  33416. return result;
  33417. };
  33418. /**
  33419. * Creates the vertexData of the Ribbon.
  33420. */
  33421. VertexData.CreateRibbon = function (options) {
  33422. var pathArray = options.pathArray;
  33423. var closeArray = options.closeArray || false;
  33424. var closePath = options.closePath || false;
  33425. var invertUV = options.invertUV || false;
  33426. var defaultOffset = Math.floor(pathArray[0].length / 2);
  33427. var offset = options.offset || defaultOffset;
  33428. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  33429. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33430. var customUV = options.uvs;
  33431. var customColors = options.colors;
  33432. var positions = [];
  33433. var indices = [];
  33434. var normals = [];
  33435. var uvs = [];
  33436. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  33437. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  33438. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  33439. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  33440. var minlg; // minimal length among all paths from pathArray
  33441. var lg = []; // array of path lengths : nb of vertex per path
  33442. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  33443. var p; // path iterator
  33444. var i; // point iterator
  33445. var j; // point iterator
  33446. // if single path in pathArray
  33447. if (pathArray.length < 2) {
  33448. var ar1 = [];
  33449. var ar2 = [];
  33450. for (i = 0; i < pathArray[0].length - offset; i++) {
  33451. ar1.push(pathArray[0][i]);
  33452. ar2.push(pathArray[0][i + offset]);
  33453. }
  33454. pathArray = [ar1, ar2];
  33455. }
  33456. // positions and horizontal distances (u)
  33457. var idc = 0;
  33458. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  33459. var path;
  33460. var l;
  33461. minlg = pathArray[0].length;
  33462. var vectlg;
  33463. var dist;
  33464. for (p = 0; p < pathArray.length; p++) {
  33465. uTotalDistance[p] = 0;
  33466. us[p] = [0];
  33467. path = pathArray[p];
  33468. l = path.length;
  33469. minlg = (minlg < l) ? minlg : l;
  33470. j = 0;
  33471. while (j < l) {
  33472. positions.push(path[j].x, path[j].y, path[j].z);
  33473. if (j > 0) {
  33474. vectlg = path[j].subtract(path[j - 1]).length();
  33475. dist = vectlg + uTotalDistance[p];
  33476. us[p].push(dist);
  33477. uTotalDistance[p] = dist;
  33478. }
  33479. j++;
  33480. }
  33481. if (closePath) {
  33482. j--;
  33483. positions.push(path[0].x, path[0].y, path[0].z);
  33484. vectlg = path[j].subtract(path[0]).length();
  33485. dist = vectlg + uTotalDistance[p];
  33486. us[p].push(dist);
  33487. uTotalDistance[p] = dist;
  33488. }
  33489. lg[p] = l + closePathCorr;
  33490. idx[p] = idc;
  33491. idc += (l + closePathCorr);
  33492. }
  33493. // vertical distances (v)
  33494. var path1;
  33495. var path2;
  33496. var vertex1 = null;
  33497. var vertex2 = null;
  33498. for (i = 0; i < minlg + closePathCorr; i++) {
  33499. vTotalDistance[i] = 0;
  33500. vs[i] = [0];
  33501. for (p = 0; p < pathArray.length - 1; p++) {
  33502. path1 = pathArray[p];
  33503. path2 = pathArray[p + 1];
  33504. if (i === minlg) {
  33505. vertex1 = path1[0];
  33506. vertex2 = path2[0];
  33507. }
  33508. else {
  33509. vertex1 = path1[i];
  33510. vertex2 = path2[i];
  33511. }
  33512. vectlg = vertex2.subtract(vertex1).length();
  33513. dist = vectlg + vTotalDistance[i];
  33514. vs[i].push(dist);
  33515. vTotalDistance[i] = dist;
  33516. }
  33517. if (closeArray && vertex2 && vertex1) {
  33518. path1 = pathArray[p];
  33519. path2 = pathArray[0];
  33520. if (i === minlg) {
  33521. vertex2 = path2[0];
  33522. }
  33523. vectlg = vertex2.subtract(vertex1).length();
  33524. dist = vectlg + vTotalDistance[i];
  33525. vTotalDistance[i] = dist;
  33526. }
  33527. }
  33528. // uvs
  33529. var u;
  33530. var v;
  33531. if (customUV) {
  33532. for (p = 0; p < customUV.length; p++) {
  33533. uvs.push(customUV[p].x, customUV[p].y);
  33534. }
  33535. }
  33536. else {
  33537. for (p = 0; p < pathArray.length; p++) {
  33538. for (i = 0; i < minlg + closePathCorr; i++) {
  33539. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  33540. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  33541. if (invertUV) {
  33542. uvs.push(v, u);
  33543. }
  33544. else {
  33545. uvs.push(u, v);
  33546. }
  33547. }
  33548. }
  33549. }
  33550. // indices
  33551. p = 0; // path index
  33552. var pi = 0; // positions array index
  33553. var l1 = lg[p] - 1; // path1 length
  33554. var l2 = lg[p + 1] - 1; // path2 length
  33555. var min = (l1 < l2) ? l1 : l2; // current path stop index
  33556. var shft = idx[1] - idx[0]; // shift
  33557. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  33558. while (pi <= min && p < path1nb) {
  33559. // 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
  33560. indices.push(pi, pi + shft, pi + 1);
  33561. indices.push(pi + shft + 1, pi + 1, pi + shft);
  33562. pi += 1;
  33563. if (pi === min) {
  33564. p++;
  33565. if (p === lg.length - 1) {
  33566. shft = idx[0] - idx[p];
  33567. l1 = lg[p] - 1;
  33568. l2 = lg[0] - 1;
  33569. }
  33570. else {
  33571. shft = idx[p + 1] - idx[p];
  33572. l1 = lg[p] - 1;
  33573. l2 = lg[p + 1] - 1;
  33574. }
  33575. pi = idx[p];
  33576. min = (l1 < l2) ? l1 + pi : l2 + pi;
  33577. }
  33578. }
  33579. // normals
  33580. VertexData.ComputeNormals(positions, indices, normals);
  33581. if (closePath) {
  33582. var indexFirst = 0;
  33583. var indexLast = 0;
  33584. for (p = 0; p < pathArray.length; p++) {
  33585. indexFirst = idx[p] * 3;
  33586. if (p + 1 < pathArray.length) {
  33587. indexLast = (idx[p + 1] - 1) * 3;
  33588. }
  33589. else {
  33590. indexLast = normals.length - 3;
  33591. }
  33592. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  33593. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  33594. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  33595. normals[indexLast] = normals[indexFirst];
  33596. normals[indexLast + 1] = normals[indexFirst + 1];
  33597. normals[indexLast + 2] = normals[indexFirst + 2];
  33598. }
  33599. }
  33600. // sides
  33601. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33602. // Colors
  33603. var colors = null;
  33604. if (customColors) {
  33605. colors = new Float32Array(customColors.length * 4);
  33606. for (var c = 0; c < customColors.length; c++) {
  33607. colors[c * 4] = customColors[c].r;
  33608. colors[c * 4 + 1] = customColors[c].g;
  33609. colors[c * 4 + 2] = customColors[c].b;
  33610. colors[c * 4 + 3] = customColors[c].a;
  33611. }
  33612. }
  33613. // Result
  33614. var vertexData = new VertexData();
  33615. var positions32 = new Float32Array(positions);
  33616. var normals32 = new Float32Array(normals);
  33617. var uvs32 = new Float32Array(uvs);
  33618. vertexData.indices = indices;
  33619. vertexData.positions = positions32;
  33620. vertexData.normals = normals32;
  33621. vertexData.uvs = uvs32;
  33622. if (colors) {
  33623. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  33624. }
  33625. if (closePath) {
  33626. vertexData._idx = idx;
  33627. }
  33628. return vertexData;
  33629. };
  33630. /**
  33631. * Creates the VertexData of the Box.
  33632. */
  33633. VertexData.CreateBox = function (options) {
  33634. var normalsSource = [
  33635. new BABYLON.Vector3(0, 0, 1),
  33636. new BABYLON.Vector3(0, 0, -1),
  33637. new BABYLON.Vector3(1, 0, 0),
  33638. new BABYLON.Vector3(-1, 0, 0),
  33639. new BABYLON.Vector3(0, 1, 0),
  33640. new BABYLON.Vector3(0, -1, 0)
  33641. ];
  33642. var indices = [];
  33643. var positions = [];
  33644. var normals = [];
  33645. var uvs = [];
  33646. var width = options.width || options.size || 1;
  33647. var height = options.height || options.size || 1;
  33648. var depth = options.depth || options.size || 1;
  33649. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33650. var faceUV = options.faceUV || new Array(6);
  33651. var faceColors = options.faceColors;
  33652. var colors = [];
  33653. // default face colors and UV if undefined
  33654. for (var f = 0; f < 6; f++) {
  33655. if (faceUV[f] === undefined) {
  33656. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33657. }
  33658. if (faceColors && faceColors[f] === undefined) {
  33659. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33660. }
  33661. }
  33662. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  33663. // Create each face in turn.
  33664. for (var index = 0; index < normalsSource.length; index++) {
  33665. var normal = normalsSource[index];
  33666. // Get two vectors perpendicular to the face normal and to each other.
  33667. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  33668. var side2 = BABYLON.Vector3.Cross(normal, side1);
  33669. // Six indices (two triangles) per face.
  33670. var verticesLength = positions.length / 3;
  33671. indices.push(verticesLength);
  33672. indices.push(verticesLength + 1);
  33673. indices.push(verticesLength + 2);
  33674. indices.push(verticesLength);
  33675. indices.push(verticesLength + 2);
  33676. indices.push(verticesLength + 3);
  33677. // Four vertices per face.
  33678. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  33679. positions.push(vertex.x, vertex.y, vertex.z);
  33680. normals.push(normal.x, normal.y, normal.z);
  33681. uvs.push(faceUV[index].z, faceUV[index].w);
  33682. if (faceColors) {
  33683. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33684. }
  33685. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  33686. positions.push(vertex.x, vertex.y, vertex.z);
  33687. normals.push(normal.x, normal.y, normal.z);
  33688. uvs.push(faceUV[index].x, faceUV[index].w);
  33689. if (faceColors) {
  33690. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33691. }
  33692. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  33693. positions.push(vertex.x, vertex.y, vertex.z);
  33694. normals.push(normal.x, normal.y, normal.z);
  33695. uvs.push(faceUV[index].x, faceUV[index].y);
  33696. if (faceColors) {
  33697. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33698. }
  33699. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  33700. positions.push(vertex.x, vertex.y, vertex.z);
  33701. normals.push(normal.x, normal.y, normal.z);
  33702. uvs.push(faceUV[index].z, faceUV[index].y);
  33703. if (faceColors) {
  33704. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33705. }
  33706. }
  33707. // sides
  33708. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33709. // Result
  33710. var vertexData = new VertexData();
  33711. vertexData.indices = indices;
  33712. vertexData.positions = positions;
  33713. vertexData.normals = normals;
  33714. vertexData.uvs = uvs;
  33715. if (faceColors) {
  33716. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  33717. vertexData.colors = totalColors;
  33718. }
  33719. return vertexData;
  33720. };
  33721. /**
  33722. * Creates the VertexData of the Sphere.
  33723. */
  33724. VertexData.CreateSphere = function (options) {
  33725. var segments = options.segments || 32;
  33726. var diameterX = options.diameterX || options.diameter || 1;
  33727. var diameterY = options.diameterY || options.diameter || 1;
  33728. var diameterZ = options.diameterZ || options.diameter || 1;
  33729. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33730. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  33731. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33732. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  33733. var totalZRotationSteps = 2 + segments;
  33734. var totalYRotationSteps = 2 * totalZRotationSteps;
  33735. var indices = [];
  33736. var positions = [];
  33737. var normals = [];
  33738. var uvs = [];
  33739. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  33740. var normalizedZ = zRotationStep / totalZRotationSteps;
  33741. var angleZ = normalizedZ * Math.PI * slice;
  33742. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  33743. var normalizedY = yRotationStep / totalYRotationSteps;
  33744. var angleY = normalizedY * Math.PI * 2 * arc;
  33745. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  33746. var rotationY = BABYLON.Matrix.RotationY(angleY);
  33747. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  33748. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  33749. var vertex = complete.multiply(radius);
  33750. var normal = complete.divide(radius).normalize();
  33751. positions.push(vertex.x, vertex.y, vertex.z);
  33752. normals.push(normal.x, normal.y, normal.z);
  33753. uvs.push(normalizedY, normalizedZ);
  33754. }
  33755. if (zRotationStep > 0) {
  33756. var verticesCount = positions.length / 3;
  33757. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  33758. indices.push((firstIndex));
  33759. indices.push((firstIndex + 1));
  33760. indices.push(firstIndex + totalYRotationSteps + 1);
  33761. indices.push((firstIndex + totalYRotationSteps + 1));
  33762. indices.push((firstIndex + 1));
  33763. indices.push((firstIndex + totalYRotationSteps + 2));
  33764. }
  33765. }
  33766. }
  33767. // Sides
  33768. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33769. // Result
  33770. var vertexData = new VertexData();
  33771. vertexData.indices = indices;
  33772. vertexData.positions = positions;
  33773. vertexData.normals = normals;
  33774. vertexData.uvs = uvs;
  33775. return vertexData;
  33776. };
  33777. /**
  33778. * Creates the VertexData of the Cylinder or Cone.
  33779. */
  33780. VertexData.CreateCylinder = function (options) {
  33781. var height = options.height || 2;
  33782. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  33783. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  33784. var tessellation = options.tessellation || 24;
  33785. var subdivisions = options.subdivisions || 1;
  33786. var hasRings = options.hasRings ? true : false;
  33787. var enclose = options.enclose ? true : false;
  33788. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33789. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33790. var faceUV = options.faceUV || new Array(3);
  33791. var faceColors = options.faceColors;
  33792. // default face colors and UV if undefined
  33793. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  33794. var ringNb = (hasRings) ? subdivisions : 1;
  33795. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  33796. var f;
  33797. for (f = 0; f < surfaceNb; f++) {
  33798. if (faceColors && faceColors[f] === undefined) {
  33799. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33800. }
  33801. }
  33802. for (f = 0; f < surfaceNb; f++) {
  33803. if (faceUV && faceUV[f] === undefined) {
  33804. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33805. }
  33806. }
  33807. var indices = new Array();
  33808. var positions = new Array();
  33809. var normals = new Array();
  33810. var uvs = new Array();
  33811. var colors = new Array();
  33812. var angle_step = Math.PI * 2 * arc / tessellation;
  33813. var angle;
  33814. var h;
  33815. var radius;
  33816. var tan = (diameterBottom - diameterTop) / 2 / height;
  33817. var ringVertex = BABYLON.Vector3.Zero();
  33818. var ringNormal = BABYLON.Vector3.Zero();
  33819. var ringFirstVertex = BABYLON.Vector3.Zero();
  33820. var ringFirstNormal = BABYLON.Vector3.Zero();
  33821. var quadNormal = BABYLON.Vector3.Zero();
  33822. var Y = BABYLON.Axis.Y;
  33823. // positions, normals, uvs
  33824. var i;
  33825. var j;
  33826. var r;
  33827. var ringIdx = 1;
  33828. var s = 1; // surface index
  33829. var cs = 0;
  33830. var v = 0;
  33831. for (i = 0; i <= subdivisions; i++) {
  33832. h = i / subdivisions;
  33833. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  33834. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  33835. for (r = 0; r < ringIdx; r++) {
  33836. if (hasRings) {
  33837. s += r;
  33838. }
  33839. if (enclose) {
  33840. s += 2 * r;
  33841. }
  33842. for (j = 0; j <= tessellation; j++) {
  33843. angle = j * angle_step;
  33844. // position
  33845. ringVertex.x = Math.cos(-angle) * radius;
  33846. ringVertex.y = -height / 2 + h * height;
  33847. ringVertex.z = Math.sin(-angle) * radius;
  33848. // normal
  33849. if (diameterTop === 0 && i === subdivisions) {
  33850. // if no top cap, reuse former normals
  33851. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  33852. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  33853. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  33854. }
  33855. else {
  33856. ringNormal.x = ringVertex.x;
  33857. ringNormal.z = ringVertex.z;
  33858. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  33859. ringNormal.normalize();
  33860. }
  33861. // keep first ring vertex values for enclose
  33862. if (j === 0) {
  33863. ringFirstVertex.copyFrom(ringVertex);
  33864. ringFirstNormal.copyFrom(ringNormal);
  33865. }
  33866. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33867. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  33868. if (hasRings) {
  33869. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  33870. }
  33871. else {
  33872. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  33873. }
  33874. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  33875. if (faceColors) {
  33876. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  33877. }
  33878. }
  33879. // if enclose, add four vertices and their dedicated normals
  33880. if (arc !== 1 && enclose) {
  33881. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33882. positions.push(0, ringVertex.y, 0);
  33883. positions.push(0, ringVertex.y, 0);
  33884. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  33885. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  33886. quadNormal.normalize();
  33887. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33888. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  33889. quadNormal.normalize();
  33890. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33891. if (hasRings) {
  33892. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  33893. }
  33894. else {
  33895. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  33896. }
  33897. uvs.push(faceUV[s + 1].x, v);
  33898. uvs.push(faceUV[s + 1].z, v);
  33899. if (hasRings) {
  33900. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  33901. }
  33902. else {
  33903. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  33904. }
  33905. uvs.push(faceUV[s + 2].x, v);
  33906. uvs.push(faceUV[s + 2].z, v);
  33907. if (faceColors) {
  33908. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33909. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33910. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33911. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33912. }
  33913. }
  33914. if (cs !== s) {
  33915. cs = s;
  33916. }
  33917. }
  33918. }
  33919. // indices
  33920. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  33921. var s;
  33922. i = 0;
  33923. for (s = 0; s < subdivisions; s++) {
  33924. var i0 = 0;
  33925. var i1 = 0;
  33926. var i2 = 0;
  33927. var i3 = 0;
  33928. for (j = 0; j < tessellation; j++) {
  33929. i0 = i * (e + 1) + j;
  33930. i1 = (i + 1) * (e + 1) + j;
  33931. i2 = i * (e + 1) + (j + 1);
  33932. i3 = (i + 1) * (e + 1) + (j + 1);
  33933. indices.push(i0, i1, i2);
  33934. indices.push(i3, i2, i1);
  33935. }
  33936. if (arc !== 1 && enclose) {
  33937. indices.push(i0 + 2, i1 + 2, i2 + 2);
  33938. indices.push(i3 + 2, i2 + 2, i1 + 2);
  33939. indices.push(i0 + 4, i1 + 4, i2 + 4);
  33940. indices.push(i3 + 4, i2 + 4, i1 + 4);
  33941. }
  33942. i = (hasRings) ? (i + 2) : (i + 1);
  33943. }
  33944. // Caps
  33945. var createCylinderCap = function (isTop) {
  33946. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  33947. if (radius === 0) {
  33948. return;
  33949. }
  33950. // Cap positions, normals & uvs
  33951. var angle;
  33952. var circleVector;
  33953. var i;
  33954. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  33955. var c = null;
  33956. if (faceColors) {
  33957. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  33958. }
  33959. // cap center
  33960. var vbase = positions.length / 3;
  33961. var offset = isTop ? height / 2 : -height / 2;
  33962. var center = new BABYLON.Vector3(0, offset, 0);
  33963. positions.push(center.x, center.y, center.z);
  33964. normals.push(0, isTop ? 1 : -1, 0);
  33965. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  33966. if (c) {
  33967. colors.push(c.r, c.g, c.b, c.a);
  33968. }
  33969. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  33970. for (i = 0; i <= tessellation; i++) {
  33971. angle = Math.PI * 2 * i * arc / tessellation;
  33972. var cos = Math.cos(-angle);
  33973. var sin = Math.sin(-angle);
  33974. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  33975. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  33976. positions.push(circleVector.x, circleVector.y, circleVector.z);
  33977. normals.push(0, isTop ? 1 : -1, 0);
  33978. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  33979. if (c) {
  33980. colors.push(c.r, c.g, c.b, c.a);
  33981. }
  33982. }
  33983. // Cap indices
  33984. for (i = 0; i < tessellation; i++) {
  33985. if (!isTop) {
  33986. indices.push(vbase);
  33987. indices.push(vbase + (i + 1));
  33988. indices.push(vbase + (i + 2));
  33989. }
  33990. else {
  33991. indices.push(vbase);
  33992. indices.push(vbase + (i + 2));
  33993. indices.push(vbase + (i + 1));
  33994. }
  33995. }
  33996. };
  33997. // add caps to geometry
  33998. createCylinderCap(false);
  33999. createCylinderCap(true);
  34000. // Sides
  34001. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34002. var vertexData = new VertexData();
  34003. vertexData.indices = indices;
  34004. vertexData.positions = positions;
  34005. vertexData.normals = normals;
  34006. vertexData.uvs = uvs;
  34007. if (faceColors) {
  34008. vertexData.colors = colors;
  34009. }
  34010. return vertexData;
  34011. };
  34012. /**
  34013. * Creates the VertexData of the Torus.
  34014. */
  34015. VertexData.CreateTorus = function (options) {
  34016. var indices = [];
  34017. var positions = [];
  34018. var normals = [];
  34019. var uvs = [];
  34020. var diameter = options.diameter || 1;
  34021. var thickness = options.thickness || 0.5;
  34022. var tessellation = options.tessellation || 16;
  34023. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34024. var stride = tessellation + 1;
  34025. for (var i = 0; i <= tessellation; i++) {
  34026. var u = i / tessellation;
  34027. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  34028. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  34029. for (var j = 0; j <= tessellation; j++) {
  34030. var v = 1 - j / tessellation;
  34031. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  34032. var dx = Math.cos(innerAngle);
  34033. var dy = Math.sin(innerAngle);
  34034. // Create a vertex.
  34035. var normal = new BABYLON.Vector3(dx, dy, 0);
  34036. var position = normal.scale(thickness / 2);
  34037. var textureCoordinate = new BABYLON.Vector2(u, v);
  34038. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  34039. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  34040. positions.push(position.x, position.y, position.z);
  34041. normals.push(normal.x, normal.y, normal.z);
  34042. uvs.push(textureCoordinate.x, textureCoordinate.y);
  34043. // And create indices for two triangles.
  34044. var nextI = (i + 1) % stride;
  34045. var nextJ = (j + 1) % stride;
  34046. indices.push(i * stride + j);
  34047. indices.push(i * stride + nextJ);
  34048. indices.push(nextI * stride + j);
  34049. indices.push(i * stride + nextJ);
  34050. indices.push(nextI * stride + nextJ);
  34051. indices.push(nextI * stride + j);
  34052. }
  34053. }
  34054. // Sides
  34055. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34056. // Result
  34057. var vertexData = new VertexData();
  34058. vertexData.indices = indices;
  34059. vertexData.positions = positions;
  34060. vertexData.normals = normals;
  34061. vertexData.uvs = uvs;
  34062. return vertexData;
  34063. };
  34064. /**
  34065. * Creates the VertexData of the LineSystem.
  34066. */
  34067. VertexData.CreateLineSystem = function (options) {
  34068. var indices = [];
  34069. var positions = [];
  34070. var lines = options.lines;
  34071. var colors = options.colors;
  34072. var vertexColors = [];
  34073. var idx = 0;
  34074. for (var l = 0; l < lines.length; l++) {
  34075. var points = lines[l];
  34076. for (var index = 0; index < points.length; index++) {
  34077. positions.push(points[index].x, points[index].y, points[index].z);
  34078. if (colors) {
  34079. var color = colors[l];
  34080. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  34081. }
  34082. if (index > 0) {
  34083. indices.push(idx - 1);
  34084. indices.push(idx);
  34085. }
  34086. idx++;
  34087. }
  34088. }
  34089. var vertexData = new VertexData();
  34090. vertexData.indices = indices;
  34091. vertexData.positions = positions;
  34092. if (colors) {
  34093. vertexData.colors = vertexColors;
  34094. }
  34095. return vertexData;
  34096. };
  34097. /**
  34098. * Create the VertexData of the DashedLines.
  34099. */
  34100. VertexData.CreateDashedLines = function (options) {
  34101. var dashSize = options.dashSize || 3;
  34102. var gapSize = options.gapSize || 1;
  34103. var dashNb = options.dashNb || 200;
  34104. var points = options.points;
  34105. var positions = new Array();
  34106. var indices = new Array();
  34107. var curvect = BABYLON.Vector3.Zero();
  34108. var lg = 0;
  34109. var nb = 0;
  34110. var shft = 0;
  34111. var dashshft = 0;
  34112. var curshft = 0;
  34113. var idx = 0;
  34114. var i = 0;
  34115. for (i = 0; i < points.length - 1; i++) {
  34116. points[i + 1].subtractToRef(points[i], curvect);
  34117. lg += curvect.length();
  34118. }
  34119. shft = lg / dashNb;
  34120. dashshft = dashSize * shft / (dashSize + gapSize);
  34121. for (i = 0; i < points.length - 1; i++) {
  34122. points[i + 1].subtractToRef(points[i], curvect);
  34123. nb = Math.floor(curvect.length() / shft);
  34124. curvect.normalize();
  34125. for (var j = 0; j < nb; j++) {
  34126. curshft = shft * j;
  34127. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  34128. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  34129. indices.push(idx, idx + 1);
  34130. idx += 2;
  34131. }
  34132. }
  34133. // Result
  34134. var vertexData = new VertexData();
  34135. vertexData.positions = positions;
  34136. vertexData.indices = indices;
  34137. return vertexData;
  34138. };
  34139. /**
  34140. * Creates the VertexData of the Ground.
  34141. */
  34142. VertexData.CreateGround = function (options) {
  34143. var indices = [];
  34144. var positions = [];
  34145. var normals = [];
  34146. var uvs = [];
  34147. var row, col;
  34148. var width = options.width || 1;
  34149. var height = options.height || 1;
  34150. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  34151. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  34152. for (row = 0; row <= subdivisionsY; row++) {
  34153. for (col = 0; col <= subdivisionsX; col++) {
  34154. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  34155. var normal = new BABYLON.Vector3(0, 1.0, 0);
  34156. positions.push(position.x, position.y, position.z);
  34157. normals.push(normal.x, normal.y, normal.z);
  34158. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  34159. }
  34160. }
  34161. for (row = 0; row < subdivisionsY; row++) {
  34162. for (col = 0; col < subdivisionsX; col++) {
  34163. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  34164. indices.push(col + 1 + row * (subdivisionsX + 1));
  34165. indices.push(col + row * (subdivisionsX + 1));
  34166. indices.push(col + (row + 1) * (subdivisionsX + 1));
  34167. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  34168. indices.push(col + row * (subdivisionsX + 1));
  34169. }
  34170. }
  34171. // Result
  34172. var vertexData = new VertexData();
  34173. vertexData.indices = indices;
  34174. vertexData.positions = positions;
  34175. vertexData.normals = normals;
  34176. vertexData.uvs = uvs;
  34177. return vertexData;
  34178. };
  34179. /**
  34180. * Creates the VertexData of the TiledGround.
  34181. */
  34182. VertexData.CreateTiledGround = function (options) {
  34183. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  34184. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  34185. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  34186. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  34187. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  34188. var precision = options.precision || { w: 1, h: 1 };
  34189. var indices = new Array();
  34190. var positions = new Array();
  34191. var normals = new Array();
  34192. var uvs = new Array();
  34193. var row, col, tileRow, tileCol;
  34194. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  34195. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  34196. precision.w = (precision.w < 1) ? 1 : precision.w;
  34197. precision.h = (precision.h < 1) ? 1 : precision.h;
  34198. var tileSize = {
  34199. 'w': (xmax - xmin) / subdivisions.w,
  34200. 'h': (zmax - zmin) / subdivisions.h
  34201. };
  34202. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  34203. // Indices
  34204. var base = positions.length / 3;
  34205. var rowLength = precision.w + 1;
  34206. for (row = 0; row < precision.h; row++) {
  34207. for (col = 0; col < precision.w; col++) {
  34208. var square = [
  34209. base + col + row * rowLength,
  34210. base + (col + 1) + row * rowLength,
  34211. base + (col + 1) + (row + 1) * rowLength,
  34212. base + col + (row + 1) * rowLength
  34213. ];
  34214. indices.push(square[1]);
  34215. indices.push(square[2]);
  34216. indices.push(square[3]);
  34217. indices.push(square[0]);
  34218. indices.push(square[1]);
  34219. indices.push(square[3]);
  34220. }
  34221. }
  34222. // Position, normals and uvs
  34223. var position = BABYLON.Vector3.Zero();
  34224. var normal = new BABYLON.Vector3(0, 1.0, 0);
  34225. for (row = 0; row <= precision.h; row++) {
  34226. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  34227. for (col = 0; col <= precision.w; col++) {
  34228. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  34229. position.y = 0;
  34230. positions.push(position.x, position.y, position.z);
  34231. normals.push(normal.x, normal.y, normal.z);
  34232. uvs.push(col / precision.w, row / precision.h);
  34233. }
  34234. }
  34235. }
  34236. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  34237. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  34238. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  34239. }
  34240. }
  34241. // Result
  34242. var vertexData = new VertexData();
  34243. vertexData.indices = indices;
  34244. vertexData.positions = positions;
  34245. vertexData.normals = normals;
  34246. vertexData.uvs = uvs;
  34247. return vertexData;
  34248. };
  34249. /**
  34250. * Creates the VertexData of the Ground designed from a heightmap.
  34251. */
  34252. VertexData.CreateGroundFromHeightMap = function (options) {
  34253. var indices = [];
  34254. var positions = [];
  34255. var normals = [];
  34256. var uvs = [];
  34257. var row, col;
  34258. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  34259. // Vertices
  34260. for (row = 0; row <= options.subdivisions; row++) {
  34261. for (col = 0; col <= options.subdivisions; col++) {
  34262. 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));
  34263. // Compute height
  34264. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  34265. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  34266. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  34267. var r = options.buffer[pos] / 255.0;
  34268. var g = options.buffer[pos + 1] / 255.0;
  34269. var b = options.buffer[pos + 2] / 255.0;
  34270. var gradient = r * filter.r + g * filter.g + b * filter.b;
  34271. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  34272. // Add vertex
  34273. positions.push(position.x, position.y, position.z);
  34274. normals.push(0, 0, 0);
  34275. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  34276. }
  34277. }
  34278. // Indices
  34279. for (row = 0; row < options.subdivisions; row++) {
  34280. for (col = 0; col < options.subdivisions; col++) {
  34281. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  34282. indices.push(col + 1 + row * (options.subdivisions + 1));
  34283. indices.push(col + row * (options.subdivisions + 1));
  34284. indices.push(col + (row + 1) * (options.subdivisions + 1));
  34285. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  34286. indices.push(col + row * (options.subdivisions + 1));
  34287. }
  34288. }
  34289. // Normals
  34290. VertexData.ComputeNormals(positions, indices, normals);
  34291. // Result
  34292. var vertexData = new VertexData();
  34293. vertexData.indices = indices;
  34294. vertexData.positions = positions;
  34295. vertexData.normals = normals;
  34296. vertexData.uvs = uvs;
  34297. return vertexData;
  34298. };
  34299. /**
  34300. * Creates the VertexData of the Plane.
  34301. */
  34302. VertexData.CreatePlane = function (options) {
  34303. var indices = [];
  34304. var positions = [];
  34305. var normals = [];
  34306. var uvs = [];
  34307. var width = options.width || options.size || 1;
  34308. var height = options.height || options.size || 1;
  34309. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34310. // Vertices
  34311. var halfWidth = width / 2.0;
  34312. var halfHeight = height / 2.0;
  34313. positions.push(-halfWidth, -halfHeight, 0);
  34314. normals.push(0, 0, -1.0);
  34315. uvs.push(0.0, 0.0);
  34316. positions.push(halfWidth, -halfHeight, 0);
  34317. normals.push(0, 0, -1.0);
  34318. uvs.push(1.0, 0.0);
  34319. positions.push(halfWidth, halfHeight, 0);
  34320. normals.push(0, 0, -1.0);
  34321. uvs.push(1.0, 1.0);
  34322. positions.push(-halfWidth, halfHeight, 0);
  34323. normals.push(0, 0, -1.0);
  34324. uvs.push(0.0, 1.0);
  34325. // Indices
  34326. indices.push(0);
  34327. indices.push(1);
  34328. indices.push(2);
  34329. indices.push(0);
  34330. indices.push(2);
  34331. indices.push(3);
  34332. // Sides
  34333. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34334. // Result
  34335. var vertexData = new VertexData();
  34336. vertexData.indices = indices;
  34337. vertexData.positions = positions;
  34338. vertexData.normals = normals;
  34339. vertexData.uvs = uvs;
  34340. return vertexData;
  34341. };
  34342. /**
  34343. * Creates the VertexData of the Disc or regular Polygon.
  34344. */
  34345. VertexData.CreateDisc = function (options) {
  34346. var positions = new Array();
  34347. var indices = new Array();
  34348. var normals = new Array();
  34349. var uvs = new Array();
  34350. var radius = options.radius || 0.5;
  34351. var tessellation = options.tessellation || 64;
  34352. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  34353. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34354. // positions and uvs
  34355. positions.push(0, 0, 0); // disc center first
  34356. uvs.push(0.5, 0.5);
  34357. var theta = Math.PI * 2 * arc;
  34358. var step = theta / tessellation;
  34359. for (var a = 0; a < theta; a += step) {
  34360. var x = Math.cos(a);
  34361. var y = Math.sin(a);
  34362. var u = (x + 1) / 2;
  34363. var v = (1 - y) / 2;
  34364. positions.push(radius * x, radius * y, 0);
  34365. uvs.push(u, v);
  34366. }
  34367. if (arc === 1) {
  34368. positions.push(positions[3], positions[4], positions[5]); // close the circle
  34369. uvs.push(uvs[2], uvs[3]);
  34370. }
  34371. //indices
  34372. var vertexNb = positions.length / 3;
  34373. for (var i = 1; i < vertexNb - 1; i++) {
  34374. indices.push(i + 1, 0, i);
  34375. }
  34376. // result
  34377. VertexData.ComputeNormals(positions, indices, normals);
  34378. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34379. var vertexData = new VertexData();
  34380. vertexData.indices = indices;
  34381. vertexData.positions = positions;
  34382. vertexData.normals = normals;
  34383. vertexData.uvs = uvs;
  34384. return vertexData;
  34385. };
  34386. /**
  34387. * Re-creates the VertexData of the Polygon for sideOrientation.
  34388. */
  34389. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  34390. var faceUV = fUV || new Array(3);
  34391. var faceColors = fColors;
  34392. var colors = [];
  34393. // default face colors and UV if undefined
  34394. for (var f = 0; f < 3; f++) {
  34395. if (faceUV[f] === undefined) {
  34396. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  34397. }
  34398. if (faceColors && faceColors[f] === undefined) {
  34399. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  34400. }
  34401. }
  34402. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34403. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34404. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  34405. var indices = polygon.getIndices();
  34406. // set face colours and textures
  34407. var idx = 0;
  34408. var face = 0;
  34409. for (var index = 0; index < normals.length; index += 3) {
  34410. //Edge Face no. 1
  34411. if (Math.abs(normals[index + 1]) < 0.001) {
  34412. face = 1;
  34413. }
  34414. //Top Face no. 0
  34415. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  34416. face = 0;
  34417. }
  34418. //Bottom Face no. 2
  34419. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  34420. face = 2;
  34421. }
  34422. idx = index / 3;
  34423. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  34424. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  34425. if (faceColors) {
  34426. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  34427. }
  34428. }
  34429. // sides
  34430. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  34431. // Result
  34432. var vertexData = new VertexData();
  34433. vertexData.indices = indices;
  34434. vertexData.positions = positions;
  34435. vertexData.normals = normals;
  34436. vertexData.uvs = uvs;
  34437. if (faceColors) {
  34438. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  34439. vertexData.colors = totalColors;
  34440. }
  34441. return vertexData;
  34442. };
  34443. /**
  34444. * Creates the VertexData of the IcoSphere.
  34445. */
  34446. VertexData.CreateIcoSphere = function (options) {
  34447. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34448. var radius = options.radius || 1;
  34449. var flat = (options.flat === undefined) ? true : options.flat;
  34450. var subdivisions = options.subdivisions || 4;
  34451. var radiusX = options.radiusX || radius;
  34452. var radiusY = options.radiusY || radius;
  34453. var radiusZ = options.radiusZ || radius;
  34454. var t = (1 + Math.sqrt(5)) / 2;
  34455. // 12 vertex x,y,z
  34456. var ico_vertices = [
  34457. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  34458. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  34459. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  34460. ];
  34461. // index of 3 vertex makes a face of icopshere
  34462. var ico_indices = [
  34463. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  34464. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  34465. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  34466. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  34467. ];
  34468. // vertex for uv have aliased position, not for UV
  34469. var vertices_unalias_id = [
  34470. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  34471. // vertex alias
  34472. 0,
  34473. 2,
  34474. 3,
  34475. 3,
  34476. 3,
  34477. 4,
  34478. 7,
  34479. 8,
  34480. 9,
  34481. 9,
  34482. 10,
  34483. 11 // 23: B + 12
  34484. ];
  34485. // uv as integer step (not pixels !)
  34486. var ico_vertexuv = [
  34487. 5, 1, 3, 1, 6, 4, 0, 0,
  34488. 5, 3, 4, 2, 2, 2, 4, 0,
  34489. 2, 0, 1, 1, 6, 0, 6, 2,
  34490. // vertex alias (for same vertex on different faces)
  34491. 0, 4,
  34492. 3, 3,
  34493. 4, 4,
  34494. 3, 1,
  34495. 4, 2,
  34496. 4, 4,
  34497. 0, 2,
  34498. 1, 1,
  34499. 2, 2,
  34500. 3, 3,
  34501. 1, 3,
  34502. 2, 4 // 23: B + 12
  34503. ];
  34504. // Vertices[0, 1, ...9, A, B] : position on UV plane
  34505. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  34506. // First island of uv mapping
  34507. // v = 4h 3+ 2
  34508. // v = 3h 9+ 4
  34509. // v = 2h 9+ 5 B
  34510. // v = 1h 9 1 0
  34511. // v = 0h 3 8 7 A
  34512. // u = 0 1 2 3 4 5 6 *a
  34513. // Second island of uv mapping
  34514. // v = 4h 0+ B+ 4+
  34515. // v = 3h A+ 2+
  34516. // v = 2h 7+ 6 3+
  34517. // v = 1h 8+ 3+
  34518. // v = 0h
  34519. // u = 0 1 2 3 4 5 6 *a
  34520. // Face layout on texture UV mapping
  34521. // ============
  34522. // \ 4 /\ 16 / ======
  34523. // \ / \ / /\ 11 /
  34524. // \/ 7 \/ / \ /
  34525. // ======= / 10 \/
  34526. // /\ 17 /\ =======
  34527. // / \ / \ \ 15 /\
  34528. // / 8 \/ 12 \ \ / \
  34529. // ============ \/ 6 \
  34530. // \ 18 /\ ============
  34531. // \ / \ \ 5 /\ 0 /
  34532. // \/ 13 \ \ / \ /
  34533. // ======= \/ 1 \/
  34534. // =============
  34535. // /\ 19 /\ 2 /\
  34536. // / \ / \ / \
  34537. // / 14 \/ 9 \/ 3 \
  34538. // ===================
  34539. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  34540. var ustep = 138 / 1024;
  34541. var vstep = 239 / 1024;
  34542. var uoffset = 60 / 1024;
  34543. var voffset = 26 / 1024;
  34544. // Second island should have margin, not to touch the first island
  34545. // avoid any borderline artefact in pixel rounding
  34546. var island_u_offset = -40 / 1024;
  34547. var island_v_offset = +20 / 1024;
  34548. // face is either island 0 or 1 :
  34549. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  34550. var island = [
  34551. 0, 0, 0, 0, 1,
  34552. 0, 0, 1, 1, 0,
  34553. 0, 0, 1, 1, 0,
  34554. 0, 1, 1, 1, 0 // 15 - 19
  34555. ];
  34556. var indices = new Array();
  34557. var positions = new Array();
  34558. var normals = new Array();
  34559. var uvs = new Array();
  34560. var current_indice = 0;
  34561. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  34562. var face_vertex_pos = new Array(3);
  34563. var face_vertex_uv = new Array(3);
  34564. var v012;
  34565. for (v012 = 0; v012 < 3; v012++) {
  34566. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  34567. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  34568. }
  34569. // create all with normals
  34570. for (var face = 0; face < 20; face++) {
  34571. // 3 vertex per face
  34572. for (v012 = 0; v012 < 3; v012++) {
  34573. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  34574. var v_id = ico_indices[3 * face + v012];
  34575. // vertex have 3D position (x,y,z)
  34576. 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]);
  34577. // Normalize to get normal, then scale to radius
  34578. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  34579. // uv Coordinates from vertex ID
  34580. 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);
  34581. }
  34582. // Subdivide the face (interpolate pos, norm, uv)
  34583. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  34584. // - norm is linear interpolation of vertex corner normal
  34585. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  34586. // - uv is linear interpolation
  34587. //
  34588. // Topology is as below for sub-divide by 2
  34589. // vertex shown as v0,v1,v2
  34590. // interp index is i1 to progress in range [v0,v1[
  34591. // interp index is i2 to progress in range [v0,v2[
  34592. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  34593. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  34594. //
  34595. //
  34596. // i2 v2
  34597. // ^ ^
  34598. // / / \
  34599. // / / \
  34600. // / / \
  34601. // / / (0,1) \
  34602. // / #---------\
  34603. // / / \ (0,0)'/ \
  34604. // / / \ / \
  34605. // / / \ / \
  34606. // / / (0,0) \ / (1,0) \
  34607. // / #---------#---------\
  34608. // v0 v1
  34609. //
  34610. // --------------------> i1
  34611. //
  34612. // interp of (i1,i2):
  34613. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  34614. // along i1 : lerp(x0,x1, i1/(S-i2))
  34615. //
  34616. // centroid of triangle is needed to get help normal computation
  34617. // (c1,c2) are used for centroid location
  34618. var interp_vertex = function (i1, i2, c1, c2) {
  34619. // vertex is interpolated from
  34620. // - face_vertex_pos[0..2]
  34621. // - face_vertex_uv[0..2]
  34622. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  34623. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  34624. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  34625. pos_interp.normalize();
  34626. var vertex_normal;
  34627. if (flat) {
  34628. // in flat mode, recalculate normal as face centroid normal
  34629. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  34630. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  34631. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  34632. }
  34633. else {
  34634. // in smooth mode, recalculate normal from each single vertex position
  34635. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  34636. }
  34637. // Vertex normal need correction due to X,Y,Z radius scaling
  34638. vertex_normal.x /= radiusX;
  34639. vertex_normal.y /= radiusY;
  34640. vertex_normal.z /= radiusZ;
  34641. vertex_normal.normalize();
  34642. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  34643. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  34644. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  34645. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  34646. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  34647. uvs.push(uv_interp.x, uv_interp.y);
  34648. // push each vertex has member of a face
  34649. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  34650. indices.push(current_indice);
  34651. current_indice++;
  34652. };
  34653. for (var i2 = 0; i2 < subdivisions; i2++) {
  34654. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  34655. // face : (i1,i2) for /\ :
  34656. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  34657. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34658. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34659. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34660. if (i1 + i2 + 1 < subdivisions) {
  34661. // face : (i1,i2)' for \/ :
  34662. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  34663. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34664. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34665. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34666. }
  34667. }
  34668. }
  34669. }
  34670. // Sides
  34671. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34672. // Result
  34673. var vertexData = new VertexData();
  34674. vertexData.indices = indices;
  34675. vertexData.positions = positions;
  34676. vertexData.normals = normals;
  34677. vertexData.uvs = uvs;
  34678. return vertexData;
  34679. };
  34680. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  34681. /**
  34682. * Creates the VertexData of the Polyhedron.
  34683. */
  34684. VertexData.CreatePolyhedron = function (options) {
  34685. // provided polyhedron types :
  34686. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  34687. // 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)
  34688. var polyhedra = [];
  34689. 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]] };
  34690. 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]] };
  34691. polyhedra[2] = {
  34692. 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]],
  34693. 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]]
  34694. };
  34695. polyhedra[3] = {
  34696. 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]],
  34697. 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]]
  34698. };
  34699. polyhedra[4] = {
  34700. 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]],
  34701. 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]]
  34702. };
  34703. 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]] };
  34704. 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]] };
  34705. 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]] };
  34706. 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]] };
  34707. 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]] };
  34708. 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]] };
  34709. 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]] };
  34710. 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]] };
  34711. 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]] };
  34712. polyhedra[14] = {
  34713. 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]],
  34714. 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]]
  34715. };
  34716. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  34717. var size = options.size;
  34718. var sizeX = options.sizeX || size || 1;
  34719. var sizeY = options.sizeY || size || 1;
  34720. var sizeZ = options.sizeZ || size || 1;
  34721. var data = options.custom || polyhedra[type];
  34722. var nbfaces = data.face.length;
  34723. var faceUV = options.faceUV || new Array(nbfaces);
  34724. var faceColors = options.faceColors;
  34725. var flat = (options.flat === undefined) ? true : options.flat;
  34726. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34727. var positions = new Array();
  34728. var indices = new Array();
  34729. var normals = new Array();
  34730. var uvs = new Array();
  34731. var colors = new Array();
  34732. var index = 0;
  34733. var faceIdx = 0; // face cursor in the array "indexes"
  34734. var indexes = new Array();
  34735. var i = 0;
  34736. var f = 0;
  34737. var u, v, ang, x, y, tmp;
  34738. // default face colors and UV if undefined
  34739. if (flat) {
  34740. for (f = 0; f < nbfaces; f++) {
  34741. if (faceColors && faceColors[f] === undefined) {
  34742. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  34743. }
  34744. if (faceUV && faceUV[f] === undefined) {
  34745. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  34746. }
  34747. }
  34748. }
  34749. if (!flat) {
  34750. for (i = 0; i < data.vertex.length; i++) {
  34751. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  34752. uvs.push(0, 0);
  34753. }
  34754. for (f = 0; f < nbfaces; f++) {
  34755. for (i = 0; i < data.face[f].length - 2; i++) {
  34756. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  34757. }
  34758. }
  34759. }
  34760. else {
  34761. for (f = 0; f < nbfaces; f++) {
  34762. var fl = data.face[f].length; // number of vertices of the current face
  34763. ang = 2 * Math.PI / fl;
  34764. x = 0.5 * Math.tan(ang / 2);
  34765. y = 0.5;
  34766. // positions, uvs, colors
  34767. for (i = 0; i < fl; i++) {
  34768. // positions
  34769. 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);
  34770. indexes.push(index);
  34771. index++;
  34772. // uvs
  34773. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  34774. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  34775. uvs.push(u, v);
  34776. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  34777. y = x * Math.sin(ang) + y * Math.cos(ang);
  34778. x = tmp;
  34779. // colors
  34780. if (faceColors) {
  34781. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  34782. }
  34783. }
  34784. // indices from indexes
  34785. for (i = 0; i < fl - 2; i++) {
  34786. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  34787. }
  34788. faceIdx += fl;
  34789. }
  34790. }
  34791. VertexData.ComputeNormals(positions, indices, normals);
  34792. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34793. var vertexData = new VertexData();
  34794. vertexData.positions = positions;
  34795. vertexData.indices = indices;
  34796. vertexData.normals = normals;
  34797. vertexData.uvs = uvs;
  34798. if (faceColors && flat) {
  34799. vertexData.colors = colors;
  34800. }
  34801. return vertexData;
  34802. };
  34803. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  34804. /**
  34805. * Creates the VertexData of the Torus Knot.
  34806. */
  34807. VertexData.CreateTorusKnot = function (options) {
  34808. var indices = new Array();
  34809. var positions = new Array();
  34810. var normals = new Array();
  34811. var uvs = new Array();
  34812. var radius = options.radius || 2;
  34813. var tube = options.tube || 0.5;
  34814. var radialSegments = options.radialSegments || 32;
  34815. var tubularSegments = options.tubularSegments || 32;
  34816. var p = options.p || 2;
  34817. var q = options.q || 3;
  34818. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34819. // Helper
  34820. var getPos = function (angle) {
  34821. var cu = Math.cos(angle);
  34822. var su = Math.sin(angle);
  34823. var quOverP = q / p * angle;
  34824. var cs = Math.cos(quOverP);
  34825. var tx = radius * (2 + cs) * 0.5 * cu;
  34826. var ty = radius * (2 + cs) * su * 0.5;
  34827. var tz = radius * Math.sin(quOverP) * 0.5;
  34828. return new BABYLON.Vector3(tx, ty, tz);
  34829. };
  34830. // Vertices
  34831. var i;
  34832. var j;
  34833. for (i = 0; i <= radialSegments; i++) {
  34834. var modI = i % radialSegments;
  34835. var u = modI / radialSegments * 2 * p * Math.PI;
  34836. var p1 = getPos(u);
  34837. var p2 = getPos(u + 0.01);
  34838. var tang = p2.subtract(p1);
  34839. var n = p2.add(p1);
  34840. var bitan = BABYLON.Vector3.Cross(tang, n);
  34841. n = BABYLON.Vector3.Cross(bitan, tang);
  34842. bitan.normalize();
  34843. n.normalize();
  34844. for (j = 0; j < tubularSegments; j++) {
  34845. var modJ = j % tubularSegments;
  34846. var v = modJ / tubularSegments * 2 * Math.PI;
  34847. var cx = -tube * Math.cos(v);
  34848. var cy = tube * Math.sin(v);
  34849. positions.push(p1.x + cx * n.x + cy * bitan.x);
  34850. positions.push(p1.y + cx * n.y + cy * bitan.y);
  34851. positions.push(p1.z + cx * n.z + cy * bitan.z);
  34852. uvs.push(i / radialSegments);
  34853. uvs.push(j / tubularSegments);
  34854. }
  34855. }
  34856. for (i = 0; i < radialSegments; i++) {
  34857. for (j = 0; j < tubularSegments; j++) {
  34858. var jNext = (j + 1) % tubularSegments;
  34859. var a = i * tubularSegments + j;
  34860. var b = (i + 1) * tubularSegments + j;
  34861. var c = (i + 1) * tubularSegments + jNext;
  34862. var d = i * tubularSegments + jNext;
  34863. indices.push(d);
  34864. indices.push(b);
  34865. indices.push(a);
  34866. indices.push(d);
  34867. indices.push(c);
  34868. indices.push(b);
  34869. }
  34870. }
  34871. // Normals
  34872. VertexData.ComputeNormals(positions, indices, normals);
  34873. // Sides
  34874. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34875. // Result
  34876. var vertexData = new VertexData();
  34877. vertexData.indices = indices;
  34878. vertexData.positions = positions;
  34879. vertexData.normals = normals;
  34880. vertexData.uvs = uvs;
  34881. return vertexData;
  34882. };
  34883. // Tools
  34884. /**
  34885. * @param {any} - positions (number[] or Float32Array)
  34886. * @param {any} - indices (number[] or Uint16Array)
  34887. * @param {any} - normals (number[] or Float32Array)
  34888. * options (optional) :
  34889. * facetPositions : optional array of facet positions (vector3)
  34890. * facetNormals : optional array of facet normals (vector3)
  34891. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  34892. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  34893. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  34894. * bbSize : optional bounding box size data, required for facetPartitioning computation
  34895. * bInfo : optional bounding info, required for facetPartitioning computation
  34896. * useRightHandedSystem: optional boolean to for right handed system computation
  34897. * depthSort : optional boolean to enable the facet depth sort computation
  34898. * distanceTo : optional Vector3 to compute the facet depth from this location
  34899. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  34900. */
  34901. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  34902. // temporary scalar variables
  34903. var index = 0; // facet index
  34904. var p1p2x = 0.0; // p1p2 vector x coordinate
  34905. var p1p2y = 0.0; // p1p2 vector y coordinate
  34906. var p1p2z = 0.0; // p1p2 vector z coordinate
  34907. var p3p2x = 0.0; // p3p2 vector x coordinate
  34908. var p3p2y = 0.0; // p3p2 vector y coordinate
  34909. var p3p2z = 0.0; // p3p2 vector z coordinate
  34910. var faceNormalx = 0.0; // facet normal x coordinate
  34911. var faceNormaly = 0.0; // facet normal y coordinate
  34912. var faceNormalz = 0.0; // facet normal z coordinate
  34913. var length = 0.0; // facet normal length before normalization
  34914. var v1x = 0; // vector1 x index in the positions array
  34915. var v1y = 0; // vector1 y index in the positions array
  34916. var v1z = 0; // vector1 z index in the positions array
  34917. var v2x = 0; // vector2 x index in the positions array
  34918. var v2y = 0; // vector2 y index in the positions array
  34919. var v2z = 0; // vector2 z index in the positions array
  34920. var v3x = 0; // vector3 x index in the positions array
  34921. var v3y = 0; // vector3 y index in the positions array
  34922. var v3z = 0; // vector3 z index in the positions array
  34923. var computeFacetNormals = false;
  34924. var computeFacetPositions = false;
  34925. var computeFacetPartitioning = false;
  34926. var computeDepthSort = false;
  34927. var faceNormalSign = 1;
  34928. var ratio = 0;
  34929. var distanceTo = null;
  34930. if (options) {
  34931. computeFacetNormals = (options.facetNormals) ? true : false;
  34932. computeFacetPositions = (options.facetPositions) ? true : false;
  34933. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  34934. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  34935. ratio = options.ratio || 0;
  34936. computeDepthSort = (options.depthSort) ? true : false;
  34937. distanceTo = (options.distanceTo);
  34938. if (computeDepthSort) {
  34939. if (distanceTo === undefined) {
  34940. distanceTo = BABYLON.Vector3.Zero();
  34941. }
  34942. var depthSortedFacets = options.depthSortedFacets;
  34943. }
  34944. }
  34945. // facetPartitioning reinit if needed
  34946. var xSubRatio = 0;
  34947. var ySubRatio = 0;
  34948. var zSubRatio = 0;
  34949. var subSq = 0;
  34950. if (computeFacetPartitioning && options && options.bbSize) {
  34951. var ox = 0; // X partitioning index for facet position
  34952. var oy = 0; // Y partinioning index for facet position
  34953. var oz = 0; // Z partinioning index for facet position
  34954. var b1x = 0; // X partitioning index for facet v1 vertex
  34955. var b1y = 0; // Y partitioning index for facet v1 vertex
  34956. var b1z = 0; // z partitioning index for facet v1 vertex
  34957. var b2x = 0; // X partitioning index for facet v2 vertex
  34958. var b2y = 0; // Y partitioning index for facet v2 vertex
  34959. var b2z = 0; // Z partitioning index for facet v2 vertex
  34960. var b3x = 0; // X partitioning index for facet v3 vertex
  34961. var b3y = 0; // Y partitioning index for facet v3 vertex
  34962. var b3z = 0; // Z partitioning index for facet v3 vertex
  34963. var block_idx_o = 0; // facet barycenter block index
  34964. var block_idx_v1 = 0; // v1 vertex block index
  34965. var block_idx_v2 = 0; // v2 vertex block index
  34966. var block_idx_v3 = 0; // v3 vertex block index
  34967. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  34968. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  34969. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  34970. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  34971. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  34972. subSq = options.subDiv.max * options.subDiv.max;
  34973. options.facetPartitioning.length = 0;
  34974. }
  34975. // reset the normals
  34976. for (index = 0; index < positions.length; index++) {
  34977. normals[index] = 0.0;
  34978. }
  34979. // Loop : 1 indice triplet = 1 facet
  34980. var nbFaces = (indices.length / 3) | 0;
  34981. for (index = 0; index < nbFaces; index++) {
  34982. // get the indexes of the coordinates of each vertex of the facet
  34983. v1x = indices[index * 3] * 3;
  34984. v1y = v1x + 1;
  34985. v1z = v1x + 2;
  34986. v2x = indices[index * 3 + 1] * 3;
  34987. v2y = v2x + 1;
  34988. v2z = v2x + 2;
  34989. v3x = indices[index * 3 + 2] * 3;
  34990. v3y = v3x + 1;
  34991. v3z = v3x + 2;
  34992. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  34993. p1p2y = positions[v1y] - positions[v2y];
  34994. p1p2z = positions[v1z] - positions[v2z];
  34995. p3p2x = positions[v3x] - positions[v2x];
  34996. p3p2y = positions[v3y] - positions[v2y];
  34997. p3p2z = positions[v3z] - positions[v2z];
  34998. // compute the face normal with the cross product
  34999. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  35000. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  35001. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  35002. // normalize this normal and store it in the array facetData
  35003. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  35004. length = (length === 0) ? 1.0 : length;
  35005. faceNormalx /= length;
  35006. faceNormaly /= length;
  35007. faceNormalz /= length;
  35008. if (computeFacetNormals && options) {
  35009. options.facetNormals[index].x = faceNormalx;
  35010. options.facetNormals[index].y = faceNormaly;
  35011. options.facetNormals[index].z = faceNormalz;
  35012. }
  35013. if (computeFacetPositions && options) {
  35014. // compute and the facet barycenter coordinates in the array facetPositions
  35015. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  35016. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  35017. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  35018. }
  35019. if (computeFacetPartitioning && options) {
  35020. // store the facet indexes in arrays in the main facetPartitioning array :
  35021. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  35022. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  35023. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  35024. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  35025. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  35026. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  35027. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  35028. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  35029. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  35030. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  35031. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  35032. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  35033. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  35034. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  35035. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  35036. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  35037. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  35038. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  35039. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  35040. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  35041. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  35042. // push each facet index in each block containing the vertex
  35043. options.facetPartitioning[block_idx_v1].push(index);
  35044. if (block_idx_v2 != block_idx_v1) {
  35045. options.facetPartitioning[block_idx_v2].push(index);
  35046. }
  35047. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  35048. options.facetPartitioning[block_idx_v3].push(index);
  35049. }
  35050. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  35051. options.facetPartitioning[block_idx_o].push(index);
  35052. }
  35053. }
  35054. if (computeDepthSort && options && options.facetPositions) {
  35055. var dsf = depthSortedFacets[index];
  35056. dsf.ind = index * 3;
  35057. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  35058. }
  35059. // compute the normals anyway
  35060. normals[v1x] += faceNormalx; // accumulate all the normals per face
  35061. normals[v1y] += faceNormaly;
  35062. normals[v1z] += faceNormalz;
  35063. normals[v2x] += faceNormalx;
  35064. normals[v2y] += faceNormaly;
  35065. normals[v2z] += faceNormalz;
  35066. normals[v3x] += faceNormalx;
  35067. normals[v3y] += faceNormaly;
  35068. normals[v3z] += faceNormalz;
  35069. }
  35070. // last normalization of each normal
  35071. for (index = 0; index < normals.length / 3; index++) {
  35072. faceNormalx = normals[index * 3];
  35073. faceNormaly = normals[index * 3 + 1];
  35074. faceNormalz = normals[index * 3 + 2];
  35075. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  35076. length = (length === 0) ? 1.0 : length;
  35077. faceNormalx /= length;
  35078. faceNormaly /= length;
  35079. faceNormalz /= length;
  35080. normals[index * 3] = faceNormalx;
  35081. normals[index * 3 + 1] = faceNormaly;
  35082. normals[index * 3 + 2] = faceNormalz;
  35083. }
  35084. };
  35085. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  35086. var li = indices.length;
  35087. var ln = normals.length;
  35088. var i;
  35089. var n;
  35090. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  35091. switch (sideOrientation) {
  35092. case BABYLON.Mesh.FRONTSIDE:
  35093. // nothing changed
  35094. break;
  35095. case BABYLON.Mesh.BACKSIDE:
  35096. var tmp;
  35097. // indices
  35098. for (i = 0; i < li; i += 3) {
  35099. tmp = indices[i];
  35100. indices[i] = indices[i + 2];
  35101. indices[i + 2] = tmp;
  35102. }
  35103. // normals
  35104. for (n = 0; n < ln; n++) {
  35105. normals[n] = -normals[n];
  35106. }
  35107. break;
  35108. case BABYLON.Mesh.DOUBLESIDE:
  35109. // positions
  35110. var lp = positions.length;
  35111. var l = lp / 3;
  35112. for (var p = 0; p < lp; p++) {
  35113. positions[lp + p] = positions[p];
  35114. }
  35115. // indices
  35116. for (i = 0; i < li; i += 3) {
  35117. indices[i + li] = indices[i + 2] + l;
  35118. indices[i + 1 + li] = indices[i + 1] + l;
  35119. indices[i + 2 + li] = indices[i] + l;
  35120. }
  35121. // normals
  35122. for (n = 0; n < ln; n++) {
  35123. normals[ln + n] = -normals[n];
  35124. }
  35125. // uvs
  35126. var lu = uvs.length;
  35127. var u = 0;
  35128. for (u = 0; u < lu; u++) {
  35129. uvs[u + lu] = uvs[u];
  35130. }
  35131. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  35132. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  35133. u = 0;
  35134. for (i = 0; i < lu / 2; i++) {
  35135. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  35136. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  35137. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  35138. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  35139. u += 2;
  35140. }
  35141. break;
  35142. }
  35143. };
  35144. /**
  35145. * Creates a new VertexData from the imported parameters.
  35146. */
  35147. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  35148. var vertexData = new VertexData();
  35149. // positions
  35150. var positions = parsedVertexData.positions;
  35151. if (positions) {
  35152. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  35153. }
  35154. // normals
  35155. var normals = parsedVertexData.normals;
  35156. if (normals) {
  35157. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  35158. }
  35159. // tangents
  35160. var tangents = parsedVertexData.tangents;
  35161. if (tangents) {
  35162. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  35163. }
  35164. // uvs
  35165. var uvs = parsedVertexData.uvs;
  35166. if (uvs) {
  35167. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  35168. }
  35169. // uv2s
  35170. var uv2s = parsedVertexData.uv2s;
  35171. if (uv2s) {
  35172. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  35173. }
  35174. // uv3s
  35175. var uv3s = parsedVertexData.uv3s;
  35176. if (uv3s) {
  35177. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  35178. }
  35179. // uv4s
  35180. var uv4s = parsedVertexData.uv4s;
  35181. if (uv4s) {
  35182. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  35183. }
  35184. // uv5s
  35185. var uv5s = parsedVertexData.uv5s;
  35186. if (uv5s) {
  35187. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  35188. }
  35189. // uv6s
  35190. var uv6s = parsedVertexData.uv6s;
  35191. if (uv6s) {
  35192. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  35193. }
  35194. // colors
  35195. var colors = parsedVertexData.colors;
  35196. if (colors) {
  35197. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  35198. }
  35199. // matricesIndices
  35200. var matricesIndices = parsedVertexData.matricesIndices;
  35201. if (matricesIndices) {
  35202. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  35203. }
  35204. // matricesWeights
  35205. var matricesWeights = parsedVertexData.matricesWeights;
  35206. if (matricesWeights) {
  35207. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  35208. }
  35209. // indices
  35210. var indices = parsedVertexData.indices;
  35211. if (indices) {
  35212. vertexData.indices = indices;
  35213. }
  35214. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  35215. };
  35216. return VertexData;
  35217. }());
  35218. BABYLON.VertexData = VertexData;
  35219. })(BABYLON || (BABYLON = {}));
  35220. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  35221. "use strict";
  35222. var BABYLON;
  35223. (function (BABYLON) {
  35224. /**
  35225. * Class used to store geometry data (vertex buffers + index buffer)
  35226. */
  35227. var Geometry = /** @class */ (function () {
  35228. /**
  35229. * Creates a new geometry
  35230. * @param id defines the unique ID
  35231. * @param scene defines the hosting scene
  35232. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  35233. * @param updatable defines if geometry must be updatable (false by default)
  35234. * @param mesh defines the mesh that will be associated with the geometry
  35235. */
  35236. function Geometry(id, scene, vertexData, updatable, mesh) {
  35237. if (updatable === void 0) { updatable = false; }
  35238. if (mesh === void 0) { mesh = null; }
  35239. /**
  35240. * Gets the delay loading state of the geometry (none by default which means not delayed)
  35241. */
  35242. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  35243. this._totalVertices = 0;
  35244. this._isDisposed = false;
  35245. this._indexBufferIsUpdatable = false;
  35246. this.id = id;
  35247. this._engine = scene.getEngine();
  35248. this._meshes = [];
  35249. this._scene = scene;
  35250. //Init vertex buffer cache
  35251. this._vertexBuffers = {};
  35252. this._indices = [];
  35253. this._updatable = updatable;
  35254. // vertexData
  35255. if (vertexData) {
  35256. this.setAllVerticesData(vertexData, updatable);
  35257. }
  35258. else {
  35259. this._totalVertices = 0;
  35260. this._indices = [];
  35261. }
  35262. if (this._engine.getCaps().vertexArrayObject) {
  35263. this._vertexArrayObjects = {};
  35264. }
  35265. // applyToMesh
  35266. if (mesh) {
  35267. if (mesh.getClassName() === "LinesMesh") {
  35268. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  35269. this.updateExtend();
  35270. }
  35271. this.applyToMesh(mesh);
  35272. mesh.computeWorldMatrix(true);
  35273. }
  35274. }
  35275. Object.defineProperty(Geometry.prototype, "boundingBias", {
  35276. /**
  35277. * 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
  35278. */
  35279. get: function () {
  35280. return this._boundingBias;
  35281. },
  35282. /**
  35283. * 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
  35284. */
  35285. set: function (value) {
  35286. if (this._boundingBias && this._boundingBias.equals(value)) {
  35287. return;
  35288. }
  35289. this._boundingBias = value.clone();
  35290. this.updateBoundingInfo(true, null);
  35291. },
  35292. enumerable: true,
  35293. configurable: true
  35294. });
  35295. /**
  35296. * Static function used to attach a new empty geometry to a mesh
  35297. * @param mesh defines the mesh to attach the geometry to
  35298. * @returns the new {BABYLON.Geometry}
  35299. */
  35300. Geometry.CreateGeometryForMesh = function (mesh) {
  35301. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  35302. geometry.applyToMesh(mesh);
  35303. return geometry;
  35304. };
  35305. Object.defineProperty(Geometry.prototype, "extend", {
  35306. /**
  35307. * Gets the current extend of the geometry
  35308. */
  35309. get: function () {
  35310. return this._extend;
  35311. },
  35312. enumerable: true,
  35313. configurable: true
  35314. });
  35315. /**
  35316. * Gets the hosting scene
  35317. * @returns the hosting {BABYLON.Scene}
  35318. */
  35319. Geometry.prototype.getScene = function () {
  35320. return this._scene;
  35321. };
  35322. /**
  35323. * Gets the hosting engine
  35324. * @returns the hosting {BABYLON.Engine}
  35325. */
  35326. Geometry.prototype.getEngine = function () {
  35327. return this._engine;
  35328. };
  35329. /**
  35330. * Defines if the geometry is ready to use
  35331. * @returns true if the geometry is ready to be used
  35332. */
  35333. Geometry.prototype.isReady = function () {
  35334. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  35335. };
  35336. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  35337. /**
  35338. * Gets a value indicating that the geometry should not be serialized
  35339. */
  35340. get: function () {
  35341. for (var index = 0; index < this._meshes.length; index++) {
  35342. if (!this._meshes[index].doNotSerialize) {
  35343. return false;
  35344. }
  35345. }
  35346. return true;
  35347. },
  35348. enumerable: true,
  35349. configurable: true
  35350. });
  35351. /** @ignore */
  35352. Geometry.prototype._rebuild = function () {
  35353. if (this._vertexArrayObjects) {
  35354. this._vertexArrayObjects = {};
  35355. }
  35356. // Index buffer
  35357. if (this._meshes.length !== 0 && this._indices) {
  35358. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  35359. }
  35360. // Vertex buffers
  35361. for (var key in this._vertexBuffers) {
  35362. var vertexBuffer = this._vertexBuffers[key];
  35363. vertexBuffer._rebuild();
  35364. }
  35365. };
  35366. /**
  35367. * Affects all gemetry data in one call
  35368. * @param vertexData defines the geometry data
  35369. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  35370. */
  35371. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  35372. vertexData.applyToGeometry(this, updatable);
  35373. this.notifyUpdate();
  35374. };
  35375. /**
  35376. * Set specific vertex data
  35377. * @param kind defines the data kind (Position, normal, etc...)
  35378. * @param data defines the vertex data to use
  35379. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  35380. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  35381. */
  35382. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  35383. if (updatable === void 0) { updatable = false; }
  35384. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  35385. this.setVerticesBuffer(buffer);
  35386. };
  35387. /**
  35388. * Removes a specific vertex data
  35389. * @param kind defines the data kind (Position, normal, etc...)
  35390. */
  35391. Geometry.prototype.removeVerticesData = function (kind) {
  35392. if (this._vertexBuffers[kind]) {
  35393. this._vertexBuffers[kind].dispose();
  35394. delete this._vertexBuffers[kind];
  35395. }
  35396. };
  35397. /**
  35398. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  35399. * @param buffer defines the vertex buffer to use
  35400. */
  35401. Geometry.prototype.setVerticesBuffer = function (buffer) {
  35402. var kind = buffer.getKind();
  35403. if (this._vertexBuffers[kind]) {
  35404. this._vertexBuffers[kind].dispose();
  35405. }
  35406. this._vertexBuffers[kind] = buffer;
  35407. if (kind === BABYLON.VertexBuffer.PositionKind) {
  35408. var data = buffer.getData();
  35409. var stride = buffer.getStrideSize();
  35410. this._totalVertices = data.length / stride;
  35411. this.updateExtend(data, stride);
  35412. this._resetPointsArrayCache();
  35413. var meshes = this._meshes;
  35414. var numOfMeshes = meshes.length;
  35415. for (var index = 0; index < numOfMeshes; index++) {
  35416. var mesh = meshes[index];
  35417. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35418. mesh._createGlobalSubMesh(false);
  35419. mesh.computeWorldMatrix(true);
  35420. }
  35421. }
  35422. this.notifyUpdate(kind);
  35423. if (this._vertexArrayObjects) {
  35424. this._disposeVertexArrayObjects();
  35425. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  35426. }
  35427. };
  35428. /**
  35429. * Update a specific vertex buffer
  35430. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  35431. * It will do nothing if the buffer is not updatable
  35432. * @param kind defines the data kind (Position, normal, etc...)
  35433. * @param data defines the data to use
  35434. * @param offset defines the offset in the target buffer where to store the data
  35435. */
  35436. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  35437. var vertexBuffer = this.getVertexBuffer(kind);
  35438. if (!vertexBuffer) {
  35439. return;
  35440. }
  35441. vertexBuffer.updateDirectly(data, offset);
  35442. this.notifyUpdate(kind);
  35443. };
  35444. /**
  35445. * Update a specific vertex buffer
  35446. * This function will create a new buffer if the current one is not updatable
  35447. * @param kind defines the data kind (Position, normal, etc...)
  35448. * @param data defines the data to use
  35449. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  35450. */
  35451. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  35452. if (updateExtends === void 0) { updateExtends = false; }
  35453. var vertexBuffer = this.getVertexBuffer(kind);
  35454. if (!vertexBuffer) {
  35455. return;
  35456. }
  35457. vertexBuffer.update(data);
  35458. if (kind === BABYLON.VertexBuffer.PositionKind) {
  35459. var stride = vertexBuffer.getStrideSize();
  35460. this._totalVertices = data.length / stride;
  35461. this.updateBoundingInfo(updateExtends, data);
  35462. }
  35463. this.notifyUpdate(kind);
  35464. };
  35465. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  35466. if (updateExtends) {
  35467. this.updateExtend(data);
  35468. }
  35469. var meshes = this._meshes;
  35470. var numOfMeshes = meshes.length;
  35471. this._resetPointsArrayCache();
  35472. for (var index = 0; index < numOfMeshes; index++) {
  35473. var mesh = meshes[index];
  35474. if (updateExtends) {
  35475. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35476. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  35477. var subMesh = mesh.subMeshes[subIndex];
  35478. subMesh.refreshBoundingInfo();
  35479. }
  35480. }
  35481. }
  35482. };
  35483. /** @ignore */
  35484. Geometry.prototype._bind = function (effect, indexToBind) {
  35485. if (!effect) {
  35486. return;
  35487. }
  35488. if (indexToBind === undefined) {
  35489. indexToBind = this._indexBuffer;
  35490. }
  35491. var vbs = this.getVertexBuffers();
  35492. if (!vbs) {
  35493. return;
  35494. }
  35495. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  35496. this._engine.bindBuffers(vbs, indexToBind, effect);
  35497. return;
  35498. }
  35499. // Using VAO
  35500. if (!this._vertexArrayObjects[effect.key]) {
  35501. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  35502. }
  35503. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  35504. };
  35505. /**
  35506. * Gets total number of vertices
  35507. * @returns the total number of vertices
  35508. */
  35509. Geometry.prototype.getTotalVertices = function () {
  35510. if (!this.isReady()) {
  35511. return 0;
  35512. }
  35513. return this._totalVertices;
  35514. };
  35515. /**
  35516. * Gets a specific vertex data attached to this geometry
  35517. * @param kind defines the data kind (Position, normal, etc...)
  35518. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  35519. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  35520. * @returns a float array containing vertex data
  35521. */
  35522. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  35523. var vertexBuffer = this.getVertexBuffer(kind);
  35524. if (!vertexBuffer) {
  35525. return null;
  35526. }
  35527. var orig = vertexBuffer.getData();
  35528. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  35529. return orig;
  35530. }
  35531. else {
  35532. var len = orig.length;
  35533. var copy = [];
  35534. for (var i = 0; i < len; i++) {
  35535. copy.push(orig[i]);
  35536. }
  35537. return copy;
  35538. }
  35539. };
  35540. /**
  35541. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  35542. * @param kind defines the data kind (Position, normal, etc...)
  35543. * @returns true if the vertex buffer with the specified kind is updatable
  35544. */
  35545. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  35546. var vb = this._vertexBuffers[kind];
  35547. if (!vb) {
  35548. return false;
  35549. }
  35550. return vb.isUpdatable();
  35551. };
  35552. /**
  35553. * Gets a specific vertex buffer
  35554. * @param kind defines the data kind (Position, normal, etc...)
  35555. * @returns a {BABYLON.VertexBuffer}
  35556. */
  35557. Geometry.prototype.getVertexBuffer = function (kind) {
  35558. if (!this.isReady()) {
  35559. return null;
  35560. }
  35561. return this._vertexBuffers[kind];
  35562. };
  35563. /**
  35564. * Returns all vertex buffers
  35565. * @return an object holding all vertex buffers indexed by kind
  35566. */
  35567. Geometry.prototype.getVertexBuffers = function () {
  35568. if (!this.isReady()) {
  35569. return null;
  35570. }
  35571. return this._vertexBuffers;
  35572. };
  35573. /**
  35574. * Gets a boolean indicating if specific vertex buffer is present
  35575. * @param kind defines the data kind (Position, normal, etc...)
  35576. * @returns true if data is present
  35577. */
  35578. Geometry.prototype.isVerticesDataPresent = function (kind) {
  35579. if (!this._vertexBuffers) {
  35580. if (this._delayInfo) {
  35581. return this._delayInfo.indexOf(kind) !== -1;
  35582. }
  35583. return false;
  35584. }
  35585. return this._vertexBuffers[kind] !== undefined;
  35586. };
  35587. /**
  35588. * Gets a list of all attached data kinds (Position, normal, etc...)
  35589. * @returns a list of string containing all kinds
  35590. */
  35591. Geometry.prototype.getVerticesDataKinds = function () {
  35592. var result = [];
  35593. var kind;
  35594. if (!this._vertexBuffers && this._delayInfo) {
  35595. for (kind in this._delayInfo) {
  35596. result.push(kind);
  35597. }
  35598. }
  35599. else {
  35600. for (kind in this._vertexBuffers) {
  35601. result.push(kind);
  35602. }
  35603. }
  35604. return result;
  35605. };
  35606. /**
  35607. * Update index buffer
  35608. * @param indices defines the indices to store in the index buffer
  35609. * @param offset defines the offset in the target buffer where to store the data
  35610. */
  35611. Geometry.prototype.updateIndices = function (indices, offset) {
  35612. if (!this._indexBuffer) {
  35613. return;
  35614. }
  35615. if (!this._indexBufferIsUpdatable) {
  35616. this.setIndices(indices, null, true);
  35617. }
  35618. else {
  35619. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  35620. }
  35621. };
  35622. /**
  35623. * Creates a new index buffer
  35624. * @param indices defines the indices to store in the index buffer
  35625. * @param totalVertices defines the total number of vertices (could be null)
  35626. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  35627. */
  35628. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  35629. if (totalVertices === void 0) { totalVertices = null; }
  35630. if (updatable === void 0) { updatable = false; }
  35631. if (this._indexBuffer) {
  35632. this._engine._releaseBuffer(this._indexBuffer);
  35633. }
  35634. this._disposeVertexArrayObjects();
  35635. this._indices = indices;
  35636. this._indexBufferIsUpdatable = updatable;
  35637. if (this._meshes.length !== 0 && this._indices) {
  35638. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  35639. }
  35640. if (totalVertices != undefined) {
  35641. this._totalVertices = totalVertices;
  35642. }
  35643. var meshes = this._meshes;
  35644. var numOfMeshes = meshes.length;
  35645. for (var index = 0; index < numOfMeshes; index++) {
  35646. meshes[index]._createGlobalSubMesh(true);
  35647. }
  35648. this.notifyUpdate();
  35649. };
  35650. /**
  35651. * Return the total number of indices
  35652. * @returns the total number of indices
  35653. */
  35654. Geometry.prototype.getTotalIndices = function () {
  35655. if (!this.isReady()) {
  35656. return 0;
  35657. }
  35658. return this._indices.length;
  35659. };
  35660. /**
  35661. * Gets the index buffer array
  35662. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  35663. * @returns the index buffer array
  35664. */
  35665. Geometry.prototype.getIndices = function (copyWhenShared) {
  35666. if (!this.isReady()) {
  35667. return null;
  35668. }
  35669. var orig = this._indices;
  35670. if (!copyWhenShared || this._meshes.length === 1) {
  35671. return orig;
  35672. }
  35673. else {
  35674. var len = orig.length;
  35675. var copy = [];
  35676. for (var i = 0; i < len; i++) {
  35677. copy.push(orig[i]);
  35678. }
  35679. return copy;
  35680. }
  35681. };
  35682. /**
  35683. * Gets the index buffer
  35684. * @return the index buffer
  35685. */
  35686. Geometry.prototype.getIndexBuffer = function () {
  35687. if (!this.isReady()) {
  35688. return null;
  35689. }
  35690. return this._indexBuffer;
  35691. };
  35692. /** @ignore */
  35693. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  35694. if (effect === void 0) { effect = null; }
  35695. if (!effect || !this._vertexArrayObjects) {
  35696. return;
  35697. }
  35698. if (this._vertexArrayObjects[effect.key]) {
  35699. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  35700. delete this._vertexArrayObjects[effect.key];
  35701. }
  35702. };
  35703. /**
  35704. * Release the associated resources for a specific mesh
  35705. * @param mesh defines the source mesh
  35706. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  35707. */
  35708. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  35709. var meshes = this._meshes;
  35710. var index = meshes.indexOf(mesh);
  35711. if (index === -1) {
  35712. return;
  35713. }
  35714. meshes.splice(index, 1);
  35715. mesh._geometry = null;
  35716. if (meshes.length === 0 && shouldDispose) {
  35717. this.dispose();
  35718. }
  35719. };
  35720. /**
  35721. * Apply current geometry to a given mesh
  35722. * @param mesh defines the mesh to apply geometry to
  35723. */
  35724. Geometry.prototype.applyToMesh = function (mesh) {
  35725. if (mesh._geometry === this) {
  35726. return;
  35727. }
  35728. var previousGeometry = mesh._geometry;
  35729. if (previousGeometry) {
  35730. previousGeometry.releaseForMesh(mesh);
  35731. }
  35732. var meshes = this._meshes;
  35733. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  35734. mesh._geometry = this;
  35735. this._scene.pushGeometry(this);
  35736. meshes.push(mesh);
  35737. if (this.isReady()) {
  35738. this._applyToMesh(mesh);
  35739. }
  35740. else {
  35741. mesh._boundingInfo = this._boundingInfo;
  35742. }
  35743. };
  35744. Geometry.prototype.updateExtend = function (data, stride) {
  35745. if (data === void 0) { data = null; }
  35746. if (!data) {
  35747. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  35748. }
  35749. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  35750. };
  35751. Geometry.prototype._applyToMesh = function (mesh) {
  35752. var numOfMeshes = this._meshes.length;
  35753. // vertexBuffers
  35754. for (var kind in this._vertexBuffers) {
  35755. if (numOfMeshes === 1) {
  35756. this._vertexBuffers[kind].create();
  35757. }
  35758. var buffer = this._vertexBuffers[kind].getBuffer();
  35759. if (buffer)
  35760. buffer.references = numOfMeshes;
  35761. if (kind === BABYLON.VertexBuffer.PositionKind) {
  35762. if (!this._extend) {
  35763. this.updateExtend(this._vertexBuffers[kind].getData());
  35764. }
  35765. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35766. mesh._createGlobalSubMesh(false);
  35767. //bounding info was just created again, world matrix should be applied again.
  35768. mesh._updateBoundingInfo();
  35769. }
  35770. }
  35771. // indexBuffer
  35772. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  35773. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  35774. }
  35775. if (this._indexBuffer) {
  35776. this._indexBuffer.references = numOfMeshes;
  35777. }
  35778. };
  35779. Geometry.prototype.notifyUpdate = function (kind) {
  35780. if (this.onGeometryUpdated) {
  35781. this.onGeometryUpdated(this, kind);
  35782. }
  35783. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  35784. var mesh = _a[_i];
  35785. mesh._markSubMeshesAsAttributesDirty();
  35786. }
  35787. };
  35788. /**
  35789. * Load the geometry if it was flagged as delay loaded
  35790. * @param scene defines the hosting scene
  35791. * @param onLoaded defines a callback called when the geometry is loaded
  35792. */
  35793. Geometry.prototype.load = function (scene, onLoaded) {
  35794. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  35795. return;
  35796. }
  35797. if (this.isReady()) {
  35798. if (onLoaded) {
  35799. onLoaded();
  35800. }
  35801. return;
  35802. }
  35803. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  35804. this._queueLoad(scene, onLoaded);
  35805. };
  35806. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  35807. var _this = this;
  35808. if (!this.delayLoadingFile) {
  35809. return;
  35810. }
  35811. scene._addPendingData(this);
  35812. scene._loadFile(this.delayLoadingFile, function (data) {
  35813. if (!_this._delayLoadingFunction) {
  35814. return;
  35815. }
  35816. _this._delayLoadingFunction(JSON.parse(data), _this);
  35817. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  35818. _this._delayInfo = [];
  35819. scene._removePendingData(_this);
  35820. var meshes = _this._meshes;
  35821. var numOfMeshes = meshes.length;
  35822. for (var index = 0; index < numOfMeshes; index++) {
  35823. _this._applyToMesh(meshes[index]);
  35824. }
  35825. if (onLoaded) {
  35826. onLoaded();
  35827. }
  35828. }, undefined, true);
  35829. };
  35830. /**
  35831. * Invert the geometry to move from a right handed system to a left handed one.
  35832. */
  35833. Geometry.prototype.toLeftHanded = function () {
  35834. // Flip faces
  35835. var tIndices = this.getIndices(false);
  35836. if (tIndices != null && tIndices.length > 0) {
  35837. for (var i = 0; i < tIndices.length; i += 3) {
  35838. var tTemp = tIndices[i + 0];
  35839. tIndices[i + 0] = tIndices[i + 2];
  35840. tIndices[i + 2] = tTemp;
  35841. }
  35842. this.setIndices(tIndices);
  35843. }
  35844. // Negate position.z
  35845. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  35846. if (tPositions != null && tPositions.length > 0) {
  35847. for (var i = 0; i < tPositions.length; i += 3) {
  35848. tPositions[i + 2] = -tPositions[i + 2];
  35849. }
  35850. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  35851. }
  35852. // Negate normal.z
  35853. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  35854. if (tNormals != null && tNormals.length > 0) {
  35855. for (var i = 0; i < tNormals.length; i += 3) {
  35856. tNormals[i + 2] = -tNormals[i + 2];
  35857. }
  35858. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  35859. }
  35860. };
  35861. // Cache
  35862. /** @ignore */
  35863. Geometry.prototype._resetPointsArrayCache = function () {
  35864. this._positions = null;
  35865. };
  35866. /** @ignore */
  35867. Geometry.prototype._generatePointsArray = function () {
  35868. if (this._positions)
  35869. return true;
  35870. this._positions = [];
  35871. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35872. if (!data) {
  35873. return false;
  35874. }
  35875. for (var index = 0; index < data.length; index += 3) {
  35876. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  35877. }
  35878. return true;
  35879. };
  35880. /**
  35881. * Gets a value indicating if the geometry is disposed
  35882. * @returns true if the geometry was disposed
  35883. */
  35884. Geometry.prototype.isDisposed = function () {
  35885. return this._isDisposed;
  35886. };
  35887. Geometry.prototype._disposeVertexArrayObjects = function () {
  35888. if (this._vertexArrayObjects) {
  35889. for (var kind in this._vertexArrayObjects) {
  35890. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  35891. }
  35892. this._vertexArrayObjects = {};
  35893. }
  35894. };
  35895. /**
  35896. * Free all associated resources
  35897. */
  35898. Geometry.prototype.dispose = function () {
  35899. var meshes = this._meshes;
  35900. var numOfMeshes = meshes.length;
  35901. var index;
  35902. for (index = 0; index < numOfMeshes; index++) {
  35903. this.releaseForMesh(meshes[index]);
  35904. }
  35905. this._meshes = [];
  35906. this._disposeVertexArrayObjects();
  35907. for (var kind in this._vertexBuffers) {
  35908. this._vertexBuffers[kind].dispose();
  35909. }
  35910. this._vertexBuffers = {};
  35911. this._totalVertices = 0;
  35912. if (this._indexBuffer) {
  35913. this._engine._releaseBuffer(this._indexBuffer);
  35914. }
  35915. this._indexBuffer = null;
  35916. this._indices = [];
  35917. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  35918. this.delayLoadingFile = null;
  35919. this._delayLoadingFunction = null;
  35920. this._delayInfo = [];
  35921. this._boundingInfo = null;
  35922. this._scene.removeGeometry(this);
  35923. this._isDisposed = true;
  35924. };
  35925. /**
  35926. * Clone the current geometry into a new geometry
  35927. * @param id defines the unique ID of the new geometry
  35928. * @returns a new geometry object
  35929. */
  35930. Geometry.prototype.copy = function (id) {
  35931. var vertexData = new BABYLON.VertexData();
  35932. vertexData.indices = [];
  35933. var indices = this.getIndices();
  35934. if (indices) {
  35935. for (var index = 0; index < indices.length; index++) {
  35936. vertexData.indices.push(indices[index]);
  35937. }
  35938. }
  35939. var updatable = false;
  35940. var stopChecking = false;
  35941. var kind;
  35942. for (kind in this._vertexBuffers) {
  35943. // using slice() to make a copy of the array and not just reference it
  35944. var data = this.getVerticesData(kind);
  35945. if (data instanceof Float32Array) {
  35946. vertexData.set(new Float32Array(data), kind);
  35947. }
  35948. else {
  35949. vertexData.set(data.slice(0), kind);
  35950. }
  35951. if (!stopChecking) {
  35952. var vb = this.getVertexBuffer(kind);
  35953. if (vb) {
  35954. updatable = vb.isUpdatable();
  35955. stopChecking = !updatable;
  35956. }
  35957. }
  35958. }
  35959. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  35960. geometry.delayLoadState = this.delayLoadState;
  35961. geometry.delayLoadingFile = this.delayLoadingFile;
  35962. geometry._delayLoadingFunction = this._delayLoadingFunction;
  35963. for (kind in this._delayInfo) {
  35964. geometry._delayInfo = geometry._delayInfo || [];
  35965. geometry._delayInfo.push(kind);
  35966. }
  35967. // Bounding info
  35968. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35969. return geometry;
  35970. };
  35971. /**
  35972. * Serialize the current geometry info (and not the vertices data) into a JSON object
  35973. * @return a JSON representation of the current geometry data (without the vertices data)
  35974. */
  35975. Geometry.prototype.serialize = function () {
  35976. var serializationObject = {};
  35977. serializationObject.id = this.id;
  35978. serializationObject.updatable = this._updatable;
  35979. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  35980. serializationObject.tags = BABYLON.Tags.GetTags(this);
  35981. }
  35982. return serializationObject;
  35983. };
  35984. Geometry.prototype.toNumberArray = function (origin) {
  35985. if (Array.isArray(origin)) {
  35986. return origin;
  35987. }
  35988. else {
  35989. return Array.prototype.slice.call(origin);
  35990. }
  35991. };
  35992. /**
  35993. * Serialize all vertices data into a JSON oject
  35994. * @returns a JSON representation of the current geometry data
  35995. */
  35996. Geometry.prototype.serializeVerticeData = function () {
  35997. var serializationObject = this.serialize();
  35998. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  35999. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  36000. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  36001. serializationObject.positions._updatable = true;
  36002. }
  36003. }
  36004. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36005. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  36006. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  36007. serializationObject.normals._updatable = true;
  36008. }
  36009. }
  36010. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36011. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  36012. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  36013. serializationObject.tangets._updatable = true;
  36014. }
  36015. }
  36016. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36017. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  36018. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  36019. serializationObject.uvs._updatable = true;
  36020. }
  36021. }
  36022. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36023. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  36024. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  36025. serializationObject.uv2s._updatable = true;
  36026. }
  36027. }
  36028. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36029. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  36030. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  36031. serializationObject.uv3s._updatable = true;
  36032. }
  36033. }
  36034. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36035. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  36036. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  36037. serializationObject.uv4s._updatable = true;
  36038. }
  36039. }
  36040. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36041. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  36042. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  36043. serializationObject.uv5s._updatable = true;
  36044. }
  36045. }
  36046. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  36047. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  36048. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  36049. serializationObject.uv6s._updatable = true;
  36050. }
  36051. }
  36052. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36053. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  36054. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  36055. serializationObject.colors._updatable = true;
  36056. }
  36057. }
  36058. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36059. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  36060. serializationObject.matricesIndices._isExpanded = true;
  36061. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36062. serializationObject.matricesIndices._updatable = true;
  36063. }
  36064. }
  36065. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36066. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  36067. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36068. serializationObject.matricesWeights._updatable = true;
  36069. }
  36070. }
  36071. serializationObject.indices = this.toNumberArray(this.getIndices());
  36072. return serializationObject;
  36073. };
  36074. // Statics
  36075. /**
  36076. * Extracts a clone of a mesh geometry
  36077. * @param mesh defines the source mesh
  36078. * @param id defines the unique ID of the new geometry object
  36079. * @returns the new geometry object
  36080. */
  36081. Geometry.ExtractFromMesh = function (mesh, id) {
  36082. var geometry = mesh._geometry;
  36083. if (!geometry) {
  36084. return null;
  36085. }
  36086. return geometry.copy(id);
  36087. };
  36088. /**
  36089. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  36090. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  36091. * Be aware Math.random() could cause collisions, but:
  36092. * "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"
  36093. * @returns a string containing a new GUID
  36094. */
  36095. Geometry.RandomId = function () {
  36096. return BABYLON.Tools.RandomId();
  36097. };
  36098. /** @ignore */
  36099. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  36100. var scene = mesh.getScene();
  36101. // Geometry
  36102. var geometryId = parsedGeometry.geometryId;
  36103. if (geometryId) {
  36104. var geometry = scene.getGeometryByID(geometryId);
  36105. if (geometry) {
  36106. geometry.applyToMesh(mesh);
  36107. }
  36108. }
  36109. else if (parsedGeometry instanceof ArrayBuffer) {
  36110. var binaryInfo = mesh._binaryInfo;
  36111. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  36112. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  36113. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  36114. }
  36115. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  36116. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  36117. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  36118. }
  36119. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  36120. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  36121. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  36122. }
  36123. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  36124. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  36125. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  36126. }
  36127. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  36128. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  36129. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  36130. }
  36131. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  36132. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  36133. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  36134. }
  36135. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  36136. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  36137. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  36138. }
  36139. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  36140. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  36141. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  36142. }
  36143. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  36144. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  36145. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  36146. }
  36147. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  36148. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  36149. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  36150. }
  36151. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  36152. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  36153. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  36154. }
  36155. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  36156. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  36157. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  36158. }
  36159. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  36160. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  36161. mesh.setIndices(indicesData, null);
  36162. }
  36163. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  36164. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  36165. mesh.subMeshes = [];
  36166. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  36167. var materialIndex = subMeshesData[(i * 5) + 0];
  36168. var verticesStart = subMeshesData[(i * 5) + 1];
  36169. var verticesCount = subMeshesData[(i * 5) + 2];
  36170. var indexStart = subMeshesData[(i * 5) + 3];
  36171. var indexCount = subMeshesData[(i * 5) + 4];
  36172. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  36173. }
  36174. }
  36175. }
  36176. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  36177. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  36178. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  36179. if (parsedGeometry.tangents) {
  36180. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  36181. }
  36182. if (parsedGeometry.uvs) {
  36183. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  36184. }
  36185. if (parsedGeometry.uvs2) {
  36186. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  36187. }
  36188. if (parsedGeometry.uvs3) {
  36189. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  36190. }
  36191. if (parsedGeometry.uvs4) {
  36192. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  36193. }
  36194. if (parsedGeometry.uvs5) {
  36195. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  36196. }
  36197. if (parsedGeometry.uvs6) {
  36198. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  36199. }
  36200. if (parsedGeometry.colors) {
  36201. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  36202. }
  36203. if (parsedGeometry.matricesIndices) {
  36204. if (!parsedGeometry.matricesIndices._isExpanded) {
  36205. var floatIndices = [];
  36206. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  36207. var matricesIndex = parsedGeometry.matricesIndices[i];
  36208. floatIndices.push(matricesIndex & 0x000000FF);
  36209. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  36210. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  36211. floatIndices.push(matricesIndex >> 24);
  36212. }
  36213. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  36214. }
  36215. else {
  36216. delete parsedGeometry.matricesIndices._isExpanded;
  36217. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  36218. }
  36219. }
  36220. if (parsedGeometry.matricesIndicesExtra) {
  36221. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  36222. var floatIndices = [];
  36223. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  36224. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  36225. floatIndices.push(matricesIndex & 0x000000FF);
  36226. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  36227. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  36228. floatIndices.push(matricesIndex >> 24);
  36229. }
  36230. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  36231. }
  36232. else {
  36233. delete parsedGeometry.matricesIndices._isExpanded;
  36234. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  36235. }
  36236. }
  36237. if (parsedGeometry.matricesWeights) {
  36238. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  36239. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  36240. }
  36241. if (parsedGeometry.matricesWeightsExtra) {
  36242. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  36243. }
  36244. mesh.setIndices(parsedGeometry.indices, null);
  36245. }
  36246. // SubMeshes
  36247. if (parsedGeometry.subMeshes) {
  36248. mesh.subMeshes = [];
  36249. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  36250. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  36251. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  36252. }
  36253. }
  36254. // Flat shading
  36255. if (mesh._shouldGenerateFlatShading) {
  36256. mesh.convertToFlatShadedMesh();
  36257. delete mesh._shouldGenerateFlatShading;
  36258. }
  36259. // Update
  36260. mesh.computeWorldMatrix(true);
  36261. // Octree
  36262. var sceneOctree = scene.selectionOctree;
  36263. if (sceneOctree !== undefined && sceneOctree !== null) {
  36264. sceneOctree.addMesh(mesh);
  36265. }
  36266. };
  36267. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  36268. var epsilon = 1e-3;
  36269. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  36270. return;
  36271. }
  36272. var noInfluenceBoneIndex = 0.0;
  36273. if (parsedGeometry.skeletonId > -1) {
  36274. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  36275. if (!skeleton) {
  36276. return;
  36277. }
  36278. noInfluenceBoneIndex = skeleton.bones.length;
  36279. }
  36280. else {
  36281. return;
  36282. }
  36283. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  36284. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  36285. var matricesWeights = parsedGeometry.matricesWeights;
  36286. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  36287. var influencers = parsedGeometry.numBoneInfluencer;
  36288. var size = matricesWeights.length;
  36289. for (var i = 0; i < size; i += 4) {
  36290. var weight = 0.0;
  36291. var firstZeroWeight = -1;
  36292. for (var j = 0; j < 4; j++) {
  36293. var w = matricesWeights[i + j];
  36294. weight += w;
  36295. if (w < epsilon && firstZeroWeight < 0) {
  36296. firstZeroWeight = j;
  36297. }
  36298. }
  36299. if (matricesWeightsExtra) {
  36300. for (var j = 0; j < 4; j++) {
  36301. var w = matricesWeightsExtra[i + j];
  36302. weight += w;
  36303. if (w < epsilon && firstZeroWeight < 0) {
  36304. firstZeroWeight = j + 4;
  36305. }
  36306. }
  36307. }
  36308. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  36309. firstZeroWeight = influencers - 1;
  36310. }
  36311. if (weight > epsilon) {
  36312. var mweight = 1.0 / weight;
  36313. for (var j = 0; j < 4; j++) {
  36314. matricesWeights[i + j] *= mweight;
  36315. }
  36316. if (matricesWeightsExtra) {
  36317. for (var j = 0; j < 4; j++) {
  36318. matricesWeightsExtra[i + j] *= mweight;
  36319. }
  36320. }
  36321. }
  36322. else {
  36323. if (firstZeroWeight >= 4) {
  36324. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  36325. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  36326. }
  36327. else {
  36328. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  36329. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  36330. }
  36331. }
  36332. }
  36333. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  36334. if (parsedGeometry.matricesWeightsExtra) {
  36335. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  36336. }
  36337. };
  36338. /**
  36339. * Create a new geometry from persisted data (Using .babylon file format)
  36340. * @param parsedVertexData defines the persisted data
  36341. * @param scene defines the hosting scene
  36342. * @param rootUrl defines the root url to use to load assets (like delayed data)
  36343. * @returns the new geometry object
  36344. */
  36345. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  36346. if (scene.getGeometryByID(parsedVertexData.id)) {
  36347. return null; // null since geometry could be something else than a box...
  36348. }
  36349. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  36350. if (BABYLON.Tags) {
  36351. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  36352. }
  36353. if (parsedVertexData.delayLoadingFile) {
  36354. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  36355. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  36356. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  36357. geometry._delayInfo = [];
  36358. if (parsedVertexData.hasUVs) {
  36359. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  36360. }
  36361. if (parsedVertexData.hasUVs2) {
  36362. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  36363. }
  36364. if (parsedVertexData.hasUVs3) {
  36365. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  36366. }
  36367. if (parsedVertexData.hasUVs4) {
  36368. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  36369. }
  36370. if (parsedVertexData.hasUVs5) {
  36371. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  36372. }
  36373. if (parsedVertexData.hasUVs6) {
  36374. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  36375. }
  36376. if (parsedVertexData.hasColors) {
  36377. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  36378. }
  36379. if (parsedVertexData.hasMatricesIndices) {
  36380. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  36381. }
  36382. if (parsedVertexData.hasMatricesWeights) {
  36383. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  36384. }
  36385. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  36386. }
  36387. else {
  36388. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  36389. }
  36390. scene.pushGeometry(geometry, true);
  36391. return geometry;
  36392. };
  36393. return Geometry;
  36394. }());
  36395. BABYLON.Geometry = Geometry;
  36396. // Primitives
  36397. /// Abstract class
  36398. /**
  36399. * Abstract class used to provide common services for all typed geometries
  36400. */
  36401. var _PrimitiveGeometry = /** @class */ (function (_super) {
  36402. __extends(_PrimitiveGeometry, _super);
  36403. /**
  36404. * Creates a new typed geometry
  36405. * @param id defines the unique ID of the geometry
  36406. * @param scene defines the hosting scene
  36407. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36408. * @param mesh defines the hosting mesh (can be null)
  36409. */
  36410. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  36411. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  36412. if (mesh === void 0) { mesh = null; }
  36413. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  36414. _this._canBeRegenerated = _canBeRegenerated;
  36415. _this._beingRegenerated = true;
  36416. _this.regenerate();
  36417. _this._beingRegenerated = false;
  36418. return _this;
  36419. }
  36420. /**
  36421. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  36422. * @returns true if the geometry can be regenerated
  36423. */
  36424. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  36425. return this._canBeRegenerated;
  36426. };
  36427. /**
  36428. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  36429. */
  36430. _PrimitiveGeometry.prototype.regenerate = function () {
  36431. if (!this._canBeRegenerated) {
  36432. return;
  36433. }
  36434. this._beingRegenerated = true;
  36435. this.setAllVerticesData(this._regenerateVertexData(), false);
  36436. this._beingRegenerated = false;
  36437. };
  36438. /**
  36439. * Clone the geometry
  36440. * @param id defines the unique ID of the new geometry
  36441. * @returns the new geometry
  36442. */
  36443. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  36444. return _super.prototype.copy.call(this, id);
  36445. };
  36446. // overrides
  36447. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  36448. if (!this._beingRegenerated) {
  36449. return;
  36450. }
  36451. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  36452. };
  36453. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  36454. if (!this._beingRegenerated) {
  36455. return;
  36456. }
  36457. _super.prototype.setVerticesData.call(this, kind, data, false);
  36458. };
  36459. // to override
  36460. /** @ignore */
  36461. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  36462. throw new Error("Abstract method");
  36463. };
  36464. _PrimitiveGeometry.prototype.copy = function (id) {
  36465. throw new Error("Must be overriden in sub-classes.");
  36466. };
  36467. _PrimitiveGeometry.prototype.serialize = function () {
  36468. var serializationObject = _super.prototype.serialize.call(this);
  36469. serializationObject.canBeRegenerated = this.canBeRegenerated();
  36470. return serializationObject;
  36471. };
  36472. return _PrimitiveGeometry;
  36473. }(Geometry));
  36474. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  36475. /**
  36476. * Creates a ribbon geometry
  36477. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  36478. */
  36479. var RibbonGeometry = /** @class */ (function (_super) {
  36480. __extends(RibbonGeometry, _super);
  36481. /**
  36482. * Creates a ribbon geometry
  36483. * @param id defines the unique ID of the geometry
  36484. * @param scene defines the hosting scene
  36485. * @param pathArray defines the array of paths to use
  36486. * @param closeArray defines if the last path and the first path must be joined
  36487. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  36488. * @param offset defines the offset between points
  36489. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36490. * @param mesh defines the hosting mesh (can be null)
  36491. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36492. */
  36493. function RibbonGeometry(id, scene,
  36494. /**
  36495. * Defines the array of paths to use
  36496. */
  36497. pathArray,
  36498. /**
  36499. * Defines if the last and first points of each path in your pathArray must be joined
  36500. */
  36501. closeArray,
  36502. /**
  36503. * Defines if the last and first points of each path in your pathArray must be joined
  36504. */
  36505. closePath,
  36506. /**
  36507. * Defines the offset between points
  36508. */
  36509. offset, canBeRegenerated, mesh,
  36510. /**
  36511. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36512. */
  36513. side) {
  36514. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36515. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36516. _this.pathArray = pathArray;
  36517. _this.closeArray = closeArray;
  36518. _this.closePath = closePath;
  36519. _this.offset = offset;
  36520. _this.side = side;
  36521. return _this;
  36522. }
  36523. /** @ignore */
  36524. RibbonGeometry.prototype._regenerateVertexData = function () {
  36525. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  36526. };
  36527. RibbonGeometry.prototype.copy = function (id) {
  36528. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  36529. };
  36530. return RibbonGeometry;
  36531. }(_PrimitiveGeometry));
  36532. BABYLON.RibbonGeometry = RibbonGeometry;
  36533. /**
  36534. * Creates a box geometry
  36535. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  36536. */
  36537. var BoxGeometry = /** @class */ (function (_super) {
  36538. __extends(BoxGeometry, _super);
  36539. /**
  36540. * Creates a box geometry
  36541. * @param id defines the unique ID of the geometry
  36542. * @param scene defines the hosting scene
  36543. * @param size defines the zise of the box (width, height and depth are the same)
  36544. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36545. * @param mesh defines the hosting mesh (can be null)
  36546. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36547. */
  36548. function BoxGeometry(id, scene,
  36549. /**
  36550. * Defines the zise of the box (width, height and depth are the same)
  36551. */
  36552. size, canBeRegenerated, mesh,
  36553. /**
  36554. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36555. */
  36556. side) {
  36557. if (mesh === void 0) { mesh = null; }
  36558. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36559. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36560. _this.size = size;
  36561. _this.side = side;
  36562. return _this;
  36563. }
  36564. BoxGeometry.prototype._regenerateVertexData = function () {
  36565. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  36566. };
  36567. BoxGeometry.prototype.copy = function (id) {
  36568. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  36569. };
  36570. BoxGeometry.prototype.serialize = function () {
  36571. var serializationObject = _super.prototype.serialize.call(this);
  36572. serializationObject.size = this.size;
  36573. return serializationObject;
  36574. };
  36575. BoxGeometry.Parse = function (parsedBox, scene) {
  36576. if (scene.getGeometryByID(parsedBox.id)) {
  36577. return null; // null since geometry could be something else than a box...
  36578. }
  36579. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  36580. if (BABYLON.Tags) {
  36581. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  36582. }
  36583. scene.pushGeometry(box, true);
  36584. return box;
  36585. };
  36586. return BoxGeometry;
  36587. }(_PrimitiveGeometry));
  36588. BABYLON.BoxGeometry = BoxGeometry;
  36589. /**
  36590. * Creates a sphere geometry
  36591. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  36592. */
  36593. var SphereGeometry = /** @class */ (function (_super) {
  36594. __extends(SphereGeometry, _super);
  36595. /**
  36596. * Create a new sphere geometry
  36597. * @param id defines the unique ID of the geometry
  36598. * @param scene defines the hosting scene
  36599. * @param segments defines the number of segments to use to create the sphere
  36600. * @param diameter defines the diameter of the sphere
  36601. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36602. * @param mesh defines the hosting mesh (can be null)
  36603. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36604. */
  36605. function SphereGeometry(id, scene,
  36606. /**
  36607. * Defines the number of segments to use to create the sphere
  36608. */
  36609. segments,
  36610. /**
  36611. * Defines the diameter of the sphere
  36612. */
  36613. diameter, canBeRegenerated, mesh,
  36614. /**
  36615. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36616. */
  36617. side) {
  36618. if (mesh === void 0) { mesh = null; }
  36619. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36620. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36621. _this.segments = segments;
  36622. _this.diameter = diameter;
  36623. _this.side = side;
  36624. return _this;
  36625. }
  36626. SphereGeometry.prototype._regenerateVertexData = function () {
  36627. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  36628. };
  36629. SphereGeometry.prototype.copy = function (id) {
  36630. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  36631. };
  36632. SphereGeometry.prototype.serialize = function () {
  36633. var serializationObject = _super.prototype.serialize.call(this);
  36634. serializationObject.segments = this.segments;
  36635. serializationObject.diameter = this.diameter;
  36636. return serializationObject;
  36637. };
  36638. SphereGeometry.Parse = function (parsedSphere, scene) {
  36639. if (scene.getGeometryByID(parsedSphere.id)) {
  36640. return null; // null since geometry could be something else than a sphere...
  36641. }
  36642. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  36643. if (BABYLON.Tags) {
  36644. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  36645. }
  36646. scene.pushGeometry(sphere, true);
  36647. return sphere;
  36648. };
  36649. return SphereGeometry;
  36650. }(_PrimitiveGeometry));
  36651. BABYLON.SphereGeometry = SphereGeometry;
  36652. /**
  36653. * Creates a disc geometry
  36654. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  36655. */
  36656. var DiscGeometry = /** @class */ (function (_super) {
  36657. __extends(DiscGeometry, _super);
  36658. /**
  36659. * Creates a new disc geometry
  36660. * @param id defines the unique ID of the geometry
  36661. * @param scene defines the hosting scene
  36662. * @param radius defines the radius of the disc
  36663. * @param tessellation defines the tesselation factor to apply to the disc
  36664. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36665. * @param mesh defines the hosting mesh (can be null)
  36666. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36667. */
  36668. function DiscGeometry(id, scene,
  36669. /**
  36670. * Defines the radius of the disc
  36671. */
  36672. radius,
  36673. /**
  36674. * Defines the tesselation factor to apply to the disc
  36675. */
  36676. tessellation, canBeRegenerated, mesh,
  36677. /**
  36678. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36679. */
  36680. side) {
  36681. if (mesh === void 0) { mesh = null; }
  36682. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36683. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36684. _this.radius = radius;
  36685. _this.tessellation = tessellation;
  36686. _this.side = side;
  36687. return _this;
  36688. }
  36689. DiscGeometry.prototype._regenerateVertexData = function () {
  36690. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  36691. };
  36692. DiscGeometry.prototype.copy = function (id) {
  36693. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  36694. };
  36695. return DiscGeometry;
  36696. }(_PrimitiveGeometry));
  36697. BABYLON.DiscGeometry = DiscGeometry;
  36698. /**
  36699. * Creates a new cylinder geometry
  36700. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  36701. */
  36702. var CylinderGeometry = /** @class */ (function (_super) {
  36703. __extends(CylinderGeometry, _super);
  36704. /**
  36705. * Creates a new cylinder geometry
  36706. * @param id defines the unique ID of the geometry
  36707. * @param scene defines the hosting scene
  36708. * @param height defines the height of the cylinder
  36709. * @param diameterTop defines the diameter of the cylinder's top cap
  36710. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  36711. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  36712. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  36713. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36714. * @param mesh defines the hosting mesh (can be null)
  36715. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36716. */
  36717. function CylinderGeometry(id, scene,
  36718. /**
  36719. * Defines the height of the cylinder
  36720. */
  36721. height,
  36722. /**
  36723. * Defines the diameter of the cylinder's top cap
  36724. */
  36725. diameterTop,
  36726. /**
  36727. * Defines the diameter of the cylinder's bottom cap
  36728. */
  36729. diameterBottom,
  36730. /**
  36731. * Defines the tessellation factor to apply to the cylinder
  36732. */
  36733. tessellation,
  36734. /**
  36735. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  36736. */
  36737. subdivisions, canBeRegenerated, mesh,
  36738. /**
  36739. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36740. */
  36741. side) {
  36742. if (subdivisions === void 0) { subdivisions = 1; }
  36743. if (mesh === void 0) { mesh = null; }
  36744. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36745. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36746. _this.height = height;
  36747. _this.diameterTop = diameterTop;
  36748. _this.diameterBottom = diameterBottom;
  36749. _this.tessellation = tessellation;
  36750. _this.subdivisions = subdivisions;
  36751. _this.side = side;
  36752. return _this;
  36753. }
  36754. CylinderGeometry.prototype._regenerateVertexData = function () {
  36755. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  36756. };
  36757. CylinderGeometry.prototype.copy = function (id) {
  36758. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  36759. };
  36760. CylinderGeometry.prototype.serialize = function () {
  36761. var serializationObject = _super.prototype.serialize.call(this);
  36762. serializationObject.height = this.height;
  36763. serializationObject.diameterTop = this.diameterTop;
  36764. serializationObject.diameterBottom = this.diameterBottom;
  36765. serializationObject.tessellation = this.tessellation;
  36766. return serializationObject;
  36767. };
  36768. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  36769. if (scene.getGeometryByID(parsedCylinder.id)) {
  36770. return null; // null since geometry could be something else than a cylinder...
  36771. }
  36772. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  36773. if (BABYLON.Tags) {
  36774. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  36775. }
  36776. scene.pushGeometry(cylinder, true);
  36777. return cylinder;
  36778. };
  36779. return CylinderGeometry;
  36780. }(_PrimitiveGeometry));
  36781. BABYLON.CylinderGeometry = CylinderGeometry;
  36782. /**
  36783. * Creates a new torus geometry
  36784. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  36785. */
  36786. var TorusGeometry = /** @class */ (function (_super) {
  36787. __extends(TorusGeometry, _super);
  36788. /**
  36789. * Creates a new torus geometry
  36790. * @param id defines the unique ID of the geometry
  36791. * @param scene defines the hosting scene
  36792. * @param diameter defines the diameter of the torus
  36793. * @param thickness defines the thickness of the torus (ie. internal diameter)
  36794. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  36795. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36796. * @param mesh defines the hosting mesh (can be null)
  36797. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36798. */
  36799. function TorusGeometry(id, scene,
  36800. /**
  36801. * Defines the diameter of the torus
  36802. */
  36803. diameter,
  36804. /**
  36805. * Defines the thickness of the torus (ie. internal diameter)
  36806. */
  36807. thickness,
  36808. /**
  36809. * Defines the tesselation factor to apply to the torus
  36810. */
  36811. tessellation, canBeRegenerated, mesh,
  36812. /**
  36813. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36814. */
  36815. side) {
  36816. if (mesh === void 0) { mesh = null; }
  36817. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36818. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36819. _this.diameter = diameter;
  36820. _this.thickness = thickness;
  36821. _this.tessellation = tessellation;
  36822. _this.side = side;
  36823. return _this;
  36824. }
  36825. TorusGeometry.prototype._regenerateVertexData = function () {
  36826. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  36827. };
  36828. TorusGeometry.prototype.copy = function (id) {
  36829. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  36830. };
  36831. TorusGeometry.prototype.serialize = function () {
  36832. var serializationObject = _super.prototype.serialize.call(this);
  36833. serializationObject.diameter = this.diameter;
  36834. serializationObject.thickness = this.thickness;
  36835. serializationObject.tessellation = this.tessellation;
  36836. return serializationObject;
  36837. };
  36838. TorusGeometry.Parse = function (parsedTorus, scene) {
  36839. if (scene.getGeometryByID(parsedTorus.id)) {
  36840. return null; // null since geometry could be something else than a torus...
  36841. }
  36842. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  36843. if (BABYLON.Tags) {
  36844. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  36845. }
  36846. scene.pushGeometry(torus, true);
  36847. return torus;
  36848. };
  36849. return TorusGeometry;
  36850. }(_PrimitiveGeometry));
  36851. BABYLON.TorusGeometry = TorusGeometry;
  36852. /**
  36853. * Creates a new ground geometry
  36854. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  36855. */
  36856. var GroundGeometry = /** @class */ (function (_super) {
  36857. __extends(GroundGeometry, _super);
  36858. /**
  36859. * Creates a new ground geometry
  36860. * @param id defines the unique ID of the geometry
  36861. * @param scene defines the hosting scene
  36862. * @param width defines the width of the ground
  36863. * @param height defines the height of the ground
  36864. * @param subdivisions defines the subdivisions to apply to the ground
  36865. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36866. * @param mesh defines the hosting mesh (can be null)
  36867. */
  36868. function GroundGeometry(id, scene,
  36869. /**
  36870. * Defines the width of the ground
  36871. */
  36872. width,
  36873. /**
  36874. * Defines the height of the ground
  36875. */
  36876. height,
  36877. /**
  36878. * Defines the subdivisions to apply to the ground
  36879. */
  36880. subdivisions, canBeRegenerated, mesh) {
  36881. if (mesh === void 0) { mesh = null; }
  36882. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36883. _this.width = width;
  36884. _this.height = height;
  36885. _this.subdivisions = subdivisions;
  36886. return _this;
  36887. }
  36888. GroundGeometry.prototype._regenerateVertexData = function () {
  36889. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  36890. };
  36891. GroundGeometry.prototype.copy = function (id) {
  36892. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  36893. };
  36894. GroundGeometry.prototype.serialize = function () {
  36895. var serializationObject = _super.prototype.serialize.call(this);
  36896. serializationObject.width = this.width;
  36897. serializationObject.height = this.height;
  36898. serializationObject.subdivisions = this.subdivisions;
  36899. return serializationObject;
  36900. };
  36901. GroundGeometry.Parse = function (parsedGround, scene) {
  36902. if (scene.getGeometryByID(parsedGround.id)) {
  36903. return null; // null since geometry could be something else than a ground...
  36904. }
  36905. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  36906. if (BABYLON.Tags) {
  36907. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  36908. }
  36909. scene.pushGeometry(ground, true);
  36910. return ground;
  36911. };
  36912. return GroundGeometry;
  36913. }(_PrimitiveGeometry));
  36914. BABYLON.GroundGeometry = GroundGeometry;
  36915. /**
  36916. * Creates a tiled ground geometry
  36917. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  36918. */
  36919. var TiledGroundGeometry = /** @class */ (function (_super) {
  36920. __extends(TiledGroundGeometry, _super);
  36921. /**
  36922. * Creates a tiled ground geometry
  36923. * @param id defines the unique ID of the geometry
  36924. * @param scene defines the hosting scene
  36925. * @param xmin defines the minimum value on X axis
  36926. * @param zmin defines the minimum value on Z axis
  36927. * @param xmax defines the maximum value on X axis
  36928. * @param zmax defines the maximum value on Z axis
  36929. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  36930. * @param precision defines the precision to use when computing the tiles
  36931. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36932. * @param mesh defines the hosting mesh (can be null)
  36933. */
  36934. function TiledGroundGeometry(id, scene,
  36935. /**
  36936. * Defines the minimum value on X axis
  36937. */
  36938. xmin,
  36939. /**
  36940. * Defines the minimum value on Z axis
  36941. */
  36942. zmin,
  36943. /**
  36944. * Defines the maximum value on X axis
  36945. */
  36946. xmax,
  36947. /**
  36948. * Defines the maximum value on Z axis
  36949. */
  36950. zmax,
  36951. /**
  36952. * Defines the subdivisions to apply to the ground
  36953. */
  36954. subdivisions,
  36955. /**
  36956. * Defines the precision to use when computing the tiles
  36957. */
  36958. precision, canBeRegenerated, mesh) {
  36959. if (mesh === void 0) { mesh = null; }
  36960. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36961. _this.xmin = xmin;
  36962. _this.zmin = zmin;
  36963. _this.xmax = xmax;
  36964. _this.zmax = zmax;
  36965. _this.subdivisions = subdivisions;
  36966. _this.precision = precision;
  36967. return _this;
  36968. }
  36969. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  36970. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  36971. };
  36972. TiledGroundGeometry.prototype.copy = function (id) {
  36973. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  36974. };
  36975. return TiledGroundGeometry;
  36976. }(_PrimitiveGeometry));
  36977. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  36978. /**
  36979. * Creates a plane geometry
  36980. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  36981. */
  36982. var PlaneGeometry = /** @class */ (function (_super) {
  36983. __extends(PlaneGeometry, _super);
  36984. /**
  36985. * Creates a plane geometry
  36986. * @param id defines the unique ID of the geometry
  36987. * @param scene defines the hosting scene
  36988. * @param size defines the size of the plane (width === height)
  36989. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36990. * @param mesh defines the hosting mesh (can be null)
  36991. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36992. */
  36993. function PlaneGeometry(id, scene,
  36994. /**
  36995. * Defines the size of the plane (width === height)
  36996. */
  36997. size, canBeRegenerated, mesh,
  36998. /**
  36999. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  37000. */
  37001. side) {
  37002. if (mesh === void 0) { mesh = null; }
  37003. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  37004. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  37005. _this.size = size;
  37006. _this.side = side;
  37007. return _this;
  37008. }
  37009. PlaneGeometry.prototype._regenerateVertexData = function () {
  37010. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  37011. };
  37012. PlaneGeometry.prototype.copy = function (id) {
  37013. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  37014. };
  37015. PlaneGeometry.prototype.serialize = function () {
  37016. var serializationObject = _super.prototype.serialize.call(this);
  37017. serializationObject.size = this.size;
  37018. return serializationObject;
  37019. };
  37020. PlaneGeometry.Parse = function (parsedPlane, scene) {
  37021. if (scene.getGeometryByID(parsedPlane.id)) {
  37022. return null; // null since geometry could be something else than a ground...
  37023. }
  37024. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  37025. if (BABYLON.Tags) {
  37026. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  37027. }
  37028. scene.pushGeometry(plane, true);
  37029. return plane;
  37030. };
  37031. return PlaneGeometry;
  37032. }(_PrimitiveGeometry));
  37033. BABYLON.PlaneGeometry = PlaneGeometry;
  37034. /**
  37035. * Creates a torus knot geometry
  37036. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  37037. */
  37038. var TorusKnotGeometry = /** @class */ (function (_super) {
  37039. __extends(TorusKnotGeometry, _super);
  37040. /**
  37041. * Creates a torus knot geometry
  37042. * @param id defines the unique ID of the geometry
  37043. * @param scene defines the hosting scene
  37044. * @param radius defines the radius of the torus knot
  37045. * @param tube defines the thickness of the torus knot tube
  37046. * @param radialSegments defines the number of radial segments
  37047. * @param tubularSegments defines the number of tubular segments
  37048. * @param p defines the first number of windings
  37049. * @param q defines the second number of windings
  37050. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  37051. * @param mesh defines the hosting mesh (can be null)
  37052. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  37053. */
  37054. function TorusKnotGeometry(id, scene,
  37055. /**
  37056. * Defines the radius of the torus knot
  37057. */
  37058. radius,
  37059. /**
  37060. * Defines the thickness of the torus knot tube
  37061. */
  37062. tube,
  37063. /**
  37064. * Defines the number of radial segments
  37065. */
  37066. radialSegments,
  37067. /**
  37068. * Defines the number of tubular segments
  37069. */
  37070. tubularSegments,
  37071. /**
  37072. * Defines the first number of windings
  37073. */
  37074. p,
  37075. /**
  37076. * Defines the second number of windings
  37077. */
  37078. q, canBeRegenerated, mesh,
  37079. /**
  37080. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  37081. */
  37082. side) {
  37083. if (mesh === void 0) { mesh = null; }
  37084. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  37085. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  37086. _this.radius = radius;
  37087. _this.tube = tube;
  37088. _this.radialSegments = radialSegments;
  37089. _this.tubularSegments = tubularSegments;
  37090. _this.p = p;
  37091. _this.q = q;
  37092. _this.side = side;
  37093. return _this;
  37094. }
  37095. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  37096. 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 });
  37097. };
  37098. TorusKnotGeometry.prototype.copy = function (id) {
  37099. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  37100. };
  37101. TorusKnotGeometry.prototype.serialize = function () {
  37102. var serializationObject = _super.prototype.serialize.call(this);
  37103. serializationObject.radius = this.radius;
  37104. serializationObject.tube = this.tube;
  37105. serializationObject.radialSegments = this.radialSegments;
  37106. serializationObject.tubularSegments = this.tubularSegments;
  37107. serializationObject.p = this.p;
  37108. serializationObject.q = this.q;
  37109. return serializationObject;
  37110. };
  37111. ;
  37112. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  37113. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  37114. return null; // null since geometry could be something else than a ground...
  37115. }
  37116. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  37117. if (BABYLON.Tags) {
  37118. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  37119. }
  37120. scene.pushGeometry(torusKnot, true);
  37121. return torusKnot;
  37122. };
  37123. return TorusKnotGeometry;
  37124. }(_PrimitiveGeometry));
  37125. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  37126. //}
  37127. })(BABYLON || (BABYLON = {}));
  37128. //# sourceMappingURL=babylon.geometry.js.map
  37129. "use strict";
  37130. var BABYLON;
  37131. (function (BABYLON) {
  37132. /**
  37133. * PostProcessManager is used to manage one or more post processes or post process pipelines
  37134. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  37135. */
  37136. var PostProcessManager = /** @class */ (function () {
  37137. /**
  37138. * Creates a new instance of @see PostProcess
  37139. * @param scene The scene that the post process is associated with.
  37140. */
  37141. function PostProcessManager(scene) {
  37142. this._vertexBuffers = {};
  37143. this._scene = scene;
  37144. }
  37145. PostProcessManager.prototype._prepareBuffers = function () {
  37146. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  37147. return;
  37148. }
  37149. // VBO
  37150. var vertices = [];
  37151. vertices.push(1, 1);
  37152. vertices.push(-1, 1);
  37153. vertices.push(-1, -1);
  37154. vertices.push(1, -1);
  37155. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  37156. this._buildIndexBuffer();
  37157. };
  37158. PostProcessManager.prototype._buildIndexBuffer = function () {
  37159. // Indices
  37160. var indices = [];
  37161. indices.push(0);
  37162. indices.push(1);
  37163. indices.push(2);
  37164. indices.push(0);
  37165. indices.push(2);
  37166. indices.push(3);
  37167. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  37168. };
  37169. /**
  37170. * Rebuilds the vertex buffers of the manager.
  37171. */
  37172. PostProcessManager.prototype._rebuild = function () {
  37173. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  37174. if (!vb) {
  37175. return;
  37176. }
  37177. vb._rebuild();
  37178. this._buildIndexBuffer();
  37179. };
  37180. // Methods
  37181. /**
  37182. * Prepares a frame to be run through a post process.
  37183. * @param sourceTexture The input texture to the post procesess. (default: null)
  37184. * @param postProcesses An array of post processes to be run. (default: null)
  37185. * @returns True if the post processes were able to be run.
  37186. */
  37187. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  37188. if (sourceTexture === void 0) { sourceTexture = null; }
  37189. if (postProcesses === void 0) { postProcesses = null; }
  37190. var camera = this._scene.activeCamera;
  37191. if (!camera) {
  37192. return false;
  37193. }
  37194. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  37195. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  37196. return false;
  37197. }
  37198. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  37199. return true;
  37200. };
  37201. /**
  37202. * Manually render a set of post processes to a texture.
  37203. * @param postProcesses An array of post processes to be run.
  37204. * @param targetTexture The target texture to render to.
  37205. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  37206. */
  37207. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  37208. if (targetTexture === void 0) { targetTexture = null; }
  37209. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  37210. var engine = this._scene.getEngine();
  37211. for (var index = 0; index < postProcesses.length; index++) {
  37212. if (index < postProcesses.length - 1) {
  37213. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  37214. }
  37215. else {
  37216. if (targetTexture) {
  37217. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  37218. }
  37219. else {
  37220. engine.restoreDefaultFramebuffer();
  37221. }
  37222. }
  37223. var pp = postProcesses[index];
  37224. var effect = pp.apply();
  37225. if (effect) {
  37226. pp.onBeforeRenderObservable.notifyObservers(effect);
  37227. // VBOs
  37228. this._prepareBuffers();
  37229. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  37230. // Draw order
  37231. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  37232. pp.onAfterRenderObservable.notifyObservers(effect);
  37233. }
  37234. }
  37235. // Restore depth buffer
  37236. engine.setDepthBuffer(true);
  37237. engine.setDepthWrite(true);
  37238. };
  37239. /**
  37240. * Finalize the result of the output of the postprocesses.
  37241. * @param doNotPresent If true the result will not be displayed to the screen.
  37242. * @param targetTexture The target texture to render to.
  37243. * @param faceIndex The index of the face to bind the target texture to.
  37244. * @param postProcesses The array of post processes to render.
  37245. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  37246. */
  37247. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  37248. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  37249. var camera = this._scene.activeCamera;
  37250. if (!camera) {
  37251. return;
  37252. }
  37253. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  37254. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  37255. return;
  37256. }
  37257. var engine = this._scene.getEngine();
  37258. for (var index = 0, len = postProcesses.length; index < len; index++) {
  37259. var pp = postProcesses[index];
  37260. if (index < len - 1) {
  37261. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  37262. }
  37263. else {
  37264. if (targetTexture) {
  37265. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  37266. }
  37267. else {
  37268. engine.restoreDefaultFramebuffer();
  37269. }
  37270. }
  37271. if (doNotPresent) {
  37272. break;
  37273. }
  37274. var effect = pp.apply();
  37275. if (effect) {
  37276. pp.onBeforeRenderObservable.notifyObservers(effect);
  37277. // VBOs
  37278. this._prepareBuffers();
  37279. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  37280. // Draw order
  37281. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  37282. pp.onAfterRenderObservable.notifyObservers(effect);
  37283. }
  37284. }
  37285. // Restore states
  37286. engine.setDepthBuffer(true);
  37287. engine.setDepthWrite(true);
  37288. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  37289. };
  37290. /**
  37291. * Disposes of the post process manager.
  37292. */
  37293. PostProcessManager.prototype.dispose = function () {
  37294. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  37295. if (buffer) {
  37296. buffer.dispose();
  37297. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  37298. }
  37299. if (this._indexBuffer) {
  37300. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  37301. this._indexBuffer = null;
  37302. }
  37303. };
  37304. return PostProcessManager;
  37305. }());
  37306. BABYLON.PostProcessManager = PostProcessManager;
  37307. })(BABYLON || (BABYLON = {}));
  37308. //# sourceMappingURL=babylon.postProcessManager.js.map
  37309. "use strict";
  37310. var BABYLON;
  37311. (function (BABYLON) {
  37312. /**
  37313. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  37314. */
  37315. var PerformanceMonitor = /** @class */ (function () {
  37316. /**
  37317. * constructor
  37318. * @param frameSampleSize The number of samples required to saturate the sliding window
  37319. */
  37320. function PerformanceMonitor(frameSampleSize) {
  37321. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  37322. this._enabled = true;
  37323. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  37324. }
  37325. /**
  37326. * Samples current frame
  37327. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  37328. */
  37329. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  37330. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  37331. if (!this._enabled)
  37332. return;
  37333. if (this._lastFrameTimeMs != null) {
  37334. var dt = timeMs - this._lastFrameTimeMs;
  37335. this._rollingFrameTime.add(dt);
  37336. }
  37337. this._lastFrameTimeMs = timeMs;
  37338. };
  37339. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  37340. /**
  37341. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  37342. * @return Average frame time in milliseconds
  37343. */
  37344. get: function () {
  37345. return this._rollingFrameTime.average;
  37346. },
  37347. enumerable: true,
  37348. configurable: true
  37349. });
  37350. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  37351. /**
  37352. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  37353. * @return Frame time variance in milliseconds squared
  37354. */
  37355. get: function () {
  37356. return this._rollingFrameTime.variance;
  37357. },
  37358. enumerable: true,
  37359. configurable: true
  37360. });
  37361. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  37362. /**
  37363. * Returns the frame time of the most recent frame
  37364. * @return Frame time in milliseconds
  37365. */
  37366. get: function () {
  37367. return this._rollingFrameTime.history(0);
  37368. },
  37369. enumerable: true,
  37370. configurable: true
  37371. });
  37372. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  37373. /**
  37374. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  37375. * @return Framerate in frames per second
  37376. */
  37377. get: function () {
  37378. return 1000.0 / this._rollingFrameTime.average;
  37379. },
  37380. enumerable: true,
  37381. configurable: true
  37382. });
  37383. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  37384. /**
  37385. * Returns the average framerate in frames per second using the most recent frame time
  37386. * @return Framerate in frames per second
  37387. */
  37388. get: function () {
  37389. var history = this._rollingFrameTime.history(0);
  37390. if (history === 0) {
  37391. return 0;
  37392. }
  37393. return 1000.0 / history;
  37394. },
  37395. enumerable: true,
  37396. configurable: true
  37397. });
  37398. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  37399. /**
  37400. * Returns true if enough samples have been taken to completely fill the sliding window
  37401. * @return true if saturated
  37402. */
  37403. get: function () {
  37404. return this._rollingFrameTime.isSaturated();
  37405. },
  37406. enumerable: true,
  37407. configurable: true
  37408. });
  37409. /**
  37410. * Enables contributions to the sliding window sample set
  37411. */
  37412. PerformanceMonitor.prototype.enable = function () {
  37413. this._enabled = true;
  37414. };
  37415. /**
  37416. * Disables contributions to the sliding window sample set
  37417. * Samples will not be interpolated over the disabled period
  37418. */
  37419. PerformanceMonitor.prototype.disable = function () {
  37420. this._enabled = false;
  37421. //clear last sample to avoid interpolating over the disabled period when next enabled
  37422. this._lastFrameTimeMs = null;
  37423. };
  37424. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  37425. /**
  37426. * Returns true if sampling is enabled
  37427. * @return true if enabled
  37428. */
  37429. get: function () {
  37430. return this._enabled;
  37431. },
  37432. enumerable: true,
  37433. configurable: true
  37434. });
  37435. /**
  37436. * Resets performance monitor
  37437. */
  37438. PerformanceMonitor.prototype.reset = function () {
  37439. //clear last sample to avoid interpolating over the disabled period when next enabled
  37440. this._lastFrameTimeMs = null;
  37441. //wipe record
  37442. this._rollingFrameTime.reset();
  37443. };
  37444. return PerformanceMonitor;
  37445. }());
  37446. BABYLON.PerformanceMonitor = PerformanceMonitor;
  37447. /**
  37448. * RollingAverage
  37449. *
  37450. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  37451. */
  37452. var RollingAverage = /** @class */ (function () {
  37453. /**
  37454. * constructor
  37455. * @param length The number of samples required to saturate the sliding window
  37456. */
  37457. function RollingAverage(length) {
  37458. this._samples = new Array(length);
  37459. this.reset();
  37460. }
  37461. /**
  37462. * Adds a sample to the sample set
  37463. * @param v The sample value
  37464. */
  37465. RollingAverage.prototype.add = function (v) {
  37466. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  37467. var delta;
  37468. //we need to check if we've already wrapped round
  37469. if (this.isSaturated()) {
  37470. //remove bottom of stack from mean
  37471. var bottomValue = this._samples[this._pos];
  37472. delta = bottomValue - this.average;
  37473. this.average -= delta / (this._sampleCount - 1);
  37474. this._m2 -= delta * (bottomValue - this.average);
  37475. }
  37476. else {
  37477. this._sampleCount++;
  37478. }
  37479. //add new value to mean
  37480. delta = v - this.average;
  37481. this.average += delta / (this._sampleCount);
  37482. this._m2 += delta * (v - this.average);
  37483. //set the new variance
  37484. this.variance = this._m2 / (this._sampleCount - 1);
  37485. this._samples[this._pos] = v;
  37486. this._pos++;
  37487. this._pos %= this._samples.length; //positive wrap around
  37488. };
  37489. /**
  37490. * Returns previously added values or null if outside of history or outside the sliding window domain
  37491. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  37492. * @return Value previously recorded with add() or null if outside of range
  37493. */
  37494. RollingAverage.prototype.history = function (i) {
  37495. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  37496. return 0;
  37497. }
  37498. var i0 = this._wrapPosition(this._pos - 1.0);
  37499. return this._samples[this._wrapPosition(i0 - i)];
  37500. };
  37501. /**
  37502. * Returns true if enough samples have been taken to completely fill the sliding window
  37503. * @return true if sample-set saturated
  37504. */
  37505. RollingAverage.prototype.isSaturated = function () {
  37506. return this._sampleCount >= this._samples.length;
  37507. };
  37508. /**
  37509. * Resets the rolling average (equivalent to 0 samples taken so far)
  37510. */
  37511. RollingAverage.prototype.reset = function () {
  37512. this.average = 0;
  37513. this.variance = 0;
  37514. this._sampleCount = 0;
  37515. this._pos = 0;
  37516. this._m2 = 0;
  37517. };
  37518. /**
  37519. * Wraps a value around the sample range boundaries
  37520. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  37521. * @return Wrapped position in sample range
  37522. */
  37523. RollingAverage.prototype._wrapPosition = function (i) {
  37524. var max = this._samples.length;
  37525. return ((i % max) + max) % max;
  37526. };
  37527. return RollingAverage;
  37528. }());
  37529. BABYLON.RollingAverage = RollingAverage;
  37530. })(BABYLON || (BABYLON = {}));
  37531. //# sourceMappingURL=babylon.performanceMonitor.js.map
  37532. "use strict";
  37533. var BABYLON;
  37534. (function (BABYLON) {
  37535. /**
  37536. * This groups together the common properties used for image processing either in direct forward pass
  37537. * or through post processing effect depending on the use of the image processing pipeline in your scene
  37538. * or not.
  37539. */
  37540. var ImageProcessingConfiguration = /** @class */ (function () {
  37541. function ImageProcessingConfiguration() {
  37542. /**
  37543. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  37544. */
  37545. this.colorCurves = new BABYLON.ColorCurves();
  37546. this._colorCurvesEnabled = false;
  37547. this._colorGradingEnabled = false;
  37548. this._colorGradingWithGreenDepth = true;
  37549. this._colorGradingBGR = true;
  37550. this._exposure = 1.0;
  37551. this._toneMappingEnabled = false;
  37552. this._contrast = 1.0;
  37553. /**
  37554. * Vignette stretch size.
  37555. */
  37556. this.vignetteStretch = 0;
  37557. /**
  37558. * Vignette centre X Offset.
  37559. */
  37560. this.vignetteCentreX = 0;
  37561. /**
  37562. * Vignette centre Y Offset.
  37563. */
  37564. this.vignetteCentreY = 0;
  37565. /**
  37566. * Vignette weight or intensity of the vignette effect.
  37567. */
  37568. this.vignetteWeight = 1.5;
  37569. /**
  37570. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  37571. * if vignetteEnabled is set to true.
  37572. */
  37573. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  37574. /**
  37575. * Camera field of view used by the Vignette effect.
  37576. */
  37577. this.vignetteCameraFov = 0.5;
  37578. this._grainEnabled = false;
  37579. this._grainIntensity = 30;
  37580. this._grainAnimated = false;
  37581. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  37582. this._vignetteEnabled = false;
  37583. this._applyByPostProcess = false;
  37584. this._isEnabled = true;
  37585. /**
  37586. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  37587. * @type {BABYLON.Observable}
  37588. */
  37589. this.onUpdateParameters = new BABYLON.Observable();
  37590. }
  37591. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  37592. /**
  37593. * Gets wether the color curves effect is enabled.
  37594. */
  37595. get: function () {
  37596. return this._colorCurvesEnabled;
  37597. },
  37598. /**
  37599. * Sets wether the color curves effect is enabled.
  37600. */
  37601. set: function (value) {
  37602. if (this._colorCurvesEnabled === value) {
  37603. return;
  37604. }
  37605. this._colorCurvesEnabled = value;
  37606. this._updateParameters();
  37607. },
  37608. enumerable: true,
  37609. configurable: true
  37610. });
  37611. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  37612. /**
  37613. * Gets wether the color grading effect is enabled.
  37614. */
  37615. get: function () {
  37616. return this._colorGradingEnabled;
  37617. },
  37618. /**
  37619. * Sets wether the color grading effect is enabled.
  37620. */
  37621. set: function (value) {
  37622. if (this._colorGradingEnabled === value) {
  37623. return;
  37624. }
  37625. this._colorGradingEnabled = value;
  37626. this._updateParameters();
  37627. },
  37628. enumerable: true,
  37629. configurable: true
  37630. });
  37631. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  37632. /**
  37633. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  37634. */
  37635. get: function () {
  37636. return this._colorGradingWithGreenDepth;
  37637. },
  37638. /**
  37639. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  37640. */
  37641. set: function (value) {
  37642. if (this._colorGradingWithGreenDepth === value) {
  37643. return;
  37644. }
  37645. this._colorGradingWithGreenDepth = value;
  37646. this._updateParameters();
  37647. },
  37648. enumerable: true,
  37649. configurable: true
  37650. });
  37651. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  37652. /**
  37653. * Gets wether the color grading texture contains BGR values.
  37654. */
  37655. get: function () {
  37656. return this._colorGradingBGR;
  37657. },
  37658. /**
  37659. * Sets wether the color grading texture contains BGR values.
  37660. */
  37661. set: function (value) {
  37662. if (this._colorGradingBGR === value) {
  37663. return;
  37664. }
  37665. this._colorGradingBGR = value;
  37666. this._updateParameters();
  37667. },
  37668. enumerable: true,
  37669. configurable: true
  37670. });
  37671. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  37672. /**
  37673. * Gets the Exposure used in the effect.
  37674. */
  37675. get: function () {
  37676. return this._exposure;
  37677. },
  37678. /**
  37679. * Sets the Exposure used in the effect.
  37680. */
  37681. set: function (value) {
  37682. if (this._exposure === value) {
  37683. return;
  37684. }
  37685. this._exposure = value;
  37686. this._updateParameters();
  37687. },
  37688. enumerable: true,
  37689. configurable: true
  37690. });
  37691. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  37692. /**
  37693. * Gets wether the tone mapping effect is enabled.
  37694. */
  37695. get: function () {
  37696. return this._toneMappingEnabled;
  37697. },
  37698. /**
  37699. * Sets wether the tone mapping effect is enabled.
  37700. */
  37701. set: function (value) {
  37702. if (this._toneMappingEnabled === value) {
  37703. return;
  37704. }
  37705. this._toneMappingEnabled = value;
  37706. this._updateParameters();
  37707. },
  37708. enumerable: true,
  37709. configurable: true
  37710. });
  37711. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  37712. /**
  37713. * Gets the contrast used in the effect.
  37714. */
  37715. get: function () {
  37716. return this._contrast;
  37717. },
  37718. /**
  37719. * Sets the contrast used in the effect.
  37720. */
  37721. set: function (value) {
  37722. if (this._contrast === value) {
  37723. return;
  37724. }
  37725. this._contrast = value;
  37726. this._updateParameters();
  37727. },
  37728. enumerable: true,
  37729. configurable: true
  37730. });
  37731. Object.defineProperty(ImageProcessingConfiguration.prototype, "grainEnabled", {
  37732. /**
  37733. * If the grain effect should be enabled.
  37734. */
  37735. get: function () {
  37736. return this._grainEnabled;
  37737. },
  37738. set: function (value) {
  37739. if (this._grainEnabled === value) {
  37740. return;
  37741. }
  37742. this._grainEnabled = value;
  37743. this._updateParameters();
  37744. },
  37745. enumerable: true,
  37746. configurable: true
  37747. });
  37748. Object.defineProperty(ImageProcessingConfiguration.prototype, "grainIntensity", {
  37749. /**
  37750. * Amount of grain to be applied by the grain effect.
  37751. */
  37752. get: function () {
  37753. return this._grainIntensity;
  37754. },
  37755. set: function (value) {
  37756. if (this._grainIntensity === value) {
  37757. return;
  37758. }
  37759. this._grainIntensity = value;
  37760. },
  37761. enumerable: true,
  37762. configurable: true
  37763. });
  37764. Object.defineProperty(ImageProcessingConfiguration.prototype, "grainAnimated", {
  37765. /**
  37766. * If the grain effect should be animated.
  37767. */
  37768. get: function () {
  37769. return this._grainAnimated;
  37770. },
  37771. set: function (value) {
  37772. if (this._grainAnimated === value) {
  37773. return;
  37774. }
  37775. this._grainAnimated = value;
  37776. this._updateParameters();
  37777. },
  37778. enumerable: true,
  37779. configurable: true
  37780. });
  37781. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  37782. /**
  37783. * Gets the vignette blend mode allowing different kind of effect.
  37784. */
  37785. get: function () {
  37786. return this._vignetteBlendMode;
  37787. },
  37788. /**
  37789. * Sets the vignette blend mode allowing different kind of effect.
  37790. */
  37791. set: function (value) {
  37792. if (this._vignetteBlendMode === value) {
  37793. return;
  37794. }
  37795. this._vignetteBlendMode = value;
  37796. this._updateParameters();
  37797. },
  37798. enumerable: true,
  37799. configurable: true
  37800. });
  37801. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  37802. /**
  37803. * Gets wether the vignette effect is enabled.
  37804. */
  37805. get: function () {
  37806. return this._vignetteEnabled;
  37807. },
  37808. /**
  37809. * Sets wether the vignette effect is enabled.
  37810. */
  37811. set: function (value) {
  37812. if (this._vignetteEnabled === value) {
  37813. return;
  37814. }
  37815. this._vignetteEnabled = value;
  37816. this._updateParameters();
  37817. },
  37818. enumerable: true,
  37819. configurable: true
  37820. });
  37821. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  37822. /**
  37823. * Gets wether the image processing is applied through a post process or not.
  37824. */
  37825. get: function () {
  37826. return this._applyByPostProcess;
  37827. },
  37828. /**
  37829. * Sets wether the image processing is applied through a post process or not.
  37830. */
  37831. set: function (value) {
  37832. if (this._applyByPostProcess === value) {
  37833. return;
  37834. }
  37835. this._applyByPostProcess = value;
  37836. this._updateParameters();
  37837. },
  37838. enumerable: true,
  37839. configurable: true
  37840. });
  37841. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  37842. /**
  37843. * Gets wether the image processing is enabled or not.
  37844. */
  37845. get: function () {
  37846. return this._isEnabled;
  37847. },
  37848. /**
  37849. * Sets wether the image processing is enabled or not.
  37850. */
  37851. set: function (value) {
  37852. if (this._isEnabled === value) {
  37853. return;
  37854. }
  37855. this._isEnabled = value;
  37856. this._updateParameters();
  37857. },
  37858. enumerable: true,
  37859. configurable: true
  37860. });
  37861. /**
  37862. * Method called each time the image processing information changes requires to recompile the effect.
  37863. */
  37864. ImageProcessingConfiguration.prototype._updateParameters = function () {
  37865. this.onUpdateParameters.notifyObservers(this);
  37866. };
  37867. ImageProcessingConfiguration.prototype.getClassName = function () {
  37868. return "ImageProcessingConfiguration";
  37869. };
  37870. /**
  37871. * Prepare the list of uniforms associated with the Image Processing effects.
  37872. * @param uniformsList The list of uniforms used in the effect
  37873. * @param defines the list of defines currently in use
  37874. */
  37875. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  37876. if (defines.EXPOSURE) {
  37877. uniforms.push("exposureLinear");
  37878. }
  37879. if (defines.CONTRAST) {
  37880. uniforms.push("contrast");
  37881. }
  37882. if (defines.COLORGRADING) {
  37883. uniforms.push("colorTransformSettings");
  37884. }
  37885. if (defines.VIGNETTE) {
  37886. uniforms.push("vInverseScreenSize");
  37887. uniforms.push("vignetteSettings1");
  37888. uniforms.push("vignetteSettings2");
  37889. }
  37890. if (defines.COLORCURVES) {
  37891. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  37892. }
  37893. if (defines.GRAIN) {
  37894. uniforms.push("grainVarianceAmount");
  37895. uniforms.push("grainAnimatedSeed");
  37896. }
  37897. };
  37898. /**
  37899. * Prepare the list of samplers associated with the Image Processing effects.
  37900. * @param uniformsList The list of uniforms used in the effect
  37901. * @param defines the list of defines currently in use
  37902. */
  37903. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  37904. if (defines.COLORGRADING) {
  37905. samplersList.push("txColorTransform");
  37906. }
  37907. };
  37908. /**
  37909. * Prepare the list of defines associated to the shader.
  37910. * @param defines the list of defines to complete
  37911. */
  37912. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  37913. if (forPostProcess === void 0) { forPostProcess = false; }
  37914. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  37915. defines.VIGNETTE = false;
  37916. defines.TONEMAPPING = false;
  37917. defines.CONTRAST = false;
  37918. defines.EXPOSURE = false;
  37919. defines.COLORCURVES = false;
  37920. defines.COLORGRADING = false;
  37921. defines.COLORGRADING3D = false;
  37922. defines.IMAGEPROCESSING = false;
  37923. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  37924. return;
  37925. }
  37926. defines.VIGNETTE = this.vignetteEnabled;
  37927. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  37928. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  37929. defines.TONEMAPPING = this.toneMappingEnabled;
  37930. defines.CONTRAST = (this.contrast !== 1.0);
  37931. defines.EXPOSURE = (this.exposure !== 1.0);
  37932. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  37933. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  37934. if (defines.COLORGRADING) {
  37935. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  37936. }
  37937. else {
  37938. defines.COLORGRADING3D = false;
  37939. }
  37940. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  37941. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  37942. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  37943. defines.GRAIN = this.grainEnabled;
  37944. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING || defines.GRAIN;
  37945. };
  37946. /**
  37947. * Returns true if all the image processing information are ready.
  37948. */
  37949. ImageProcessingConfiguration.prototype.isReady = function () {
  37950. // Color Grading texure can not be none blocking.
  37951. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  37952. };
  37953. /**
  37954. * Binds the image processing to the shader.
  37955. * @param effect The effect to bind to
  37956. */
  37957. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  37958. if (aspectRatio === void 0) { aspectRatio = 1; }
  37959. // Color Curves
  37960. if (this._colorCurvesEnabled && this.colorCurves) {
  37961. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  37962. }
  37963. // Vignette
  37964. if (this._vignetteEnabled) {
  37965. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  37966. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  37967. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  37968. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  37969. var vignetteScaleX = vignetteScaleY * aspectRatio;
  37970. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  37971. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  37972. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  37973. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  37974. var vignettePower = -2.0 * this.vignetteWeight;
  37975. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  37976. }
  37977. // Exposure
  37978. effect.setFloat("exposureLinear", this.exposure);
  37979. // Contrast
  37980. effect.setFloat("contrast", this.contrast);
  37981. // Color transform settings
  37982. if (this.colorGradingTexture) {
  37983. effect.setTexture("txColorTransform", this.colorGradingTexture);
  37984. var textureSize = this.colorGradingTexture.getSize().height;
  37985. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  37986. 0.5 / textureSize, // textureOffset
  37987. textureSize, // textureSize
  37988. this.colorGradingTexture.level // weight
  37989. );
  37990. }
  37991. effect.setFloat("grainVarianceAmount", this.grainIntensity);
  37992. effect.setFloat("grainAnimatedSeed", this.grainAnimated ? Math.random() + 1 : 1);
  37993. };
  37994. /**
  37995. * Clones the current image processing instance.
  37996. * @return The cloned image processing
  37997. */
  37998. ImageProcessingConfiguration.prototype.clone = function () {
  37999. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  38000. };
  38001. /**
  38002. * Serializes the current image processing instance to a json representation.
  38003. * @return a JSON representation
  38004. */
  38005. ImageProcessingConfiguration.prototype.serialize = function () {
  38006. return BABYLON.SerializationHelper.Serialize(this);
  38007. };
  38008. /**
  38009. * Parses the image processing from a json representation.
  38010. * @param source the JSON source to parse
  38011. * @return The parsed image processing
  38012. */
  38013. ImageProcessingConfiguration.Parse = function (source) {
  38014. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  38015. };
  38016. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  38017. /**
  38018. * Used to apply the vignette as a mix with the pixel color.
  38019. */
  38020. get: function () {
  38021. return this._VIGNETTEMODE_MULTIPLY;
  38022. },
  38023. enumerable: true,
  38024. configurable: true
  38025. });
  38026. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  38027. /**
  38028. * Used to apply the vignette as a replacement of the pixel color.
  38029. */
  38030. get: function () {
  38031. return this._VIGNETTEMODE_OPAQUE;
  38032. },
  38033. enumerable: true,
  38034. configurable: true
  38035. });
  38036. // Static constants associated to the image processing.
  38037. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  38038. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  38039. __decorate([
  38040. BABYLON.serializeAsColorCurves()
  38041. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  38042. __decorate([
  38043. BABYLON.serialize()
  38044. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  38045. __decorate([
  38046. BABYLON.serializeAsTexture()
  38047. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  38048. __decorate([
  38049. BABYLON.serialize()
  38050. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  38051. __decorate([
  38052. BABYLON.serialize()
  38053. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  38054. __decorate([
  38055. BABYLON.serialize()
  38056. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  38057. __decorate([
  38058. BABYLON.serialize()
  38059. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  38060. __decorate([
  38061. BABYLON.serialize()
  38062. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  38063. __decorate([
  38064. BABYLON.serialize()
  38065. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  38066. __decorate([
  38067. BABYLON.serialize()
  38068. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  38069. __decorate([
  38070. BABYLON.serialize()
  38071. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  38072. __decorate([
  38073. BABYLON.serialize()
  38074. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  38075. __decorate([
  38076. BABYLON.serialize()
  38077. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  38078. __decorate([
  38079. BABYLON.serializeAsColor4()
  38080. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  38081. __decorate([
  38082. BABYLON.serialize()
  38083. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  38084. __decorate([
  38085. BABYLON.serialize()
  38086. ], ImageProcessingConfiguration.prototype, "_grainEnabled", void 0);
  38087. __decorate([
  38088. BABYLON.serialize()
  38089. ], ImageProcessingConfiguration.prototype, "_grainIntensity", void 0);
  38090. __decorate([
  38091. BABYLON.serialize()
  38092. ], ImageProcessingConfiguration.prototype, "_grainAnimated", void 0);
  38093. __decorate([
  38094. BABYLON.serialize()
  38095. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  38096. __decorate([
  38097. BABYLON.serialize()
  38098. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  38099. __decorate([
  38100. BABYLON.serialize()
  38101. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  38102. __decorate([
  38103. BABYLON.serialize()
  38104. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  38105. return ImageProcessingConfiguration;
  38106. }());
  38107. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  38108. })(BABYLON || (BABYLON = {}));
  38109. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  38110. "use strict";
  38111. var BABYLON;
  38112. (function (BABYLON) {
  38113. /**
  38114. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  38115. * It can help converting any input color in a desired output one. This can then be used to create effects
  38116. * from sepia, black and white to sixties or futuristic rendering...
  38117. *
  38118. * The only supported format is currently 3dl.
  38119. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  38120. */
  38121. var ColorGradingTexture = /** @class */ (function (_super) {
  38122. __extends(ColorGradingTexture, _super);
  38123. /**
  38124. * Instantiates a ColorGradingTexture from the following parameters.
  38125. *
  38126. * @param url The location of the color gradind data (currently only supporting 3dl)
  38127. * @param scene The scene the texture will be used in
  38128. */
  38129. function ColorGradingTexture(url, scene) {
  38130. var _this = _super.call(this, scene) || this;
  38131. if (!url) {
  38132. return _this;
  38133. }
  38134. _this._engine = scene.getEngine();
  38135. _this._textureMatrix = BABYLON.Matrix.Identity();
  38136. _this.name = url;
  38137. _this.url = url;
  38138. _this.hasAlpha = false;
  38139. _this.isCube = false;
  38140. _this.is3D = _this._engine.webGLVersion > 1;
  38141. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38142. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38143. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38144. _this.anisotropicFilteringLevel = 1;
  38145. _this._texture = _this._getFromCache(url, true);
  38146. if (!_this._texture) {
  38147. if (!scene.useDelayedTextureLoading) {
  38148. _this.loadTexture();
  38149. }
  38150. else {
  38151. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  38152. }
  38153. }
  38154. return _this;
  38155. }
  38156. /**
  38157. * Returns the texture matrix used in most of the material.
  38158. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  38159. */
  38160. ColorGradingTexture.prototype.getTextureMatrix = function () {
  38161. return this._textureMatrix;
  38162. };
  38163. /**
  38164. * Occurs when the file being loaded is a .3dl LUT file.
  38165. */
  38166. ColorGradingTexture.prototype.load3dlTexture = function () {
  38167. var engine = this._engine;
  38168. var texture;
  38169. if (engine.webGLVersion === 1) {
  38170. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  38171. }
  38172. else {
  38173. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  38174. }
  38175. this._texture = texture;
  38176. var callback = function (text) {
  38177. if (typeof text !== "string") {
  38178. return;
  38179. }
  38180. var data = null;
  38181. var tempData = null;
  38182. var line;
  38183. var lines = text.split('\n');
  38184. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  38185. var maxColor = 0;
  38186. for (var i = 0; i < lines.length; i++) {
  38187. line = lines[i];
  38188. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  38189. continue;
  38190. if (line.indexOf('#') === 0)
  38191. continue;
  38192. var words = line.split(" ");
  38193. if (size === 0) {
  38194. // Number of space + one
  38195. size = words.length;
  38196. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  38197. tempData = new Float32Array(size * size * size * 4);
  38198. continue;
  38199. }
  38200. if (size != 0) {
  38201. var r = Math.max(parseInt(words[0]), 0);
  38202. var g = Math.max(parseInt(words[1]), 0);
  38203. var b = Math.max(parseInt(words[2]), 0);
  38204. maxColor = Math.max(r, maxColor);
  38205. maxColor = Math.max(g, maxColor);
  38206. maxColor = Math.max(b, maxColor);
  38207. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  38208. if (tempData) {
  38209. tempData[pixelStorageIndex + 0] = r;
  38210. tempData[pixelStorageIndex + 1] = g;
  38211. tempData[pixelStorageIndex + 2] = b;
  38212. }
  38213. pixelIndexSlice++;
  38214. if (pixelIndexSlice % size == 0) {
  38215. pixelIndexH++;
  38216. pixelIndexSlice = 0;
  38217. if (pixelIndexH % size == 0) {
  38218. pixelIndexW++;
  38219. pixelIndexH = 0;
  38220. }
  38221. }
  38222. }
  38223. }
  38224. if (tempData && data) {
  38225. for (var i = 0; i < tempData.length; i++) {
  38226. if (i > 0 && (i + 1) % 4 === 0) {
  38227. data[i] = 255;
  38228. }
  38229. else {
  38230. var value = tempData[i];
  38231. data[i] = (value / maxColor * 255);
  38232. }
  38233. }
  38234. }
  38235. if (texture.is3D) {
  38236. texture.updateSize(size, size, size);
  38237. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  38238. }
  38239. else {
  38240. texture.updateSize(size * size, size);
  38241. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  38242. }
  38243. };
  38244. var scene = this.getScene();
  38245. if (scene) {
  38246. scene._loadFile(this.url, callback);
  38247. }
  38248. else {
  38249. this._engine._loadFile(this.url, callback);
  38250. }
  38251. return this._texture;
  38252. };
  38253. /**
  38254. * Starts the loading process of the texture.
  38255. */
  38256. ColorGradingTexture.prototype.loadTexture = function () {
  38257. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  38258. this.load3dlTexture();
  38259. }
  38260. };
  38261. /**
  38262. * Clones the color gradind texture.
  38263. */
  38264. ColorGradingTexture.prototype.clone = function () {
  38265. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  38266. // Base texture
  38267. newTexture.level = this.level;
  38268. return newTexture;
  38269. };
  38270. /**
  38271. * Called during delayed load for textures.
  38272. */
  38273. ColorGradingTexture.prototype.delayLoad = function () {
  38274. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  38275. return;
  38276. }
  38277. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  38278. this._texture = this._getFromCache(this.url, true);
  38279. if (!this._texture) {
  38280. this.loadTexture();
  38281. }
  38282. };
  38283. /**
  38284. * Parses a color grading texture serialized by Babylon.
  38285. * @param parsedTexture The texture information being parsedTexture
  38286. * @param scene The scene to load the texture in
  38287. * @param rootUrl The root url of the data assets to load
  38288. * @return A color gradind texture
  38289. */
  38290. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  38291. var texture = null;
  38292. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  38293. texture = new ColorGradingTexture(parsedTexture.name, scene);
  38294. texture.name = parsedTexture.name;
  38295. texture.level = parsedTexture.level;
  38296. }
  38297. return texture;
  38298. };
  38299. /**
  38300. * Serializes the LUT texture to json format.
  38301. */
  38302. ColorGradingTexture.prototype.serialize = function () {
  38303. if (!this.name) {
  38304. return null;
  38305. }
  38306. var serializationObject = {};
  38307. serializationObject.name = this.name;
  38308. serializationObject.level = this.level;
  38309. serializationObject.customType = "BABYLON.ColorGradingTexture";
  38310. return serializationObject;
  38311. };
  38312. /**
  38313. * Empty line regex stored for GC.
  38314. */
  38315. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  38316. return ColorGradingTexture;
  38317. }(BABYLON.BaseTexture));
  38318. BABYLON.ColorGradingTexture = ColorGradingTexture;
  38319. })(BABYLON || (BABYLON = {}));
  38320. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  38321. "use strict";
  38322. var BABYLON;
  38323. (function (BABYLON) {
  38324. /**
  38325. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  38326. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  38327. * 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;
  38328. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  38329. */
  38330. var ColorCurves = /** @class */ (function () {
  38331. function ColorCurves() {
  38332. this._dirty = true;
  38333. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  38334. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  38335. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  38336. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  38337. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  38338. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  38339. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  38340. this._globalHue = 30;
  38341. this._globalDensity = 0;
  38342. this._globalSaturation = 0;
  38343. this._globalExposure = 0;
  38344. this._highlightsHue = 30;
  38345. this._highlightsDensity = 0;
  38346. this._highlightsSaturation = 0;
  38347. this._highlightsExposure = 0;
  38348. this._midtonesHue = 30;
  38349. this._midtonesDensity = 0;
  38350. this._midtonesSaturation = 0;
  38351. this._midtonesExposure = 0;
  38352. this._shadowsHue = 30;
  38353. this._shadowsDensity = 0;
  38354. this._shadowsSaturation = 0;
  38355. this._shadowsExposure = 0;
  38356. }
  38357. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  38358. /**
  38359. * Gets the global Hue value.
  38360. * 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).
  38361. */
  38362. get: function () {
  38363. return this._globalHue;
  38364. },
  38365. /**
  38366. * Sets the global Hue value.
  38367. * 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).
  38368. */
  38369. set: function (value) {
  38370. this._globalHue = value;
  38371. this._dirty = true;
  38372. },
  38373. enumerable: true,
  38374. configurable: true
  38375. });
  38376. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  38377. /**
  38378. * Gets the global Density value.
  38379. * 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.
  38380. * Values less than zero provide a filter of opposite hue.
  38381. */
  38382. get: function () {
  38383. return this._globalDensity;
  38384. },
  38385. /**
  38386. * Sets the global Density value.
  38387. * 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.
  38388. * Values less than zero provide a filter of opposite hue.
  38389. */
  38390. set: function (value) {
  38391. this._globalDensity = value;
  38392. this._dirty = true;
  38393. },
  38394. enumerable: true,
  38395. configurable: true
  38396. });
  38397. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  38398. /**
  38399. * Gets the global Saturation value.
  38400. * 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.
  38401. */
  38402. get: function () {
  38403. return this._globalSaturation;
  38404. },
  38405. /**
  38406. * Sets the global Saturation value.
  38407. * 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.
  38408. */
  38409. set: function (value) {
  38410. this._globalSaturation = value;
  38411. this._dirty = true;
  38412. },
  38413. enumerable: true,
  38414. configurable: true
  38415. });
  38416. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  38417. /**
  38418. * Gets the highlights Hue value.
  38419. * 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).
  38420. */
  38421. get: function () {
  38422. return this._highlightsHue;
  38423. },
  38424. /**
  38425. * Sets the highlights Hue value.
  38426. * 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).
  38427. */
  38428. set: function (value) {
  38429. this._highlightsHue = value;
  38430. this._dirty = true;
  38431. },
  38432. enumerable: true,
  38433. configurable: true
  38434. });
  38435. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  38436. /**
  38437. * Gets the highlights Density value.
  38438. * 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.
  38439. * Values less than zero provide a filter of opposite hue.
  38440. */
  38441. get: function () {
  38442. return this._highlightsDensity;
  38443. },
  38444. /**
  38445. * Sets the highlights Density value.
  38446. * 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.
  38447. * Values less than zero provide a filter of opposite hue.
  38448. */
  38449. set: function (value) {
  38450. this._highlightsDensity = value;
  38451. this._dirty = true;
  38452. },
  38453. enumerable: true,
  38454. configurable: true
  38455. });
  38456. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  38457. /**
  38458. * Gets the highlights Saturation value.
  38459. * 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.
  38460. */
  38461. get: function () {
  38462. return this._highlightsSaturation;
  38463. },
  38464. /**
  38465. * Sets the highlights Saturation value.
  38466. * 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.
  38467. */
  38468. set: function (value) {
  38469. this._highlightsSaturation = value;
  38470. this._dirty = true;
  38471. },
  38472. enumerable: true,
  38473. configurable: true
  38474. });
  38475. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  38476. /**
  38477. * Gets the highlights Exposure value.
  38478. * 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.
  38479. */
  38480. get: function () {
  38481. return this._highlightsExposure;
  38482. },
  38483. /**
  38484. * Sets the highlights Exposure value.
  38485. * 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.
  38486. */
  38487. set: function (value) {
  38488. this._highlightsExposure = value;
  38489. this._dirty = true;
  38490. },
  38491. enumerable: true,
  38492. configurable: true
  38493. });
  38494. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  38495. /**
  38496. * Gets the midtones Hue value.
  38497. * 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).
  38498. */
  38499. get: function () {
  38500. return this._midtonesHue;
  38501. },
  38502. /**
  38503. * Sets the midtones Hue value.
  38504. * 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).
  38505. */
  38506. set: function (value) {
  38507. this._midtonesHue = value;
  38508. this._dirty = true;
  38509. },
  38510. enumerable: true,
  38511. configurable: true
  38512. });
  38513. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  38514. /**
  38515. * Gets the midtones Density value.
  38516. * 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.
  38517. * Values less than zero provide a filter of opposite hue.
  38518. */
  38519. get: function () {
  38520. return this._midtonesDensity;
  38521. },
  38522. /**
  38523. * Sets the midtones Density value.
  38524. * 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.
  38525. * Values less than zero provide a filter of opposite hue.
  38526. */
  38527. set: function (value) {
  38528. this._midtonesDensity = value;
  38529. this._dirty = true;
  38530. },
  38531. enumerable: true,
  38532. configurable: true
  38533. });
  38534. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  38535. /**
  38536. * Gets the midtones Saturation value.
  38537. * 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.
  38538. */
  38539. get: function () {
  38540. return this._midtonesSaturation;
  38541. },
  38542. /**
  38543. * Sets the midtones Saturation value.
  38544. * 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.
  38545. */
  38546. set: function (value) {
  38547. this._midtonesSaturation = value;
  38548. this._dirty = true;
  38549. },
  38550. enumerable: true,
  38551. configurable: true
  38552. });
  38553. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  38554. /**
  38555. * Gets the midtones Exposure value.
  38556. * 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.
  38557. */
  38558. get: function () {
  38559. return this._midtonesExposure;
  38560. },
  38561. /**
  38562. * Sets the midtones Exposure value.
  38563. * 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.
  38564. */
  38565. set: function (value) {
  38566. this._midtonesExposure = value;
  38567. this._dirty = true;
  38568. },
  38569. enumerable: true,
  38570. configurable: true
  38571. });
  38572. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  38573. /**
  38574. * Gets the shadows Hue value.
  38575. * 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).
  38576. */
  38577. get: function () {
  38578. return this._shadowsHue;
  38579. },
  38580. /**
  38581. * Sets the shadows Hue value.
  38582. * 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).
  38583. */
  38584. set: function (value) {
  38585. this._shadowsHue = value;
  38586. this._dirty = true;
  38587. },
  38588. enumerable: true,
  38589. configurable: true
  38590. });
  38591. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  38592. /**
  38593. * Gets the shadows Density value.
  38594. * 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.
  38595. * Values less than zero provide a filter of opposite hue.
  38596. */
  38597. get: function () {
  38598. return this._shadowsDensity;
  38599. },
  38600. /**
  38601. * Sets the shadows Density value.
  38602. * 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.
  38603. * Values less than zero provide a filter of opposite hue.
  38604. */
  38605. set: function (value) {
  38606. this._shadowsDensity = value;
  38607. this._dirty = true;
  38608. },
  38609. enumerable: true,
  38610. configurable: true
  38611. });
  38612. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  38613. /**
  38614. * Gets the shadows Saturation value.
  38615. * 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.
  38616. */
  38617. get: function () {
  38618. return this._shadowsSaturation;
  38619. },
  38620. /**
  38621. * Sets the shadows Saturation value.
  38622. * 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.
  38623. */
  38624. set: function (value) {
  38625. this._shadowsSaturation = value;
  38626. this._dirty = true;
  38627. },
  38628. enumerable: true,
  38629. configurable: true
  38630. });
  38631. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  38632. /**
  38633. * Gets the shadows Exposure value.
  38634. * 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.
  38635. */
  38636. get: function () {
  38637. return this._shadowsExposure;
  38638. },
  38639. /**
  38640. * Sets the shadows Exposure value.
  38641. * 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.
  38642. */
  38643. set: function (value) {
  38644. this._shadowsExposure = value;
  38645. this._dirty = true;
  38646. },
  38647. enumerable: true,
  38648. configurable: true
  38649. });
  38650. ColorCurves.prototype.getClassName = function () {
  38651. return "ColorCurves";
  38652. };
  38653. /**
  38654. * Binds the color curves to the shader.
  38655. * @param colorCurves The color curve to bind
  38656. * @param effect The effect to bind to
  38657. */
  38658. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  38659. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  38660. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  38661. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  38662. if (colorCurves._dirty) {
  38663. colorCurves._dirty = false;
  38664. // Fill in global info.
  38665. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  38666. // Compute highlights info.
  38667. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  38668. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  38669. // Compute midtones info.
  38670. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  38671. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  38672. // Compute shadows info.
  38673. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  38674. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  38675. // Compute deltas (neutral is midtones).
  38676. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  38677. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  38678. }
  38679. if (effect) {
  38680. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  38681. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  38682. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  38683. }
  38684. };
  38685. /**
  38686. * Prepare the list of uniforms associated with the ColorCurves effects.
  38687. * @param uniformsList The list of uniforms used in the effect
  38688. */
  38689. ColorCurves.PrepareUniforms = function (uniformsList) {
  38690. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  38691. };
  38692. /**
  38693. * Returns color grading data based on a hue, density, saturation and exposure value.
  38694. * @param filterHue The hue of the color filter.
  38695. * @param filterDensity The density of the color filter.
  38696. * @param saturation The saturation.
  38697. * @param exposure The exposure.
  38698. * @param result The result data container.
  38699. */
  38700. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  38701. if (hue == null) {
  38702. return;
  38703. }
  38704. hue = ColorCurves.clamp(hue, 0, 360);
  38705. density = ColorCurves.clamp(density, -100, 100);
  38706. saturation = ColorCurves.clamp(saturation, -100, 100);
  38707. exposure = ColorCurves.clamp(exposure, -100, 100);
  38708. // Remap the slider/config filter density with non-linear mapping and also scale by half
  38709. // so that the maximum filter density is only 50% control. This provides fine control
  38710. // for small values and reasonable range.
  38711. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  38712. density *= 0.5;
  38713. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  38714. if (density < 0) {
  38715. density *= -1;
  38716. hue = (hue + 180) % 360;
  38717. }
  38718. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  38719. result.scaleToRef(2, result);
  38720. result.a = 1 + 0.01 * saturation;
  38721. };
  38722. /**
  38723. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  38724. * @param value The input slider value in range [-100,100].
  38725. * @returns Adjusted value.
  38726. */
  38727. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  38728. value /= 100;
  38729. var x = Math.abs(value);
  38730. x = Math.pow(x, 2);
  38731. if (value < 0) {
  38732. x *= -1;
  38733. }
  38734. x *= 100;
  38735. return x;
  38736. };
  38737. /**
  38738. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  38739. * @param hue The hue (H) input.
  38740. * @param saturation The saturation (S) input.
  38741. * @param brightness The brightness (B) input.
  38742. * @result An RGBA color represented as Vector4.
  38743. */
  38744. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  38745. var h = ColorCurves.clamp(hue, 0, 360);
  38746. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  38747. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  38748. if (s === 0) {
  38749. result.r = v;
  38750. result.g = v;
  38751. result.b = v;
  38752. }
  38753. else {
  38754. // sector 0 to 5
  38755. h /= 60;
  38756. var i = Math.floor(h);
  38757. // fractional part of h
  38758. var f = h - i;
  38759. var p = v * (1 - s);
  38760. var q = v * (1 - s * f);
  38761. var t = v * (1 - s * (1 - f));
  38762. switch (i) {
  38763. case 0:
  38764. result.r = v;
  38765. result.g = t;
  38766. result.b = p;
  38767. break;
  38768. case 1:
  38769. result.r = q;
  38770. result.g = v;
  38771. result.b = p;
  38772. break;
  38773. case 2:
  38774. result.r = p;
  38775. result.g = v;
  38776. result.b = t;
  38777. break;
  38778. case 3:
  38779. result.r = p;
  38780. result.g = q;
  38781. result.b = v;
  38782. break;
  38783. case 4:
  38784. result.r = t;
  38785. result.g = p;
  38786. result.b = v;
  38787. break;
  38788. default:// case 5:
  38789. result.r = v;
  38790. result.g = p;
  38791. result.b = q;
  38792. break;
  38793. }
  38794. }
  38795. result.a = 1;
  38796. };
  38797. /**
  38798. * Returns a value clamped between min and max
  38799. * @param value The value to clamp
  38800. * @param min The minimum of value
  38801. * @param max The maximum of value
  38802. * @returns The clamped value.
  38803. */
  38804. ColorCurves.clamp = function (value, min, max) {
  38805. return Math.min(Math.max(value, min), max);
  38806. };
  38807. /**
  38808. * Clones the current color curve instance.
  38809. * @return The cloned curves
  38810. */
  38811. ColorCurves.prototype.clone = function () {
  38812. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  38813. };
  38814. /**
  38815. * Serializes the current color curve instance to a json representation.
  38816. * @return a JSON representation
  38817. */
  38818. ColorCurves.prototype.serialize = function () {
  38819. return BABYLON.SerializationHelper.Serialize(this);
  38820. };
  38821. /**
  38822. * Parses the color curve from a json representation.
  38823. * @param source the JSON source to parse
  38824. * @return The parsed curves
  38825. */
  38826. ColorCurves.Parse = function (source) {
  38827. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  38828. };
  38829. __decorate([
  38830. BABYLON.serialize()
  38831. ], ColorCurves.prototype, "_globalHue", void 0);
  38832. __decorate([
  38833. BABYLON.serialize()
  38834. ], ColorCurves.prototype, "_globalDensity", void 0);
  38835. __decorate([
  38836. BABYLON.serialize()
  38837. ], ColorCurves.prototype, "_globalSaturation", void 0);
  38838. __decorate([
  38839. BABYLON.serialize()
  38840. ], ColorCurves.prototype, "_globalExposure", void 0);
  38841. __decorate([
  38842. BABYLON.serialize()
  38843. ], ColorCurves.prototype, "_highlightsHue", void 0);
  38844. __decorate([
  38845. BABYLON.serialize()
  38846. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  38847. __decorate([
  38848. BABYLON.serialize()
  38849. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  38850. __decorate([
  38851. BABYLON.serialize()
  38852. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  38853. __decorate([
  38854. BABYLON.serialize()
  38855. ], ColorCurves.prototype, "_midtonesHue", void 0);
  38856. __decorate([
  38857. BABYLON.serialize()
  38858. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  38859. __decorate([
  38860. BABYLON.serialize()
  38861. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  38862. __decorate([
  38863. BABYLON.serialize()
  38864. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  38865. return ColorCurves;
  38866. }());
  38867. BABYLON.ColorCurves = ColorCurves;
  38868. })(BABYLON || (BABYLON = {}));
  38869. //# sourceMappingURL=babylon.colorCurves.js.map
  38870. "use strict";
  38871. //# sourceMappingURL=babylon.behavior.js.map
  38872. "use strict";
  38873. var BABYLON;
  38874. (function (BABYLON) {
  38875. /**
  38876. * "Static Class" containing the most commonly used helper while dealing with material for
  38877. * rendering purpose.
  38878. *
  38879. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  38880. *
  38881. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  38882. */
  38883. var MaterialHelper = /** @class */ (function () {
  38884. function MaterialHelper() {
  38885. }
  38886. /**
  38887. * Bind the current view position to an effect.
  38888. * @param effect The effect to be bound
  38889. * @param scene The scene the eyes position is used from
  38890. */
  38891. MaterialHelper.BindEyePosition = function (effect, scene) {
  38892. if (scene._forcedViewPosition) {
  38893. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  38894. return;
  38895. }
  38896. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  38897. };
  38898. /**
  38899. * Helps preparing the defines values about the UVs in used in the effect.
  38900. * UVs are shared as much as we can accross chanels in the shaders.
  38901. * @param texture The texture we are preparing the UVs for
  38902. * @param defines The defines to update
  38903. * @param key The chanel key "diffuse", "specular"... used in the shader
  38904. */
  38905. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  38906. defines._needUVs = true;
  38907. defines[key] = true;
  38908. if (texture.getTextureMatrix().isIdentity(true)) {
  38909. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  38910. if (texture.coordinatesIndex === 0) {
  38911. defines["MAINUV1"] = true;
  38912. }
  38913. else {
  38914. defines["MAINUV2"] = true;
  38915. }
  38916. }
  38917. else {
  38918. defines[key + "DIRECTUV"] = 0;
  38919. }
  38920. };
  38921. /**
  38922. * Binds a texture matrix value to its corrsponding uniform
  38923. * @param texture The texture to bind the matrix for
  38924. * @param uniformBuffer The uniform buffer receivin the data
  38925. * @param key The chanel key "diffuse", "specular"... used in the shader
  38926. */
  38927. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  38928. var matrix = texture.getTextureMatrix();
  38929. if (!matrix.isIdentity(true)) {
  38930. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  38931. }
  38932. };
  38933. /**
  38934. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  38935. * @param mesh defines the current mesh
  38936. * @param scene defines the current scene
  38937. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  38938. * @param pointsCloud defines if point cloud rendering has to be turned on
  38939. * @param fogEnabled defines if fog has to be turned on
  38940. * @param alphaTest defines if alpha testing has to be turned on
  38941. * @param defines defines the current list of defines
  38942. */
  38943. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  38944. if (defines._areMiscDirty) {
  38945. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  38946. defines["POINTSIZE"] = pointsCloud;
  38947. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  38948. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  38949. defines["ALPHATEST"] = alphaTest;
  38950. }
  38951. };
  38952. /**
  38953. * Helper used to prepare the list of defines associated with frame values for shader compilation
  38954. * @param scene defines the current scene
  38955. * @param engine defines the current engine
  38956. * @param defines specifies the list of active defines
  38957. * @param useInstances defines if instances have to be turned on
  38958. * @param useClipPlane defines if clip plane have to be turned on
  38959. */
  38960. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  38961. if (useClipPlane === void 0) { useClipPlane = null; }
  38962. var changed = false;
  38963. if (useClipPlane == null) {
  38964. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  38965. }
  38966. if (defines["CLIPPLANE"] !== useClipPlane) {
  38967. defines["CLIPPLANE"] = useClipPlane;
  38968. changed = true;
  38969. }
  38970. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  38971. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  38972. changed = true;
  38973. }
  38974. if (defines["INSTANCES"] !== useInstances) {
  38975. defines["INSTANCES"] = useInstances;
  38976. changed = true;
  38977. }
  38978. if (changed) {
  38979. defines.markAsUnprocessed();
  38980. }
  38981. };
  38982. /**
  38983. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  38984. * @param mesh The mesh containing the geometry data we will draw
  38985. * @param defines The defines to update
  38986. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  38987. * @param useBones Precise whether bones should be used or not (override mesh info)
  38988. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  38989. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  38990. * @returns false if defines are considered not dirty and have not been checked
  38991. */
  38992. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  38993. if (useMorphTargets === void 0) { useMorphTargets = false; }
  38994. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  38995. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  38996. return false;
  38997. }
  38998. defines._normals = defines._needNormals;
  38999. defines._uvs = defines._needUVs;
  39000. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  39001. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  39002. defines["TANGENT"] = true;
  39003. }
  39004. if (defines._needUVs) {
  39005. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  39006. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  39007. }
  39008. else {
  39009. defines["UV1"] = false;
  39010. defines["UV2"] = false;
  39011. }
  39012. if (useVertexColor) {
  39013. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  39014. defines["VERTEXCOLOR"] = hasVertexColors;
  39015. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  39016. }
  39017. if (useBones) {
  39018. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  39019. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  39020. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  39021. }
  39022. else {
  39023. defines["NUM_BONE_INFLUENCERS"] = 0;
  39024. defines["BonesPerMesh"] = 0;
  39025. }
  39026. }
  39027. if (useMorphTargets) {
  39028. var manager = mesh.morphTargetManager;
  39029. if (manager) {
  39030. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  39031. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  39032. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  39033. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  39034. }
  39035. else {
  39036. defines["MORPHTARGETS_TANGENT"] = false;
  39037. defines["MORPHTARGETS_NORMAL"] = false;
  39038. defines["MORPHTARGETS"] = false;
  39039. defines["NUM_MORPH_INFLUENCERS"] = 0;
  39040. }
  39041. }
  39042. return true;
  39043. };
  39044. /**
  39045. * Prepares the defines related to the light information passed in parameter
  39046. * @param scene The scene we are intending to draw
  39047. * @param mesh The mesh the effect is compiling for
  39048. * @param defines The defines to update
  39049. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  39050. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  39051. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  39052. * @returns true if normals will be required for the rest of the effect
  39053. */
  39054. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  39055. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  39056. if (disableLighting === void 0) { disableLighting = false; }
  39057. if (!defines._areLightsDirty) {
  39058. return defines._needNormals;
  39059. }
  39060. var lightIndex = 0;
  39061. var needNormals = false;
  39062. var needRebuild = false;
  39063. var lightmapMode = false;
  39064. var shadowEnabled = false;
  39065. var specularEnabled = false;
  39066. if (scene.lightsEnabled && !disableLighting) {
  39067. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  39068. var light = _a[_i];
  39069. needNormals = true;
  39070. if (defines["LIGHT" + lightIndex] === undefined) {
  39071. needRebuild = true;
  39072. }
  39073. defines["LIGHT" + lightIndex] = true;
  39074. defines["SPOTLIGHT" + lightIndex] = false;
  39075. defines["HEMILIGHT" + lightIndex] = false;
  39076. defines["POINTLIGHT" + lightIndex] = false;
  39077. defines["DIRLIGHT" + lightIndex] = false;
  39078. var type;
  39079. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  39080. type = "SPOTLIGHT" + lightIndex;
  39081. var spotLight = light;
  39082. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? spotLight.projectionTexture.isReady() : false;
  39083. }
  39084. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  39085. type = "HEMILIGHT" + lightIndex;
  39086. }
  39087. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  39088. type = "POINTLIGHT" + lightIndex;
  39089. }
  39090. else {
  39091. type = "DIRLIGHT" + lightIndex;
  39092. }
  39093. defines[type] = true;
  39094. // Specular
  39095. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  39096. specularEnabled = true;
  39097. }
  39098. // Shadows
  39099. defines["SHADOW" + lightIndex] = false;
  39100. defines["SHADOWPCF" + lightIndex] = false;
  39101. defines["SHADOWPCSS" + lightIndex] = false;
  39102. defines["SHADOWPOISSON" + lightIndex] = false;
  39103. defines["SHADOWESM" + lightIndex] = false;
  39104. defines["SHADOWCUBE" + lightIndex] = false;
  39105. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  39106. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  39107. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  39108. var shadowGenerator = light.getShadowGenerator();
  39109. if (shadowGenerator) {
  39110. shadowEnabled = true;
  39111. shadowGenerator.prepareDefines(defines, lightIndex);
  39112. }
  39113. }
  39114. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  39115. lightmapMode = true;
  39116. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  39117. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  39118. }
  39119. else {
  39120. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  39121. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  39122. }
  39123. lightIndex++;
  39124. if (lightIndex === maxSimultaneousLights)
  39125. break;
  39126. }
  39127. }
  39128. defines["SPECULARTERM"] = specularEnabled;
  39129. defines["SHADOWS"] = shadowEnabled;
  39130. // Resetting all other lights if any
  39131. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  39132. if (defines["LIGHT" + index] !== undefined) {
  39133. defines["LIGHT" + index] = false;
  39134. defines["HEMILIGHT" + lightIndex] = false;
  39135. defines["POINTLIGHT" + lightIndex] = false;
  39136. defines["DIRLIGHT" + lightIndex] = false;
  39137. defines["SPOTLIGHT" + lightIndex] = false;
  39138. defines["SHADOW" + lightIndex] = false;
  39139. }
  39140. }
  39141. var caps = scene.getEngine().getCaps();
  39142. if (defines["SHADOWFLOAT"] === undefined) {
  39143. needRebuild = true;
  39144. }
  39145. defines["SHADOWFLOAT"] = shadowEnabled &&
  39146. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  39147. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  39148. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  39149. if (needRebuild) {
  39150. defines.rebuild();
  39151. }
  39152. return needNormals;
  39153. };
  39154. /**
  39155. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  39156. * that won t be acctive due to defines being turned off.
  39157. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  39158. * @param samplersList The samplers list
  39159. * @param defines The defines helping in the list generation
  39160. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  39161. */
  39162. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  39163. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  39164. var uniformsList;
  39165. var uniformBuffersList = null;
  39166. if (uniformsListOrOptions.uniformsNames) {
  39167. var options = uniformsListOrOptions;
  39168. uniformsList = options.uniformsNames;
  39169. uniformBuffersList = options.uniformBuffersNames;
  39170. samplersList = options.samplers;
  39171. defines = options.defines;
  39172. maxSimultaneousLights = options.maxSimultaneousLights;
  39173. }
  39174. else {
  39175. uniformsList = uniformsListOrOptions;
  39176. if (!samplersList) {
  39177. samplersList = [];
  39178. }
  39179. }
  39180. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  39181. if (!defines["LIGHT" + lightIndex]) {
  39182. break;
  39183. }
  39184. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  39185. if (uniformBuffersList) {
  39186. uniformBuffersList.push("Light" + lightIndex);
  39187. }
  39188. samplersList.push("shadowSampler" + lightIndex);
  39189. samplersList.push("depthSampler" + lightIndex);
  39190. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  39191. samplersList.push("projectionLightSampler" + lightIndex);
  39192. uniformsList.push("textureProjectionMatrix" + lightIndex);
  39193. }
  39194. }
  39195. if (defines["NUM_MORPH_INFLUENCERS"]) {
  39196. uniformsList.push("morphTargetInfluences");
  39197. }
  39198. };
  39199. /**
  39200. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  39201. * @param defines The defines to update while falling back
  39202. * @param fallbacks The authorized effect fallbacks
  39203. * @param maxSimultaneousLights The maximum number of lights allowed
  39204. * @param rank the current rank of the Effect
  39205. * @returns The newly affected rank
  39206. */
  39207. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  39208. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  39209. if (rank === void 0) { rank = 0; }
  39210. var lightFallbackRank = 0;
  39211. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  39212. if (!defines["LIGHT" + lightIndex]) {
  39213. break;
  39214. }
  39215. if (lightIndex > 0) {
  39216. lightFallbackRank = rank + lightIndex;
  39217. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  39218. }
  39219. if (!defines["SHADOWS"]) {
  39220. if (defines["SHADOW" + lightIndex]) {
  39221. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  39222. }
  39223. if (defines["SHADOWPCF" + lightIndex]) {
  39224. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  39225. }
  39226. if (defines["SHADOWPCSS" + lightIndex]) {
  39227. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  39228. }
  39229. if (defines["SHADOWPOISSON" + lightIndex]) {
  39230. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  39231. }
  39232. if (defines["SHADOWESM" + lightIndex]) {
  39233. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  39234. }
  39235. }
  39236. }
  39237. return lightFallbackRank++;
  39238. };
  39239. /**
  39240. * Prepares the list of attributes required for morph targets according to the effect defines.
  39241. * @param attribs The current list of supported attribs
  39242. * @param mesh The mesh to prepare the morph targets attributes for
  39243. * @param defines The current Defines of the effect
  39244. */
  39245. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  39246. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  39247. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  39248. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  39249. var manager = mesh.morphTargetManager;
  39250. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  39251. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  39252. for (var index = 0; index < influencers; index++) {
  39253. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  39254. if (normal) {
  39255. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  39256. }
  39257. if (tangent) {
  39258. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  39259. }
  39260. if (attribs.length > maxAttributesCount) {
  39261. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  39262. }
  39263. }
  39264. }
  39265. };
  39266. /**
  39267. * Prepares the list of attributes required for bones according to the effect defines.
  39268. * @param attribs The current list of supported attribs
  39269. * @param mesh The mesh to prepare the bones attributes for
  39270. * @param defines The current Defines of the effect
  39271. * @param fallbacks The current efffect fallback strategy
  39272. */
  39273. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  39274. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  39275. fallbacks.addCPUSkinningFallback(0, mesh);
  39276. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39277. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39278. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  39279. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39280. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  39281. }
  39282. }
  39283. };
  39284. /**
  39285. * Prepares the list of attributes required for instances according to the effect defines.
  39286. * @param attribs The current list of supported attribs
  39287. * @param defines The current Defines of the effect
  39288. */
  39289. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  39290. if (defines["INSTANCES"]) {
  39291. attribs.push("world0");
  39292. attribs.push("world1");
  39293. attribs.push("world2");
  39294. attribs.push("world3");
  39295. }
  39296. };
  39297. /**
  39298. * Binds the light shadow information to the effect for the given mesh.
  39299. * @param light The light containing the generator
  39300. * @param scene The scene the lights belongs to
  39301. * @param mesh The mesh we are binding the information to render
  39302. * @param lightIndex The light index in the effect used to render the mesh
  39303. * @param effect The effect we are binding the data to
  39304. */
  39305. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  39306. if (light.shadowEnabled && mesh.receiveShadows) {
  39307. var shadowGenerator = light.getShadowGenerator();
  39308. if (shadowGenerator) {
  39309. shadowGenerator.bindShadowLight(lightIndex, effect);
  39310. }
  39311. }
  39312. };
  39313. /**
  39314. * Binds the light information to the effect.
  39315. * @param light The light containing the generator
  39316. * @param effect The effect we are binding the data to
  39317. * @param lightIndex The light index in the effect used to render
  39318. */
  39319. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  39320. light.transferToEffect(effect, lightIndex + "");
  39321. };
  39322. /**
  39323. * Binds the lights information from the scene to the effect for the given mesh.
  39324. * @param scene The scene the lights belongs to
  39325. * @param mesh The mesh we are binding the information to render
  39326. * @param effect The effect we are binding the data to
  39327. * @param defines The generated defines for the effect
  39328. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  39329. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  39330. */
  39331. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  39332. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  39333. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  39334. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  39335. for (var i = 0; i < len; i++) {
  39336. var light = mesh._lightSources[i];
  39337. var iAsString = i.toString();
  39338. var scaledIntensity = light.getScaledIntensity();
  39339. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  39340. MaterialHelper.BindLightProperties(light, effect, i);
  39341. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  39342. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  39343. if (defines["SPECULARTERM"]) {
  39344. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  39345. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  39346. }
  39347. // Shadows
  39348. if (scene.shadowsEnabled) {
  39349. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  39350. }
  39351. light._uniformBuffer.update();
  39352. }
  39353. };
  39354. /**
  39355. * Binds the fog information from the scene to the effect for the given mesh.
  39356. * @param scene The scene the lights belongs to
  39357. * @param mesh The mesh we are binding the information to render
  39358. * @param effect The effect we are binding the data to
  39359. */
  39360. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  39361. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  39362. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  39363. effect.setColor3("vFogColor", scene.fogColor);
  39364. }
  39365. };
  39366. /**
  39367. * Binds the bones information from the mesh to the effect.
  39368. * @param mesh The mesh we are binding the information to render
  39369. * @param effect The effect we are binding the data to
  39370. */
  39371. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  39372. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  39373. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  39374. if (matrices && effect) {
  39375. effect.setMatrices("mBones", matrices);
  39376. }
  39377. }
  39378. };
  39379. /**
  39380. * Binds the morph targets information from the mesh to the effect.
  39381. * @param abstractMesh The mesh we are binding the information to render
  39382. * @param effect The effect we are binding the data to
  39383. */
  39384. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  39385. var manager = abstractMesh.morphTargetManager;
  39386. if (!abstractMesh || !manager) {
  39387. return;
  39388. }
  39389. effect.setFloatArray("morphTargetInfluences", manager.influences);
  39390. };
  39391. /**
  39392. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  39393. * @param defines The generated defines used in the effect
  39394. * @param effect The effect we are binding the data to
  39395. * @param scene The scene we are willing to render with logarithmic scale for
  39396. */
  39397. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  39398. if (defines["LOGARITHMICDEPTH"]) {
  39399. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  39400. }
  39401. };
  39402. /**
  39403. * Binds the clip plane information from the scene to the effect.
  39404. * @param scene The scene the clip plane information are extracted from
  39405. * @param effect The effect we are binding the data to
  39406. */
  39407. MaterialHelper.BindClipPlane = function (effect, scene) {
  39408. if (scene.clipPlane) {
  39409. var clipPlane = scene.clipPlane;
  39410. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  39411. }
  39412. };
  39413. return MaterialHelper;
  39414. }());
  39415. BABYLON.MaterialHelper = MaterialHelper;
  39416. })(BABYLON || (BABYLON = {}));
  39417. //# sourceMappingURL=babylon.materialHelper.js.map
  39418. "use strict";
  39419. var BABYLON;
  39420. (function (BABYLON) {
  39421. var PushMaterial = /** @class */ (function (_super) {
  39422. __extends(PushMaterial, _super);
  39423. function PushMaterial(name, scene) {
  39424. var _this = _super.call(this, name, scene) || this;
  39425. _this._normalMatrix = new BABYLON.Matrix();
  39426. _this.storeEffectOnSubMeshes = true;
  39427. return _this;
  39428. }
  39429. PushMaterial.prototype.getEffect = function () {
  39430. return this._activeEffect;
  39431. };
  39432. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  39433. if (!mesh) {
  39434. return false;
  39435. }
  39436. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  39437. return true;
  39438. }
  39439. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  39440. };
  39441. /**
  39442. * Binds the given world matrix to the active effect
  39443. *
  39444. * @param world the matrix to bind
  39445. */
  39446. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  39447. this._activeEffect.setMatrix("world", world);
  39448. };
  39449. /**
  39450. * Binds the given normal matrix to the active effect
  39451. *
  39452. * @param normalMatrix the matrix to bind
  39453. */
  39454. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  39455. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  39456. };
  39457. PushMaterial.prototype.bind = function (world, mesh) {
  39458. if (!mesh) {
  39459. return;
  39460. }
  39461. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  39462. };
  39463. PushMaterial.prototype._afterBind = function (mesh, effect) {
  39464. if (effect === void 0) { effect = null; }
  39465. _super.prototype._afterBind.call(this, mesh);
  39466. this.getScene()._cachedEffect = effect;
  39467. };
  39468. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  39469. if (visibility === void 0) { visibility = 1; }
  39470. return scene.isCachedMaterialInvalid(this, effect, visibility);
  39471. };
  39472. return PushMaterial;
  39473. }(BABYLON.Material));
  39474. BABYLON.PushMaterial = PushMaterial;
  39475. })(BABYLON || (BABYLON = {}));
  39476. //# sourceMappingURL=babylon.pushMaterial.js.map
  39477. "use strict";
  39478. var BABYLON;
  39479. (function (BABYLON) {
  39480. /** @ignore */
  39481. var StandardMaterialDefines = /** @class */ (function (_super) {
  39482. __extends(StandardMaterialDefines, _super);
  39483. function StandardMaterialDefines() {
  39484. var _this = _super.call(this) || this;
  39485. _this.MAINUV1 = false;
  39486. _this.MAINUV2 = false;
  39487. _this.DIFFUSE = false;
  39488. _this.DIFFUSEDIRECTUV = 0;
  39489. _this.AMBIENT = false;
  39490. _this.AMBIENTDIRECTUV = 0;
  39491. _this.OPACITY = false;
  39492. _this.OPACITYDIRECTUV = 0;
  39493. _this.OPACITYRGB = false;
  39494. _this.REFLECTION = false;
  39495. _this.EMISSIVE = false;
  39496. _this.EMISSIVEDIRECTUV = 0;
  39497. _this.SPECULAR = false;
  39498. _this.SPECULARDIRECTUV = 0;
  39499. _this.BUMP = false;
  39500. _this.BUMPDIRECTUV = 0;
  39501. _this.PARALLAX = false;
  39502. _this.PARALLAXOCCLUSION = false;
  39503. _this.SPECULAROVERALPHA = false;
  39504. _this.CLIPPLANE = false;
  39505. _this.ALPHATEST = false;
  39506. _this.DEPTHPREPASS = false;
  39507. _this.ALPHAFROMDIFFUSE = false;
  39508. _this.POINTSIZE = false;
  39509. _this.FOG = false;
  39510. _this.SPECULARTERM = false;
  39511. _this.DIFFUSEFRESNEL = false;
  39512. _this.OPACITYFRESNEL = false;
  39513. _this.REFLECTIONFRESNEL = false;
  39514. _this.REFRACTIONFRESNEL = false;
  39515. _this.EMISSIVEFRESNEL = false;
  39516. _this.FRESNEL = false;
  39517. _this.NORMAL = false;
  39518. _this.UV1 = false;
  39519. _this.UV2 = false;
  39520. _this.VERTEXCOLOR = false;
  39521. _this.VERTEXALPHA = false;
  39522. _this.NUM_BONE_INFLUENCERS = 0;
  39523. _this.BonesPerMesh = 0;
  39524. _this.INSTANCES = false;
  39525. _this.GLOSSINESS = false;
  39526. _this.ROUGHNESS = false;
  39527. _this.EMISSIVEASILLUMINATION = false;
  39528. _this.LINKEMISSIVEWITHDIFFUSE = false;
  39529. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  39530. _this.LIGHTMAP = false;
  39531. _this.LIGHTMAPDIRECTUV = 0;
  39532. _this.OBJECTSPACE_NORMALMAP = false;
  39533. _this.USELIGHTMAPASSHADOWMAP = false;
  39534. _this.REFLECTIONMAP_3D = false;
  39535. _this.REFLECTIONMAP_SPHERICAL = false;
  39536. _this.REFLECTIONMAP_PLANAR = false;
  39537. _this.REFLECTIONMAP_CUBIC = false;
  39538. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  39539. _this.REFLECTIONMAP_PROJECTION = false;
  39540. _this.REFLECTIONMAP_SKYBOX = false;
  39541. _this.REFLECTIONMAP_EXPLICIT = false;
  39542. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  39543. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  39544. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  39545. _this.INVERTCUBICMAP = false;
  39546. _this.LOGARITHMICDEPTH = false;
  39547. _this.REFRACTION = false;
  39548. _this.REFRACTIONMAP_3D = false;
  39549. _this.REFLECTIONOVERALPHA = false;
  39550. _this.TWOSIDEDLIGHTING = false;
  39551. _this.SHADOWFLOAT = false;
  39552. _this.MORPHTARGETS = false;
  39553. _this.MORPHTARGETS_NORMAL = false;
  39554. _this.MORPHTARGETS_TANGENT = false;
  39555. _this.NUM_MORPH_INFLUENCERS = 0;
  39556. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  39557. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  39558. _this.IMAGEPROCESSING = false;
  39559. _this.VIGNETTE = false;
  39560. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  39561. _this.VIGNETTEBLENDMODEOPAQUE = false;
  39562. _this.TONEMAPPING = false;
  39563. _this.CONTRAST = false;
  39564. _this.COLORCURVES = false;
  39565. _this.COLORGRADING = false;
  39566. _this.COLORGRADING3D = false;
  39567. _this.SAMPLER3DGREENDEPTH = false;
  39568. _this.SAMPLER3DBGRMAP = false;
  39569. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  39570. _this.EXPOSURE = false;
  39571. _this.GRAIN = false;
  39572. _this.rebuild();
  39573. return _this;
  39574. }
  39575. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  39576. var modes = [
  39577. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  39578. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  39579. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  39580. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  39581. ];
  39582. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  39583. var mode = modes_1[_i];
  39584. this[mode] = (mode === modeToEnable);
  39585. }
  39586. };
  39587. return StandardMaterialDefines;
  39588. }(BABYLON.MaterialDefines));
  39589. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  39590. var StandardMaterial = /** @class */ (function (_super) {
  39591. __extends(StandardMaterial, _super);
  39592. function StandardMaterial(name, scene) {
  39593. var _this = _super.call(this, name, scene) || this;
  39594. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  39595. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  39596. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  39597. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  39598. _this.specularPower = 64;
  39599. _this._useAlphaFromDiffuseTexture = false;
  39600. _this._useEmissiveAsIllumination = false;
  39601. _this._linkEmissiveWithDiffuse = false;
  39602. _this._useSpecularOverAlpha = false;
  39603. _this._useReflectionOverAlpha = false;
  39604. _this._disableLighting = false;
  39605. _this._useObjectSpaceNormalMap = false;
  39606. _this._useParallax = false;
  39607. _this._useParallaxOcclusion = false;
  39608. _this.parallaxScaleBias = 0.05;
  39609. _this._roughness = 0;
  39610. _this.indexOfRefraction = 0.98;
  39611. _this.invertRefractionY = true;
  39612. _this._useLightmapAsShadowmap = false;
  39613. _this._useReflectionFresnelFromSpecular = false;
  39614. _this._useGlossinessFromSpecularMapAlpha = false;
  39615. _this._maxSimultaneousLights = 4;
  39616. /**
  39617. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  39618. */
  39619. _this._invertNormalMapX = false;
  39620. /**
  39621. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  39622. */
  39623. _this._invertNormalMapY = false;
  39624. /**
  39625. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  39626. */
  39627. _this._twoSidedLighting = false;
  39628. _this._renderTargets = new BABYLON.SmartArray(16);
  39629. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  39630. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  39631. // Setup the default processing configuration to the scene.
  39632. _this._attachImageProcessingConfiguration(null);
  39633. _this.getRenderTargetTextures = function () {
  39634. _this._renderTargets.reset();
  39635. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  39636. _this._renderTargets.push(_this._reflectionTexture);
  39637. }
  39638. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  39639. _this._renderTargets.push(_this._refractionTexture);
  39640. }
  39641. return _this._renderTargets;
  39642. };
  39643. return _this;
  39644. }
  39645. ;
  39646. ;
  39647. ;
  39648. ;
  39649. ;
  39650. ;
  39651. ;
  39652. ;
  39653. ;
  39654. ;
  39655. ;
  39656. ;
  39657. ;
  39658. ;
  39659. ;
  39660. ;
  39661. ;
  39662. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  39663. /**
  39664. * Gets the image processing configuration used either in this material.
  39665. */
  39666. get: function () {
  39667. return this._imageProcessingConfiguration;
  39668. },
  39669. /**
  39670. * Sets the Default image processing configuration used either in the this material.
  39671. *
  39672. * If sets to null, the scene one is in use.
  39673. */
  39674. set: function (value) {
  39675. this._attachImageProcessingConfiguration(value);
  39676. // Ensure the effect will be rebuilt.
  39677. this._markAllSubMeshesAsTexturesDirty();
  39678. },
  39679. enumerable: true,
  39680. configurable: true
  39681. });
  39682. /**
  39683. * Attaches a new image processing configuration to the Standard Material.
  39684. * @param configuration
  39685. */
  39686. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  39687. var _this = this;
  39688. if (configuration === this._imageProcessingConfiguration) {
  39689. return;
  39690. }
  39691. // Detaches observer.
  39692. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  39693. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  39694. }
  39695. // Pick the scene configuration if needed.
  39696. if (!configuration) {
  39697. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  39698. }
  39699. else {
  39700. this._imageProcessingConfiguration = configuration;
  39701. }
  39702. // Attaches observer.
  39703. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  39704. _this._markAllSubMeshesAsImageProcessingDirty();
  39705. });
  39706. };
  39707. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  39708. /**
  39709. * Gets wether the color curves effect is enabled.
  39710. */
  39711. get: function () {
  39712. return this.imageProcessingConfiguration.colorCurvesEnabled;
  39713. },
  39714. /**
  39715. * Sets wether the color curves effect is enabled.
  39716. */
  39717. set: function (value) {
  39718. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  39719. },
  39720. enumerable: true,
  39721. configurable: true
  39722. });
  39723. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  39724. /**
  39725. * Gets wether the color grading effect is enabled.
  39726. */
  39727. get: function () {
  39728. return this.imageProcessingConfiguration.colorGradingEnabled;
  39729. },
  39730. /**
  39731. * Gets wether the color grading effect is enabled.
  39732. */
  39733. set: function (value) {
  39734. this.imageProcessingConfiguration.colorGradingEnabled = value;
  39735. },
  39736. enumerable: true,
  39737. configurable: true
  39738. });
  39739. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  39740. /**
  39741. * Gets wether tonemapping is enabled or not.
  39742. */
  39743. get: function () {
  39744. return this._imageProcessingConfiguration.toneMappingEnabled;
  39745. },
  39746. /**
  39747. * Sets wether tonemapping is enabled or not
  39748. */
  39749. set: function (value) {
  39750. this._imageProcessingConfiguration.toneMappingEnabled = value;
  39751. },
  39752. enumerable: true,
  39753. configurable: true
  39754. });
  39755. ;
  39756. ;
  39757. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  39758. /**
  39759. * The camera exposure used on this material.
  39760. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  39761. * This corresponds to a photographic exposure.
  39762. */
  39763. get: function () {
  39764. return this._imageProcessingConfiguration.exposure;
  39765. },
  39766. /**
  39767. * The camera exposure used on this material.
  39768. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  39769. * This corresponds to a photographic exposure.
  39770. */
  39771. set: function (value) {
  39772. this._imageProcessingConfiguration.exposure = value;
  39773. },
  39774. enumerable: true,
  39775. configurable: true
  39776. });
  39777. ;
  39778. ;
  39779. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  39780. /**
  39781. * Gets The camera contrast used on this material.
  39782. */
  39783. get: function () {
  39784. return this._imageProcessingConfiguration.contrast;
  39785. },
  39786. /**
  39787. * Sets The camera contrast used on this material.
  39788. */
  39789. set: function (value) {
  39790. this._imageProcessingConfiguration.contrast = value;
  39791. },
  39792. enumerable: true,
  39793. configurable: true
  39794. });
  39795. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  39796. /**
  39797. * Gets the Color Grading 2D Lookup Texture.
  39798. */
  39799. get: function () {
  39800. return this._imageProcessingConfiguration.colorGradingTexture;
  39801. },
  39802. /**
  39803. * Sets the Color Grading 2D Lookup Texture.
  39804. */
  39805. set: function (value) {
  39806. this._imageProcessingConfiguration.colorGradingTexture = value;
  39807. },
  39808. enumerable: true,
  39809. configurable: true
  39810. });
  39811. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  39812. /**
  39813. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39814. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39815. * 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;
  39816. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39817. */
  39818. get: function () {
  39819. return this._imageProcessingConfiguration.colorCurves;
  39820. },
  39821. /**
  39822. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39823. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39824. * 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;
  39825. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39826. */
  39827. set: function (value) {
  39828. this._imageProcessingConfiguration.colorCurves = value;
  39829. },
  39830. enumerable: true,
  39831. configurable: true
  39832. });
  39833. StandardMaterial.prototype.getClassName = function () {
  39834. return "StandardMaterial";
  39835. };
  39836. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  39837. get: function () {
  39838. return this._useLogarithmicDepth;
  39839. },
  39840. set: function (value) {
  39841. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  39842. this._markAllSubMeshesAsMiscDirty();
  39843. },
  39844. enumerable: true,
  39845. configurable: true
  39846. });
  39847. StandardMaterial.prototype.needAlphaBlending = function () {
  39848. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  39849. };
  39850. StandardMaterial.prototype.needAlphaTesting = function () {
  39851. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  39852. };
  39853. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  39854. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  39855. };
  39856. StandardMaterial.prototype.getAlphaTestTexture = function () {
  39857. return this._diffuseTexture;
  39858. };
  39859. /**
  39860. * Child classes can use it to update shaders
  39861. */
  39862. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  39863. if (useInstances === void 0) { useInstances = false; }
  39864. if (subMesh.effect && this.isFrozen) {
  39865. if (this._wasPreviouslyReady && subMesh.effect) {
  39866. return true;
  39867. }
  39868. }
  39869. if (!subMesh._materialDefines) {
  39870. subMesh._materialDefines = new StandardMaterialDefines();
  39871. }
  39872. var scene = this.getScene();
  39873. var defines = subMesh._materialDefines;
  39874. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  39875. if (defines._renderId === scene.getRenderId()) {
  39876. return true;
  39877. }
  39878. }
  39879. var engine = scene.getEngine();
  39880. // Lights
  39881. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  39882. // Textures
  39883. if (defines._areTexturesDirty) {
  39884. defines._needUVs = false;
  39885. defines.MAINUV1 = false;
  39886. defines.MAINUV2 = false;
  39887. if (scene.texturesEnabled) {
  39888. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39889. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  39890. return false;
  39891. }
  39892. else {
  39893. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  39894. }
  39895. }
  39896. else {
  39897. defines.DIFFUSE = false;
  39898. }
  39899. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39900. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  39901. return false;
  39902. }
  39903. else {
  39904. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  39905. }
  39906. }
  39907. else {
  39908. defines.AMBIENT = false;
  39909. }
  39910. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39911. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  39912. return false;
  39913. }
  39914. else {
  39915. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  39916. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  39917. }
  39918. }
  39919. else {
  39920. defines.OPACITY = false;
  39921. }
  39922. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39923. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  39924. return false;
  39925. }
  39926. else {
  39927. defines._needNormals = true;
  39928. defines.REFLECTION = true;
  39929. defines.ROUGHNESS = (this._roughness > 0);
  39930. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  39931. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  39932. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  39933. switch (this._reflectionTexture.coordinatesMode) {
  39934. case BABYLON.Texture.CUBIC_MODE:
  39935. case BABYLON.Texture.INVCUBIC_MODE:
  39936. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  39937. break;
  39938. case BABYLON.Texture.EXPLICIT_MODE:
  39939. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  39940. break;
  39941. case BABYLON.Texture.PLANAR_MODE:
  39942. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  39943. break;
  39944. case BABYLON.Texture.PROJECTION_MODE:
  39945. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  39946. break;
  39947. case BABYLON.Texture.SKYBOX_MODE:
  39948. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  39949. break;
  39950. case BABYLON.Texture.SPHERICAL_MODE:
  39951. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  39952. break;
  39953. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  39954. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  39955. break;
  39956. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  39957. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  39958. break;
  39959. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  39960. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  39961. break;
  39962. }
  39963. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  39964. }
  39965. }
  39966. else {
  39967. defines.REFLECTION = false;
  39968. }
  39969. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39970. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  39971. return false;
  39972. }
  39973. else {
  39974. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  39975. }
  39976. }
  39977. else {
  39978. defines.EMISSIVE = false;
  39979. }
  39980. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39981. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  39982. return false;
  39983. }
  39984. else {
  39985. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  39986. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  39987. }
  39988. }
  39989. else {
  39990. defines.LIGHTMAP = false;
  39991. }
  39992. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39993. if (!this._specularTexture.isReadyOrNotBlocking()) {
  39994. return false;
  39995. }
  39996. else {
  39997. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  39998. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  39999. }
  40000. }
  40001. else {
  40002. defines.SPECULAR = false;
  40003. }
  40004. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  40005. // Bump texure can not be not blocking.
  40006. if (!this._bumpTexture.isReady()) {
  40007. return false;
  40008. }
  40009. else {
  40010. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  40011. defines.PARALLAX = this._useParallax;
  40012. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  40013. }
  40014. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  40015. }
  40016. else {
  40017. defines.BUMP = false;
  40018. }
  40019. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  40020. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  40021. return false;
  40022. }
  40023. else {
  40024. defines._needUVs = true;
  40025. defines.REFRACTION = true;
  40026. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  40027. }
  40028. }
  40029. else {
  40030. defines.REFRACTION = false;
  40031. }
  40032. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  40033. }
  40034. else {
  40035. defines.DIFFUSE = false;
  40036. defines.AMBIENT = false;
  40037. defines.OPACITY = false;
  40038. defines.REFLECTION = false;
  40039. defines.EMISSIVE = false;
  40040. defines.LIGHTMAP = false;
  40041. defines.BUMP = false;
  40042. defines.REFRACTION = false;
  40043. }
  40044. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  40045. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  40046. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  40047. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  40048. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  40049. }
  40050. if (defines._areImageProcessingDirty) {
  40051. if (!this._imageProcessingConfiguration.isReady()) {
  40052. return false;
  40053. }
  40054. this._imageProcessingConfiguration.prepareDefines(defines);
  40055. }
  40056. if (defines._areFresnelDirty) {
  40057. if (StandardMaterial.FresnelEnabled) {
  40058. // Fresnel
  40059. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  40060. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  40061. this._reflectionFresnelParameters) {
  40062. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  40063. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  40064. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  40065. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  40066. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  40067. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  40068. defines._needNormals = true;
  40069. defines.FRESNEL = true;
  40070. }
  40071. }
  40072. else {
  40073. defines.FRESNEL = false;
  40074. }
  40075. }
  40076. // Misc.
  40077. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  40078. // Attribs
  40079. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  40080. // Values that need to be evaluated on every frame
  40081. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  40082. // Get correct effect
  40083. if (defines.isDirty) {
  40084. defines.markAsProcessed();
  40085. scene.resetCachedMaterial();
  40086. // Fallbacks
  40087. var fallbacks = new BABYLON.EffectFallbacks();
  40088. if (defines.REFLECTION) {
  40089. fallbacks.addFallback(0, "REFLECTION");
  40090. }
  40091. if (defines.SPECULAR) {
  40092. fallbacks.addFallback(0, "SPECULAR");
  40093. }
  40094. if (defines.BUMP) {
  40095. fallbacks.addFallback(0, "BUMP");
  40096. }
  40097. if (defines.PARALLAX) {
  40098. fallbacks.addFallback(1, "PARALLAX");
  40099. }
  40100. if (defines.PARALLAXOCCLUSION) {
  40101. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  40102. }
  40103. if (defines.SPECULAROVERALPHA) {
  40104. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  40105. }
  40106. if (defines.FOG) {
  40107. fallbacks.addFallback(1, "FOG");
  40108. }
  40109. if (defines.POINTSIZE) {
  40110. fallbacks.addFallback(0, "POINTSIZE");
  40111. }
  40112. if (defines.LOGARITHMICDEPTH) {
  40113. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  40114. }
  40115. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  40116. if (defines.SPECULARTERM) {
  40117. fallbacks.addFallback(0, "SPECULARTERM");
  40118. }
  40119. if (defines.DIFFUSEFRESNEL) {
  40120. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  40121. }
  40122. if (defines.OPACITYFRESNEL) {
  40123. fallbacks.addFallback(2, "OPACITYFRESNEL");
  40124. }
  40125. if (defines.REFLECTIONFRESNEL) {
  40126. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  40127. }
  40128. if (defines.EMISSIVEFRESNEL) {
  40129. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  40130. }
  40131. if (defines.FRESNEL) {
  40132. fallbacks.addFallback(4, "FRESNEL");
  40133. }
  40134. //Attributes
  40135. var attribs = [BABYLON.VertexBuffer.PositionKind];
  40136. if (defines.NORMAL) {
  40137. attribs.push(BABYLON.VertexBuffer.NormalKind);
  40138. }
  40139. if (defines.UV1) {
  40140. attribs.push(BABYLON.VertexBuffer.UVKind);
  40141. }
  40142. if (defines.UV2) {
  40143. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  40144. }
  40145. if (defines.VERTEXCOLOR) {
  40146. attribs.push(BABYLON.VertexBuffer.ColorKind);
  40147. }
  40148. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  40149. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  40150. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  40151. var shaderName = "default";
  40152. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  40153. "vFogInfos", "vFogColor", "pointSize",
  40154. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  40155. "mBones",
  40156. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  40157. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  40158. "vReflectionPosition", "vReflectionSize",
  40159. "logarithmicDepthConstant", "vTangentSpaceParams"
  40160. ];
  40161. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  40162. var uniformBuffers = ["Material", "Scene"];
  40163. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  40164. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  40165. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  40166. uniformsNames: uniforms,
  40167. uniformBuffersNames: uniformBuffers,
  40168. samplers: samplers,
  40169. defines: defines,
  40170. maxSimultaneousLights: this._maxSimultaneousLights
  40171. });
  40172. if (this.customShaderNameResolve) {
  40173. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  40174. }
  40175. var join = defines.toString();
  40176. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  40177. attributes: attribs,
  40178. uniformsNames: uniforms,
  40179. uniformBuffersNames: uniformBuffers,
  40180. samplers: samplers,
  40181. defines: join,
  40182. fallbacks: fallbacks,
  40183. onCompiled: this.onCompiled,
  40184. onError: this.onError,
  40185. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  40186. }, engine), defines);
  40187. this.buildUniformLayout();
  40188. }
  40189. if (!subMesh.effect || !subMesh.effect.isReady()) {
  40190. return false;
  40191. }
  40192. defines._renderId = scene.getRenderId();
  40193. this._wasPreviouslyReady = true;
  40194. return true;
  40195. };
  40196. StandardMaterial.prototype.buildUniformLayout = function () {
  40197. // Order is important !
  40198. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  40199. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  40200. this._uniformBuffer.addUniform("opacityParts", 4);
  40201. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  40202. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  40203. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  40204. this._uniformBuffer.addUniform("refractionRightColor", 4);
  40205. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  40206. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  40207. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  40208. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  40209. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  40210. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  40211. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  40212. this._uniformBuffer.addUniform("vReflectionSize", 3);
  40213. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  40214. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  40215. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  40216. this._uniformBuffer.addUniform("vBumpInfos", 3);
  40217. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  40218. this._uniformBuffer.addUniform("ambientMatrix", 16);
  40219. this._uniformBuffer.addUniform("opacityMatrix", 16);
  40220. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  40221. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  40222. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  40223. this._uniformBuffer.addUniform("specularMatrix", 16);
  40224. this._uniformBuffer.addUniform("bumpMatrix", 16);
  40225. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  40226. this._uniformBuffer.addUniform("refractionMatrix", 16);
  40227. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  40228. this._uniformBuffer.addUniform("vSpecularColor", 4);
  40229. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  40230. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  40231. this._uniformBuffer.addUniform("pointSize", 1);
  40232. this._uniformBuffer.create();
  40233. };
  40234. StandardMaterial.prototype.unbind = function () {
  40235. if (this._activeEffect) {
  40236. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  40237. this._activeEffect.setTexture("reflection2DSampler", null);
  40238. }
  40239. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  40240. this._activeEffect.setTexture("refraction2DSampler", null);
  40241. }
  40242. }
  40243. _super.prototype.unbind.call(this);
  40244. };
  40245. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  40246. var scene = this.getScene();
  40247. var defines = subMesh._materialDefines;
  40248. if (!defines) {
  40249. return;
  40250. }
  40251. var effect = subMesh.effect;
  40252. if (!effect) {
  40253. return;
  40254. }
  40255. this._activeEffect = effect;
  40256. // Matrices
  40257. this.bindOnlyWorldMatrix(world);
  40258. // Normal Matrix
  40259. if (defines.OBJECTSPACE_NORMALMAP) {
  40260. world.toNormalMatrix(this._normalMatrix);
  40261. this.bindOnlyNormalMatrix(this._normalMatrix);
  40262. }
  40263. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  40264. // Bones
  40265. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  40266. if (mustRebind) {
  40267. this._uniformBuffer.bindToEffect(effect, "Material");
  40268. this.bindViewProjection(effect);
  40269. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  40270. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  40271. // Fresnel
  40272. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  40273. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  40274. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  40275. }
  40276. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  40277. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  40278. }
  40279. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  40280. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  40281. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  40282. }
  40283. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  40284. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  40285. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  40286. }
  40287. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  40288. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  40289. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  40290. }
  40291. }
  40292. // Textures
  40293. if (scene.texturesEnabled) {
  40294. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  40295. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  40296. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  40297. }
  40298. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  40299. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  40300. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  40301. }
  40302. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  40303. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  40304. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  40305. }
  40306. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  40307. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  40308. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  40309. if (this._reflectionTexture.boundingBoxSize) {
  40310. var cubeTexture = this._reflectionTexture;
  40311. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  40312. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  40313. }
  40314. }
  40315. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  40316. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  40317. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  40318. }
  40319. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  40320. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  40321. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  40322. }
  40323. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  40324. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  40325. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  40326. }
  40327. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  40328. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  40329. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  40330. if (scene._mirroredCameraPosition) {
  40331. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  40332. }
  40333. else {
  40334. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  40335. }
  40336. }
  40337. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  40338. var depth = 1.0;
  40339. if (!this._refractionTexture.isCube) {
  40340. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  40341. if (this._refractionTexture.depth) {
  40342. depth = this._refractionTexture.depth;
  40343. }
  40344. }
  40345. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  40346. }
  40347. }
  40348. // Point size
  40349. if (this.pointsCloud) {
  40350. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  40351. }
  40352. if (defines.SPECULARTERM) {
  40353. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  40354. }
  40355. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  40356. // Diffuse
  40357. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  40358. }
  40359. // Textures
  40360. if (scene.texturesEnabled) {
  40361. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  40362. effect.setTexture("diffuseSampler", this._diffuseTexture);
  40363. }
  40364. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  40365. effect.setTexture("ambientSampler", this._ambientTexture);
  40366. }
  40367. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  40368. effect.setTexture("opacitySampler", this._opacityTexture);
  40369. }
  40370. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  40371. if (this._reflectionTexture.isCube) {
  40372. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  40373. }
  40374. else {
  40375. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  40376. }
  40377. }
  40378. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  40379. effect.setTexture("emissiveSampler", this._emissiveTexture);
  40380. }
  40381. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  40382. effect.setTexture("lightmapSampler", this._lightmapTexture);
  40383. }
  40384. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  40385. effect.setTexture("specularSampler", this._specularTexture);
  40386. }
  40387. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  40388. effect.setTexture("bumpSampler", this._bumpTexture);
  40389. }
  40390. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  40391. var depth = 1.0;
  40392. if (this._refractionTexture.isCube) {
  40393. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  40394. }
  40395. else {
  40396. effect.setTexture("refraction2DSampler", this._refractionTexture);
  40397. }
  40398. }
  40399. }
  40400. // Clip plane
  40401. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  40402. // Colors
  40403. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  40404. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  40405. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  40406. }
  40407. if (mustRebind || !this.isFrozen) {
  40408. // Lights
  40409. if (scene.lightsEnabled && !this._disableLighting) {
  40410. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  40411. }
  40412. // View
  40413. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  40414. this.bindView(effect);
  40415. }
  40416. // Fog
  40417. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  40418. // Morph targets
  40419. if (defines.NUM_MORPH_INFLUENCERS) {
  40420. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  40421. }
  40422. // Log. depth
  40423. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  40424. // image processing
  40425. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  40426. this._imageProcessingConfiguration.bind(this._activeEffect);
  40427. }
  40428. }
  40429. this._uniformBuffer.update();
  40430. this._afterBind(mesh, this._activeEffect);
  40431. };
  40432. StandardMaterial.prototype.getAnimatables = function () {
  40433. var results = [];
  40434. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  40435. results.push(this._diffuseTexture);
  40436. }
  40437. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  40438. results.push(this._ambientTexture);
  40439. }
  40440. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  40441. results.push(this._opacityTexture);
  40442. }
  40443. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  40444. results.push(this._reflectionTexture);
  40445. }
  40446. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  40447. results.push(this._emissiveTexture);
  40448. }
  40449. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  40450. results.push(this._specularTexture);
  40451. }
  40452. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  40453. results.push(this._bumpTexture);
  40454. }
  40455. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  40456. results.push(this._lightmapTexture);
  40457. }
  40458. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  40459. results.push(this._refractionTexture);
  40460. }
  40461. return results;
  40462. };
  40463. StandardMaterial.prototype.getActiveTextures = function () {
  40464. var activeTextures = _super.prototype.getActiveTextures.call(this);
  40465. if (this._diffuseTexture) {
  40466. activeTextures.push(this._diffuseTexture);
  40467. }
  40468. if (this._ambientTexture) {
  40469. activeTextures.push(this._ambientTexture);
  40470. }
  40471. if (this._opacityTexture) {
  40472. activeTextures.push(this._opacityTexture);
  40473. }
  40474. if (this._reflectionTexture) {
  40475. activeTextures.push(this._reflectionTexture);
  40476. }
  40477. if (this._emissiveTexture) {
  40478. activeTextures.push(this._emissiveTexture);
  40479. }
  40480. if (this._specularTexture) {
  40481. activeTextures.push(this._specularTexture);
  40482. }
  40483. if (this._bumpTexture) {
  40484. activeTextures.push(this._bumpTexture);
  40485. }
  40486. if (this._lightmapTexture) {
  40487. activeTextures.push(this._lightmapTexture);
  40488. }
  40489. if (this._refractionTexture) {
  40490. activeTextures.push(this._refractionTexture);
  40491. }
  40492. return activeTextures;
  40493. };
  40494. StandardMaterial.prototype.hasTexture = function (texture) {
  40495. if (_super.prototype.hasTexture.call(this, texture)) {
  40496. return true;
  40497. }
  40498. if (this._diffuseTexture === texture) {
  40499. return true;
  40500. }
  40501. if (this._ambientTexture === texture) {
  40502. return true;
  40503. }
  40504. if (this._opacityTexture === texture) {
  40505. return true;
  40506. }
  40507. if (this._reflectionTexture === texture) {
  40508. return true;
  40509. }
  40510. if (this._emissiveTexture === texture) {
  40511. return true;
  40512. }
  40513. if (this._specularTexture === texture) {
  40514. return true;
  40515. }
  40516. if (this._bumpTexture === texture) {
  40517. return true;
  40518. }
  40519. if (this._lightmapTexture === texture) {
  40520. return true;
  40521. }
  40522. if (this._refractionTexture === texture) {
  40523. return true;
  40524. }
  40525. return false;
  40526. };
  40527. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  40528. if (forceDisposeTextures) {
  40529. if (this._diffuseTexture) {
  40530. this._diffuseTexture.dispose();
  40531. }
  40532. if (this._ambientTexture) {
  40533. this._ambientTexture.dispose();
  40534. }
  40535. if (this._opacityTexture) {
  40536. this._opacityTexture.dispose();
  40537. }
  40538. if (this._reflectionTexture) {
  40539. this._reflectionTexture.dispose();
  40540. }
  40541. if (this._emissiveTexture) {
  40542. this._emissiveTexture.dispose();
  40543. }
  40544. if (this._specularTexture) {
  40545. this._specularTexture.dispose();
  40546. }
  40547. if (this._bumpTexture) {
  40548. this._bumpTexture.dispose();
  40549. }
  40550. if (this._lightmapTexture) {
  40551. this._lightmapTexture.dispose();
  40552. }
  40553. if (this._refractionTexture) {
  40554. this._refractionTexture.dispose();
  40555. }
  40556. }
  40557. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  40558. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  40559. }
  40560. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  40561. };
  40562. StandardMaterial.prototype.clone = function (name) {
  40563. var _this = this;
  40564. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  40565. result.name = name;
  40566. result.id = name;
  40567. return result;
  40568. };
  40569. StandardMaterial.prototype.serialize = function () {
  40570. return BABYLON.SerializationHelper.Serialize(this);
  40571. };
  40572. // Statics
  40573. StandardMaterial.Parse = function (source, scene, rootUrl) {
  40574. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  40575. };
  40576. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  40577. get: function () {
  40578. return StandardMaterial._DiffuseTextureEnabled;
  40579. },
  40580. set: function (value) {
  40581. if (StandardMaterial._DiffuseTextureEnabled === value) {
  40582. return;
  40583. }
  40584. StandardMaterial._DiffuseTextureEnabled = value;
  40585. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40586. },
  40587. enumerable: true,
  40588. configurable: true
  40589. });
  40590. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  40591. get: function () {
  40592. return StandardMaterial._AmbientTextureEnabled;
  40593. },
  40594. set: function (value) {
  40595. if (StandardMaterial._AmbientTextureEnabled === value) {
  40596. return;
  40597. }
  40598. StandardMaterial._AmbientTextureEnabled = value;
  40599. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40600. },
  40601. enumerable: true,
  40602. configurable: true
  40603. });
  40604. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  40605. get: function () {
  40606. return StandardMaterial._OpacityTextureEnabled;
  40607. },
  40608. set: function (value) {
  40609. if (StandardMaterial._OpacityTextureEnabled === value) {
  40610. return;
  40611. }
  40612. StandardMaterial._OpacityTextureEnabled = value;
  40613. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40614. },
  40615. enumerable: true,
  40616. configurable: true
  40617. });
  40618. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  40619. get: function () {
  40620. return StandardMaterial._ReflectionTextureEnabled;
  40621. },
  40622. set: function (value) {
  40623. if (StandardMaterial._ReflectionTextureEnabled === value) {
  40624. return;
  40625. }
  40626. StandardMaterial._ReflectionTextureEnabled = value;
  40627. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40628. },
  40629. enumerable: true,
  40630. configurable: true
  40631. });
  40632. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  40633. get: function () {
  40634. return StandardMaterial._EmissiveTextureEnabled;
  40635. },
  40636. set: function (value) {
  40637. if (StandardMaterial._EmissiveTextureEnabled === value) {
  40638. return;
  40639. }
  40640. StandardMaterial._EmissiveTextureEnabled = value;
  40641. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40642. },
  40643. enumerable: true,
  40644. configurable: true
  40645. });
  40646. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  40647. get: function () {
  40648. return StandardMaterial._SpecularTextureEnabled;
  40649. },
  40650. set: function (value) {
  40651. if (StandardMaterial._SpecularTextureEnabled === value) {
  40652. return;
  40653. }
  40654. StandardMaterial._SpecularTextureEnabled = value;
  40655. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40656. },
  40657. enumerable: true,
  40658. configurable: true
  40659. });
  40660. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  40661. get: function () {
  40662. return StandardMaterial._BumpTextureEnabled;
  40663. },
  40664. set: function (value) {
  40665. if (StandardMaterial._BumpTextureEnabled === value) {
  40666. return;
  40667. }
  40668. StandardMaterial._BumpTextureEnabled = value;
  40669. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40670. },
  40671. enumerable: true,
  40672. configurable: true
  40673. });
  40674. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  40675. get: function () {
  40676. return StandardMaterial._LightmapTextureEnabled;
  40677. },
  40678. set: function (value) {
  40679. if (StandardMaterial._LightmapTextureEnabled === value) {
  40680. return;
  40681. }
  40682. StandardMaterial._LightmapTextureEnabled = value;
  40683. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40684. },
  40685. enumerable: true,
  40686. configurable: true
  40687. });
  40688. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  40689. get: function () {
  40690. return StandardMaterial._RefractionTextureEnabled;
  40691. },
  40692. set: function (value) {
  40693. if (StandardMaterial._RefractionTextureEnabled === value) {
  40694. return;
  40695. }
  40696. StandardMaterial._RefractionTextureEnabled = value;
  40697. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40698. },
  40699. enumerable: true,
  40700. configurable: true
  40701. });
  40702. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  40703. get: function () {
  40704. return StandardMaterial._ColorGradingTextureEnabled;
  40705. },
  40706. set: function (value) {
  40707. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  40708. return;
  40709. }
  40710. StandardMaterial._ColorGradingTextureEnabled = value;
  40711. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40712. },
  40713. enumerable: true,
  40714. configurable: true
  40715. });
  40716. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  40717. get: function () {
  40718. return StandardMaterial._FresnelEnabled;
  40719. },
  40720. set: function (value) {
  40721. if (StandardMaterial._FresnelEnabled === value) {
  40722. return;
  40723. }
  40724. StandardMaterial._FresnelEnabled = value;
  40725. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  40726. },
  40727. enumerable: true,
  40728. configurable: true
  40729. });
  40730. // Flags used to enable or disable a type of texture for all Standard Materials
  40731. StandardMaterial._DiffuseTextureEnabled = true;
  40732. StandardMaterial._AmbientTextureEnabled = true;
  40733. StandardMaterial._OpacityTextureEnabled = true;
  40734. StandardMaterial._ReflectionTextureEnabled = true;
  40735. StandardMaterial._EmissiveTextureEnabled = true;
  40736. StandardMaterial._SpecularTextureEnabled = true;
  40737. StandardMaterial._BumpTextureEnabled = true;
  40738. StandardMaterial._LightmapTextureEnabled = true;
  40739. StandardMaterial._RefractionTextureEnabled = true;
  40740. StandardMaterial._ColorGradingTextureEnabled = true;
  40741. StandardMaterial._FresnelEnabled = true;
  40742. __decorate([
  40743. BABYLON.serializeAsTexture("diffuseTexture")
  40744. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  40745. __decorate([
  40746. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  40747. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  40748. __decorate([
  40749. BABYLON.serializeAsTexture("ambientTexture")
  40750. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  40751. __decorate([
  40752. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40753. ], StandardMaterial.prototype, "ambientTexture", void 0);
  40754. __decorate([
  40755. BABYLON.serializeAsTexture("opacityTexture")
  40756. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  40757. __decorate([
  40758. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  40759. ], StandardMaterial.prototype, "opacityTexture", void 0);
  40760. __decorate([
  40761. BABYLON.serializeAsTexture("reflectionTexture")
  40762. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  40763. __decorate([
  40764. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40765. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  40766. __decorate([
  40767. BABYLON.serializeAsTexture("emissiveTexture")
  40768. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  40769. __decorate([
  40770. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40771. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  40772. __decorate([
  40773. BABYLON.serializeAsTexture("specularTexture")
  40774. ], StandardMaterial.prototype, "_specularTexture", void 0);
  40775. __decorate([
  40776. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40777. ], StandardMaterial.prototype, "specularTexture", void 0);
  40778. __decorate([
  40779. BABYLON.serializeAsTexture("bumpTexture")
  40780. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  40781. __decorate([
  40782. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40783. ], StandardMaterial.prototype, "bumpTexture", void 0);
  40784. __decorate([
  40785. BABYLON.serializeAsTexture("lightmapTexture")
  40786. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  40787. __decorate([
  40788. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40789. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  40790. __decorate([
  40791. BABYLON.serializeAsTexture("refractionTexture")
  40792. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  40793. __decorate([
  40794. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40795. ], StandardMaterial.prototype, "refractionTexture", void 0);
  40796. __decorate([
  40797. BABYLON.serializeAsColor3("ambient")
  40798. ], StandardMaterial.prototype, "ambientColor", void 0);
  40799. __decorate([
  40800. BABYLON.serializeAsColor3("diffuse")
  40801. ], StandardMaterial.prototype, "diffuseColor", void 0);
  40802. __decorate([
  40803. BABYLON.serializeAsColor3("specular")
  40804. ], StandardMaterial.prototype, "specularColor", void 0);
  40805. __decorate([
  40806. BABYLON.serializeAsColor3("emissive")
  40807. ], StandardMaterial.prototype, "emissiveColor", void 0);
  40808. __decorate([
  40809. BABYLON.serialize()
  40810. ], StandardMaterial.prototype, "specularPower", void 0);
  40811. __decorate([
  40812. BABYLON.serialize("useAlphaFromDiffuseTexture")
  40813. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  40814. __decorate([
  40815. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40816. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  40817. __decorate([
  40818. BABYLON.serialize("useEmissiveAsIllumination")
  40819. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  40820. __decorate([
  40821. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40822. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  40823. __decorate([
  40824. BABYLON.serialize("linkEmissiveWithDiffuse")
  40825. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  40826. __decorate([
  40827. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40828. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  40829. __decorate([
  40830. BABYLON.serialize("useSpecularOverAlpha")
  40831. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  40832. __decorate([
  40833. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40834. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  40835. __decorate([
  40836. BABYLON.serialize("useReflectionOverAlpha")
  40837. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  40838. __decorate([
  40839. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40840. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  40841. __decorate([
  40842. BABYLON.serialize("disableLighting")
  40843. ], StandardMaterial.prototype, "_disableLighting", void 0);
  40844. __decorate([
  40845. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40846. ], StandardMaterial.prototype, "disableLighting", void 0);
  40847. __decorate([
  40848. BABYLON.serialize("useObjectSpaceNormalMap")
  40849. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  40850. __decorate([
  40851. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40852. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  40853. __decorate([
  40854. BABYLON.serialize("useParallax")
  40855. ], StandardMaterial.prototype, "_useParallax", void 0);
  40856. __decorate([
  40857. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40858. ], StandardMaterial.prototype, "useParallax", void 0);
  40859. __decorate([
  40860. BABYLON.serialize("useParallaxOcclusion")
  40861. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  40862. __decorate([
  40863. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40864. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  40865. __decorate([
  40866. BABYLON.serialize()
  40867. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  40868. __decorate([
  40869. BABYLON.serialize("roughness")
  40870. ], StandardMaterial.prototype, "_roughness", void 0);
  40871. __decorate([
  40872. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40873. ], StandardMaterial.prototype, "roughness", void 0);
  40874. __decorate([
  40875. BABYLON.serialize()
  40876. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  40877. __decorate([
  40878. BABYLON.serialize()
  40879. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  40880. __decorate([
  40881. BABYLON.serialize("useLightmapAsShadowmap")
  40882. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  40883. __decorate([
  40884. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40885. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  40886. __decorate([
  40887. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  40888. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  40889. __decorate([
  40890. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40891. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  40892. __decorate([
  40893. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  40894. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  40895. __decorate([
  40896. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  40897. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  40898. __decorate([
  40899. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  40900. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  40901. __decorate([
  40902. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40903. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  40904. __decorate([
  40905. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  40906. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  40907. __decorate([
  40908. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40909. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  40910. __decorate([
  40911. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  40912. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  40913. __decorate([
  40914. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40915. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  40916. __decorate([
  40917. BABYLON.serialize("useReflectionFresnelFromSpecular")
  40918. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  40919. __decorate([
  40920. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40921. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  40922. __decorate([
  40923. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  40924. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  40925. __decorate([
  40926. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40927. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  40928. __decorate([
  40929. BABYLON.serialize("maxSimultaneousLights")
  40930. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  40931. __decorate([
  40932. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40933. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  40934. __decorate([
  40935. BABYLON.serialize("invertNormalMapX")
  40936. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  40937. __decorate([
  40938. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40939. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  40940. __decorate([
  40941. BABYLON.serialize("invertNormalMapY")
  40942. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  40943. __decorate([
  40944. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40945. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  40946. __decorate([
  40947. BABYLON.serialize("twoSidedLighting")
  40948. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  40949. __decorate([
  40950. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40951. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  40952. __decorate([
  40953. BABYLON.serialize()
  40954. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  40955. return StandardMaterial;
  40956. }(BABYLON.PushMaterial));
  40957. BABYLON.StandardMaterial = StandardMaterial;
  40958. })(BABYLON || (BABYLON = {}));
  40959. //# sourceMappingURL=babylon.standardMaterial.js.map
  40960. "use strict";
  40961. var BABYLON;
  40962. (function (BABYLON) {
  40963. /**
  40964. * Manages the defines for the PBR Material.
  40965. */
  40966. var PBRMaterialDefines = /** @class */ (function (_super) {
  40967. __extends(PBRMaterialDefines, _super);
  40968. /**
  40969. * Initializes the PBR Material defines.
  40970. */
  40971. function PBRMaterialDefines() {
  40972. var _this = _super.call(this) || this;
  40973. _this.PBR = true;
  40974. _this.MAINUV1 = false;
  40975. _this.MAINUV2 = false;
  40976. _this.UV1 = false;
  40977. _this.UV2 = false;
  40978. _this.ALBEDO = false;
  40979. _this.ALBEDODIRECTUV = 0;
  40980. _this.VERTEXCOLOR = false;
  40981. _this.AMBIENT = false;
  40982. _this.AMBIENTDIRECTUV = 0;
  40983. _this.AMBIENTINGRAYSCALE = false;
  40984. _this.OPACITY = false;
  40985. _this.VERTEXALPHA = false;
  40986. _this.OPACITYDIRECTUV = 0;
  40987. _this.OPACITYRGB = false;
  40988. _this.ALPHATEST = false;
  40989. _this.DEPTHPREPASS = false;
  40990. _this.ALPHABLEND = false;
  40991. _this.ALPHAFROMALBEDO = false;
  40992. _this.ALPHATESTVALUE = "0.5";
  40993. _this.SPECULAROVERALPHA = false;
  40994. _this.RADIANCEOVERALPHA = false;
  40995. _this.ALPHAFRESNEL = false;
  40996. _this.LINEARALPHAFRESNEL = false;
  40997. _this.PREMULTIPLYALPHA = false;
  40998. _this.EMISSIVE = false;
  40999. _this.EMISSIVEDIRECTUV = 0;
  41000. _this.REFLECTIVITY = false;
  41001. _this.REFLECTIVITYDIRECTUV = 0;
  41002. _this.SPECULARTERM = false;
  41003. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  41004. _this.MICROSURFACEAUTOMATIC = false;
  41005. _this.LODBASEDMICROSFURACE = false;
  41006. _this.MICROSURFACEMAP = false;
  41007. _this.MICROSURFACEMAPDIRECTUV = 0;
  41008. _this.METALLICWORKFLOW = false;
  41009. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  41010. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  41011. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  41012. _this.AOSTOREINMETALMAPRED = false;
  41013. _this.ENVIRONMENTBRDF = false;
  41014. _this.NORMAL = false;
  41015. _this.TANGENT = false;
  41016. _this.BUMP = false;
  41017. _this.BUMPDIRECTUV = 0;
  41018. _this.OBJECTSPACE_NORMALMAP = false;
  41019. _this.PARALLAX = false;
  41020. _this.PARALLAXOCCLUSION = false;
  41021. _this.NORMALXYSCALE = true;
  41022. _this.LIGHTMAP = false;
  41023. _this.LIGHTMAPDIRECTUV = 0;
  41024. _this.USELIGHTMAPASSHADOWMAP = false;
  41025. _this.GAMMALIGHTMAP = false;
  41026. _this.REFLECTION = false;
  41027. _this.REFLECTIONMAP_3D = false;
  41028. _this.REFLECTIONMAP_SPHERICAL = false;
  41029. _this.REFLECTIONMAP_PLANAR = false;
  41030. _this.REFLECTIONMAP_CUBIC = false;
  41031. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41032. _this.REFLECTIONMAP_PROJECTION = false;
  41033. _this.REFLECTIONMAP_SKYBOX = false;
  41034. _this.REFLECTIONMAP_EXPLICIT = false;
  41035. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41036. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41037. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41038. _this.INVERTCUBICMAP = false;
  41039. _this.USESPHERICALFROMREFLECTIONMAP = false;
  41040. _this.USESPHERICALINVERTEX = false;
  41041. _this.REFLECTIONMAP_OPPOSITEZ = false;
  41042. _this.LODINREFLECTIONALPHA = false;
  41043. _this.GAMMAREFLECTION = false;
  41044. _this.RADIANCEOCCLUSION = false;
  41045. _this.HORIZONOCCLUSION = false;
  41046. _this.REFRACTION = false;
  41047. _this.REFRACTIONMAP_3D = false;
  41048. _this.REFRACTIONMAP_OPPOSITEZ = false;
  41049. _this.LODINREFRACTIONALPHA = false;
  41050. _this.GAMMAREFRACTION = false;
  41051. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  41052. _this.INSTANCES = false;
  41053. _this.NUM_BONE_INFLUENCERS = 0;
  41054. _this.BonesPerMesh = 0;
  41055. _this.NONUNIFORMSCALING = false;
  41056. _this.MORPHTARGETS = false;
  41057. _this.MORPHTARGETS_NORMAL = false;
  41058. _this.MORPHTARGETS_TANGENT = false;
  41059. _this.NUM_MORPH_INFLUENCERS = 0;
  41060. _this.IMAGEPROCESSING = false;
  41061. _this.VIGNETTE = false;
  41062. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  41063. _this.VIGNETTEBLENDMODEOPAQUE = false;
  41064. _this.TONEMAPPING = false;
  41065. _this.CONTRAST = false;
  41066. _this.COLORCURVES = false;
  41067. _this.COLORGRADING = false;
  41068. _this.COLORGRADING3D = false;
  41069. _this.SAMPLER3DGREENDEPTH = false;
  41070. _this.SAMPLER3DBGRMAP = false;
  41071. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  41072. _this.EXPOSURE = false;
  41073. _this.GRAIN = false;
  41074. _this.USEPHYSICALLIGHTFALLOFF = false;
  41075. _this.TWOSIDEDLIGHTING = false;
  41076. _this.SHADOWFLOAT = false;
  41077. _this.CLIPPLANE = false;
  41078. _this.POINTSIZE = false;
  41079. _this.FOG = false;
  41080. _this.LOGARITHMICDEPTH = false;
  41081. _this.FORCENORMALFORWARD = false;
  41082. _this.UNLIT = false;
  41083. _this.rebuild();
  41084. return _this;
  41085. }
  41086. /**
  41087. * Resets the PBR Material defines.
  41088. */
  41089. PBRMaterialDefines.prototype.reset = function () {
  41090. _super.prototype.reset.call(this);
  41091. this.ALPHATESTVALUE = "0.5";
  41092. this.PBR = true;
  41093. };
  41094. return PBRMaterialDefines;
  41095. }(BABYLON.MaterialDefines));
  41096. /**
  41097. * The Physically based material base class of BJS.
  41098. *
  41099. * This offers the main features of a standard PBR material.
  41100. * For more information, please refer to the documentation :
  41101. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  41102. */
  41103. var PBRBaseMaterial = /** @class */ (function (_super) {
  41104. __extends(PBRBaseMaterial, _super);
  41105. /**
  41106. * Instantiates a new PBRMaterial instance.
  41107. *
  41108. * @param name The material name
  41109. * @param scene The scene the material will be use in.
  41110. */
  41111. function PBRBaseMaterial(name, scene) {
  41112. var _this = _super.call(this, name, scene) || this;
  41113. /**
  41114. * Intensity of the direct lights e.g. the four lights available in your scene.
  41115. * This impacts both the direct diffuse and specular highlights.
  41116. */
  41117. _this._directIntensity = 1.0;
  41118. /**
  41119. * Intensity of the emissive part of the material.
  41120. * This helps controlling the emissive effect without modifying the emissive color.
  41121. */
  41122. _this._emissiveIntensity = 1.0;
  41123. /**
  41124. * Intensity of the environment e.g. how much the environment will light the object
  41125. * either through harmonics for rough material or through the refelction for shiny ones.
  41126. */
  41127. _this._environmentIntensity = 1.0;
  41128. /**
  41129. * This is a special control allowing the reduction of the specular highlights coming from the
  41130. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  41131. */
  41132. _this._specularIntensity = 1.0;
  41133. /**
  41134. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  41135. */
  41136. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  41137. /**
  41138. * Debug Control allowing disabling the bump map on this material.
  41139. */
  41140. _this._disableBumpMap = false;
  41141. /**
  41142. * AKA Occlusion Texture Intensity in other nomenclature.
  41143. */
  41144. _this._ambientTextureStrength = 1.0;
  41145. /**
  41146. * The color of a material in ambient lighting.
  41147. */
  41148. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  41149. /**
  41150. * AKA Diffuse Color in other nomenclature.
  41151. */
  41152. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  41153. /**
  41154. * AKA Specular Color in other nomenclature.
  41155. */
  41156. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  41157. /**
  41158. * The color applied when light is reflected from a material.
  41159. */
  41160. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  41161. /**
  41162. * The color applied when light is emitted from a material.
  41163. */
  41164. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  41165. /**
  41166. * AKA Glossiness in other nomenclature.
  41167. */
  41168. _this._microSurface = 0.9;
  41169. /**
  41170. * source material index of refraction (IOR)' / 'destination material IOR.
  41171. */
  41172. _this._indexOfRefraction = 0.66;
  41173. /**
  41174. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  41175. */
  41176. _this._invertRefractionY = false;
  41177. /**
  41178. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  41179. * Materials half opaque for instance using refraction could benefit from this control.
  41180. */
  41181. _this._linkRefractionWithTransparency = false;
  41182. /**
  41183. * Specifies that the material will use the light map as a show map.
  41184. */
  41185. _this._useLightmapAsShadowmap = false;
  41186. /**
  41187. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  41188. * makes the reflect vector face the model (under horizon).
  41189. */
  41190. _this._useHorizonOcclusion = true;
  41191. /**
  41192. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  41193. * too much the area relying on ambient texture to define their ambient occlusion.
  41194. */
  41195. _this._useRadianceOcclusion = true;
  41196. /**
  41197. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  41198. */
  41199. _this._useAlphaFromAlbedoTexture = false;
  41200. /**
  41201. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  41202. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  41203. */
  41204. _this._useSpecularOverAlpha = true;
  41205. /**
  41206. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  41207. */
  41208. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  41209. /**
  41210. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  41211. */
  41212. _this._useRoughnessFromMetallicTextureAlpha = true;
  41213. /**
  41214. * Specifies if the metallic texture contains the roughness information in its green channel.
  41215. */
  41216. _this._useRoughnessFromMetallicTextureGreen = false;
  41217. /**
  41218. * Specifies if the metallic texture contains the metallness information in its blue channel.
  41219. */
  41220. _this._useMetallnessFromMetallicTextureBlue = false;
  41221. /**
  41222. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  41223. */
  41224. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  41225. /**
  41226. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  41227. */
  41228. _this._useAmbientInGrayScale = false;
  41229. /**
  41230. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  41231. * The material will try to infer what glossiness each pixel should be.
  41232. */
  41233. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  41234. /**
  41235. * BJS is using an harcoded light falloff based on a manually sets up range.
  41236. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  41237. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  41238. */
  41239. _this._usePhysicalLightFalloff = true;
  41240. /**
  41241. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  41242. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  41243. */
  41244. _this._useRadianceOverAlpha = true;
  41245. /**
  41246. * Allows using an object space normal map (instead of tangent space).
  41247. */
  41248. _this._useObjectSpaceNormalMap = false;
  41249. /**
  41250. * Allows using the bump map in parallax mode.
  41251. */
  41252. _this._useParallax = false;
  41253. /**
  41254. * Allows using the bump map in parallax occlusion mode.
  41255. */
  41256. _this._useParallaxOcclusion = false;
  41257. /**
  41258. * Controls the scale bias of the parallax mode.
  41259. */
  41260. _this._parallaxScaleBias = 0.05;
  41261. /**
  41262. * If sets to true, disables all the lights affecting the material.
  41263. */
  41264. _this._disableLighting = false;
  41265. /**
  41266. * Number of Simultaneous lights allowed on the material.
  41267. */
  41268. _this._maxSimultaneousLights = 4;
  41269. /**
  41270. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  41271. */
  41272. _this._invertNormalMapX = false;
  41273. /**
  41274. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  41275. */
  41276. _this._invertNormalMapY = false;
  41277. /**
  41278. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41279. */
  41280. _this._twoSidedLighting = false;
  41281. /**
  41282. * Defines the alpha limits in alpha test mode.
  41283. */
  41284. _this._alphaCutOff = 0.4;
  41285. /**
  41286. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  41287. */
  41288. _this._forceAlphaTest = false;
  41289. /**
  41290. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41291. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  41292. */
  41293. _this._useAlphaFresnel = false;
  41294. /**
  41295. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41296. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  41297. */
  41298. _this._useLinearAlphaFresnel = false;
  41299. /**
  41300. * The transparency mode of the material.
  41301. */
  41302. _this._transparencyMode = null;
  41303. /**
  41304. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  41305. * from cos thetav and roughness:
  41306. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  41307. */
  41308. _this._environmentBRDFTexture = null;
  41309. /**
  41310. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  41311. */
  41312. _this._forceIrradianceInFragment = false;
  41313. /**
  41314. * Force normal to face away from face.
  41315. */
  41316. _this._forceNormalForward = false;
  41317. /**
  41318. * Stores the available render targets.
  41319. */
  41320. _this._renderTargets = new BABYLON.SmartArray(16);
  41321. /**
  41322. * Sets the global ambient color for the material used in lighting calculations.
  41323. */
  41324. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  41325. /**
  41326. * If set to true, no lighting calculations will be applied.
  41327. */
  41328. _this._unlit = false;
  41329. // Setup the default processing configuration to the scene.
  41330. _this._attachImageProcessingConfiguration(null);
  41331. _this.getRenderTargetTextures = function () {
  41332. _this._renderTargets.reset();
  41333. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  41334. _this._renderTargets.push(_this._reflectionTexture);
  41335. }
  41336. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  41337. _this._renderTargets.push(_this._refractionTexture);
  41338. }
  41339. return _this._renderTargets;
  41340. };
  41341. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  41342. return _this;
  41343. }
  41344. /**
  41345. * Attaches a new image processing configuration to the PBR Material.
  41346. * @param configuration
  41347. */
  41348. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  41349. var _this = this;
  41350. if (configuration === this._imageProcessingConfiguration) {
  41351. return;
  41352. }
  41353. // Detaches observer.
  41354. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41355. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41356. }
  41357. // Pick the scene configuration if needed.
  41358. if (!configuration) {
  41359. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  41360. }
  41361. else {
  41362. this._imageProcessingConfiguration = configuration;
  41363. }
  41364. // Attaches observer.
  41365. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  41366. _this._markAllSubMeshesAsImageProcessingDirty();
  41367. });
  41368. };
  41369. /**
  41370. * Gets the name of the material class.
  41371. */
  41372. PBRBaseMaterial.prototype.getClassName = function () {
  41373. return "PBRBaseMaterial";
  41374. };
  41375. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  41376. /**
  41377. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  41378. */
  41379. get: function () {
  41380. return this._useLogarithmicDepth;
  41381. },
  41382. /**
  41383. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  41384. */
  41385. set: function (value) {
  41386. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  41387. },
  41388. enumerable: true,
  41389. configurable: true
  41390. });
  41391. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  41392. /**
  41393. * Gets the current transparency mode.
  41394. */
  41395. get: function () {
  41396. return this._transparencyMode;
  41397. },
  41398. /**
  41399. * Sets the transparency mode of the material.
  41400. */
  41401. set: function (value) {
  41402. if (this._transparencyMode === value) {
  41403. return;
  41404. }
  41405. this._transparencyMode = value;
  41406. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  41407. this._markAllSubMeshesAsTexturesAndMiscDirty();
  41408. },
  41409. enumerable: true,
  41410. configurable: true
  41411. });
  41412. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  41413. /**
  41414. * Returns true if alpha blending should be disabled.
  41415. */
  41416. get: function () {
  41417. return (this._linkRefractionWithTransparency ||
  41418. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  41419. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  41420. },
  41421. enumerable: true,
  41422. configurable: true
  41423. });
  41424. /**
  41425. * Specifies whether or not this material should be rendered in alpha blend mode.
  41426. */
  41427. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  41428. if (this._disableAlphaBlending) {
  41429. return false;
  41430. }
  41431. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  41432. };
  41433. /**
  41434. * Specifies if the mesh will require alpha blending.
  41435. * @param mesh - BJS mesh.
  41436. */
  41437. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  41438. if (this._disableAlphaBlending) {
  41439. return false;
  41440. }
  41441. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  41442. };
  41443. /**
  41444. * Specifies whether or not this material should be rendered in alpha test mode.
  41445. */
  41446. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  41447. if (this._forceAlphaTest) {
  41448. return true;
  41449. }
  41450. if (this._linkRefractionWithTransparency) {
  41451. return false;
  41452. }
  41453. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  41454. };
  41455. /**
  41456. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  41457. */
  41458. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  41459. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  41460. };
  41461. /**
  41462. * Gets the texture used for the alpha test.
  41463. */
  41464. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  41465. return this._albedoTexture;
  41466. };
  41467. /**
  41468. * Specifies that the submesh is ready to be used.
  41469. * @param mesh - BJS mesh.
  41470. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  41471. * @param useInstances - Specifies that instances should be used.
  41472. * @returns - boolean indicating that the submesh is ready or not.
  41473. */
  41474. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  41475. if (subMesh.effect && this.isFrozen) {
  41476. if (this._wasPreviouslyReady) {
  41477. return true;
  41478. }
  41479. }
  41480. if (!subMesh._materialDefines) {
  41481. subMesh._materialDefines = new PBRMaterialDefines();
  41482. }
  41483. var defines = subMesh._materialDefines;
  41484. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  41485. if (defines._renderId === this.getScene().getRenderId()) {
  41486. return true;
  41487. }
  41488. }
  41489. var scene = this.getScene();
  41490. var engine = scene.getEngine();
  41491. if (defines._areTexturesDirty) {
  41492. if (scene.texturesEnabled) {
  41493. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41494. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  41495. return false;
  41496. }
  41497. }
  41498. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41499. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  41500. return false;
  41501. }
  41502. }
  41503. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41504. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  41505. return false;
  41506. }
  41507. }
  41508. var reflectionTexture = this._getReflectionTexture();
  41509. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41510. if (!reflectionTexture.isReadyOrNotBlocking()) {
  41511. return false;
  41512. }
  41513. }
  41514. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41515. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  41516. return false;
  41517. }
  41518. }
  41519. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41520. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  41521. return false;
  41522. }
  41523. }
  41524. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41525. if (this._metallicTexture) {
  41526. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  41527. return false;
  41528. }
  41529. }
  41530. else if (this._reflectivityTexture) {
  41531. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  41532. return false;
  41533. }
  41534. }
  41535. if (this._microSurfaceTexture) {
  41536. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  41537. return false;
  41538. }
  41539. }
  41540. }
  41541. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41542. // Bump texture cannot be not blocking.
  41543. if (!this._bumpTexture.isReady()) {
  41544. return false;
  41545. }
  41546. }
  41547. var refractionTexture = this._getRefractionTexture();
  41548. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41549. if (!refractionTexture.isReadyOrNotBlocking()) {
  41550. return false;
  41551. }
  41552. }
  41553. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41554. // This is blocking.
  41555. if (!this._environmentBRDFTexture.isReady()) {
  41556. return false;
  41557. }
  41558. }
  41559. }
  41560. }
  41561. if (defines._areImageProcessingDirty) {
  41562. if (!this._imageProcessingConfiguration.isReady()) {
  41563. return false;
  41564. }
  41565. }
  41566. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  41567. mesh.createNormals(true);
  41568. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  41569. }
  41570. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  41571. if (effect) {
  41572. scene.resetCachedMaterial();
  41573. subMesh.setEffect(effect, defines);
  41574. this.buildUniformLayout();
  41575. }
  41576. if (!subMesh.effect || !subMesh.effect.isReady()) {
  41577. return false;
  41578. }
  41579. defines._renderId = scene.getRenderId();
  41580. this._wasPreviouslyReady = true;
  41581. return true;
  41582. };
  41583. /**
  41584. * Specifies if the material uses metallic roughness workflow.
  41585. * @returns boolean specifiying if the material uses metallic roughness workflow.
  41586. */
  41587. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  41588. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  41589. return true;
  41590. }
  41591. return false;
  41592. };
  41593. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  41594. if (onCompiled === void 0) { onCompiled = null; }
  41595. if (onError === void 0) { onError = null; }
  41596. if (useInstances === void 0) { useInstances = null; }
  41597. if (useClipPlane === void 0) { useClipPlane = null; }
  41598. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  41599. if (!defines.isDirty) {
  41600. return null;
  41601. }
  41602. defines.markAsProcessed();
  41603. var scene = this.getScene();
  41604. var engine = scene.getEngine();
  41605. // Fallbacks
  41606. var fallbacks = new BABYLON.EffectFallbacks();
  41607. var fallbackRank = 0;
  41608. if (defines.USESPHERICALINVERTEX) {
  41609. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  41610. }
  41611. if (defines.FOG) {
  41612. fallbacks.addFallback(fallbackRank, "FOG");
  41613. }
  41614. if (defines.POINTSIZE) {
  41615. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  41616. }
  41617. if (defines.LOGARITHMICDEPTH) {
  41618. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  41619. }
  41620. if (defines.PARALLAX) {
  41621. fallbacks.addFallback(fallbackRank, "PARALLAX");
  41622. }
  41623. if (defines.PARALLAXOCCLUSION) {
  41624. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  41625. }
  41626. if (defines.ENVIRONMENTBRDF) {
  41627. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  41628. }
  41629. if (defines.TANGENT) {
  41630. fallbacks.addFallback(fallbackRank++, "TANGENT");
  41631. }
  41632. if (defines.BUMP) {
  41633. fallbacks.addFallback(fallbackRank++, "BUMP");
  41634. }
  41635. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  41636. if (defines.SPECULARTERM) {
  41637. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  41638. }
  41639. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  41640. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  41641. }
  41642. if (defines.LIGHTMAP) {
  41643. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  41644. }
  41645. if (defines.NORMAL) {
  41646. fallbacks.addFallback(fallbackRank++, "NORMAL");
  41647. }
  41648. if (defines.AMBIENT) {
  41649. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  41650. }
  41651. if (defines.EMISSIVE) {
  41652. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  41653. }
  41654. if (defines.VERTEXCOLOR) {
  41655. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  41656. }
  41657. if (defines.NUM_BONE_INFLUENCERS > 0) {
  41658. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  41659. }
  41660. if (defines.MORPHTARGETS) {
  41661. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  41662. }
  41663. //Attributes
  41664. var attribs = [BABYLON.VertexBuffer.PositionKind];
  41665. if (defines.NORMAL) {
  41666. attribs.push(BABYLON.VertexBuffer.NormalKind);
  41667. }
  41668. if (defines.TANGENT) {
  41669. attribs.push(BABYLON.VertexBuffer.TangentKind);
  41670. }
  41671. if (defines.UV1) {
  41672. attribs.push(BABYLON.VertexBuffer.UVKind);
  41673. }
  41674. if (defines.UV2) {
  41675. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  41676. }
  41677. if (defines.VERTEXCOLOR) {
  41678. attribs.push(BABYLON.VertexBuffer.ColorKind);
  41679. }
  41680. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  41681. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  41682. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  41683. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  41684. "vFogInfos", "vFogColor", "pointSize",
  41685. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  41686. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  41687. "mBones",
  41688. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  41689. "vLightingIntensity",
  41690. "logarithmicDepthConstant",
  41691. "vSphericalX", "vSphericalY", "vSphericalZ",
  41692. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  41693. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  41694. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  41695. "vTangentSpaceParams"
  41696. ];
  41697. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  41698. "bumpSampler", "lightmapSampler", "opacitySampler",
  41699. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  41700. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  41701. "microSurfaceSampler", "environmentBrdfSampler"];
  41702. var uniformBuffers = ["Material", "Scene"];
  41703. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  41704. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  41705. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  41706. uniformsNames: uniforms,
  41707. uniformBuffersNames: uniformBuffers,
  41708. samplers: samplers,
  41709. defines: defines,
  41710. maxSimultaneousLights: this._maxSimultaneousLights
  41711. });
  41712. var join = defines.toString();
  41713. return engine.createEffect("pbr", {
  41714. attributes: attribs,
  41715. uniformsNames: uniforms,
  41716. uniformBuffersNames: uniformBuffers,
  41717. samplers: samplers,
  41718. defines: join,
  41719. fallbacks: fallbacks,
  41720. onCompiled: onCompiled,
  41721. onError: onError,
  41722. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  41723. }, engine);
  41724. };
  41725. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  41726. if (useInstances === void 0) { useInstances = null; }
  41727. if (useClipPlane === void 0) { useClipPlane = null; }
  41728. var scene = this.getScene();
  41729. var engine = scene.getEngine();
  41730. // Lights
  41731. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  41732. defines._needNormals = true;
  41733. // Textures
  41734. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  41735. if (defines._areTexturesDirty) {
  41736. defines._needUVs = false;
  41737. if (scene.texturesEnabled) {
  41738. if (scene.getEngine().getCaps().textureLOD) {
  41739. defines.LODBASEDMICROSFURACE = true;
  41740. }
  41741. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41742. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  41743. }
  41744. else {
  41745. defines.ALBEDO = false;
  41746. }
  41747. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41748. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  41749. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  41750. }
  41751. else {
  41752. defines.AMBIENT = false;
  41753. }
  41754. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41755. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  41756. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  41757. }
  41758. else {
  41759. defines.OPACITY = false;
  41760. }
  41761. var reflectionTexture = this._getReflectionTexture();
  41762. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41763. defines.REFLECTION = true;
  41764. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  41765. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  41766. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  41767. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  41768. defines.INVERTCUBICMAP = true;
  41769. }
  41770. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  41771. switch (reflectionTexture.coordinatesMode) {
  41772. case BABYLON.Texture.CUBIC_MODE:
  41773. case BABYLON.Texture.INVCUBIC_MODE:
  41774. defines.REFLECTIONMAP_CUBIC = true;
  41775. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  41776. break;
  41777. case BABYLON.Texture.EXPLICIT_MODE:
  41778. defines.REFLECTIONMAP_EXPLICIT = true;
  41779. break;
  41780. case BABYLON.Texture.PLANAR_MODE:
  41781. defines.REFLECTIONMAP_PLANAR = true;
  41782. break;
  41783. case BABYLON.Texture.PROJECTION_MODE:
  41784. defines.REFLECTIONMAP_PROJECTION = true;
  41785. break;
  41786. case BABYLON.Texture.SKYBOX_MODE:
  41787. defines.REFLECTIONMAP_SKYBOX = true;
  41788. break;
  41789. case BABYLON.Texture.SPHERICAL_MODE:
  41790. defines.REFLECTIONMAP_SPHERICAL = true;
  41791. break;
  41792. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  41793. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  41794. break;
  41795. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  41796. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  41797. break;
  41798. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  41799. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  41800. break;
  41801. }
  41802. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  41803. if (reflectionTexture.sphericalPolynomial) {
  41804. defines.USESPHERICALFROMREFLECTIONMAP = true;
  41805. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  41806. defines.USESPHERICALINVERTEX = false;
  41807. }
  41808. else {
  41809. defines.USESPHERICALINVERTEX = true;
  41810. }
  41811. }
  41812. }
  41813. }
  41814. else {
  41815. defines.REFLECTION = false;
  41816. defines.REFLECTIONMAP_3D = false;
  41817. defines.REFLECTIONMAP_SPHERICAL = false;
  41818. defines.REFLECTIONMAP_PLANAR = false;
  41819. defines.REFLECTIONMAP_CUBIC = false;
  41820. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41821. defines.REFLECTIONMAP_PROJECTION = false;
  41822. defines.REFLECTIONMAP_SKYBOX = false;
  41823. defines.REFLECTIONMAP_EXPLICIT = false;
  41824. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41825. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41826. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41827. defines.INVERTCUBICMAP = false;
  41828. defines.USESPHERICALFROMREFLECTIONMAP = false;
  41829. defines.USESPHERICALINVERTEX = false;
  41830. defines.REFLECTIONMAP_OPPOSITEZ = false;
  41831. defines.LODINREFLECTIONALPHA = false;
  41832. defines.GAMMAREFLECTION = false;
  41833. }
  41834. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41835. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  41836. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  41837. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  41838. }
  41839. else {
  41840. defines.LIGHTMAP = false;
  41841. }
  41842. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41843. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  41844. }
  41845. else {
  41846. defines.EMISSIVE = false;
  41847. }
  41848. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41849. if (this._metallicTexture) {
  41850. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  41851. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  41852. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  41853. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  41854. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  41855. }
  41856. else if (this._reflectivityTexture) {
  41857. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  41858. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  41859. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  41860. }
  41861. else {
  41862. defines.REFLECTIVITY = false;
  41863. }
  41864. if (this._microSurfaceTexture) {
  41865. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  41866. }
  41867. else {
  41868. defines.MICROSURFACEMAP = false;
  41869. }
  41870. }
  41871. else {
  41872. defines.REFLECTIVITY = false;
  41873. defines.MICROSURFACEMAP = false;
  41874. }
  41875. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41876. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  41877. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41878. defines.PARALLAX = true;
  41879. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  41880. }
  41881. else {
  41882. defines.PARALLAX = false;
  41883. }
  41884. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  41885. }
  41886. else {
  41887. defines.BUMP = false;
  41888. }
  41889. var refractionTexture = this._getRefractionTexture();
  41890. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41891. defines.REFRACTION = true;
  41892. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  41893. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  41894. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  41895. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  41896. if (this._linkRefractionWithTransparency) {
  41897. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  41898. }
  41899. }
  41900. else {
  41901. defines.REFRACTION = false;
  41902. }
  41903. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41904. defines.ENVIRONMENTBRDF = true;
  41905. }
  41906. else {
  41907. defines.ENVIRONMENTBRDF = false;
  41908. }
  41909. if (this._shouldUseAlphaFromAlbedoTexture()) {
  41910. defines.ALPHAFROMALBEDO = true;
  41911. }
  41912. else {
  41913. defines.ALPHAFROMALBEDO = false;
  41914. }
  41915. }
  41916. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  41917. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  41918. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  41919. if (!this.backFaceCulling && this._twoSidedLighting) {
  41920. defines.TWOSIDEDLIGHTING = true;
  41921. }
  41922. else {
  41923. defines.TWOSIDEDLIGHTING = false;
  41924. }
  41925. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  41926. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  41927. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  41928. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  41929. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  41930. }
  41931. if (defines._areImageProcessingDirty) {
  41932. this._imageProcessingConfiguration.prepareDefines(defines);
  41933. }
  41934. defines.FORCENORMALFORWARD = this._forceNormalForward;
  41935. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  41936. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  41937. // Misc.
  41938. if (defines._areMiscDirty) {
  41939. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  41940. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  41941. }
  41942. // Values that need to be evaluated on every frame
  41943. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  41944. // Attribs
  41945. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  41946. };
  41947. /**
  41948. * Force shader compilation
  41949. */
  41950. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  41951. var _this = this;
  41952. var localOptions = __assign({ clipPlane: false }, options);
  41953. var defines = new PBRMaterialDefines();
  41954. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  41955. if (effect.isReady()) {
  41956. if (onCompiled) {
  41957. onCompiled(this);
  41958. }
  41959. }
  41960. else {
  41961. effect.onCompileObservable.add(function () {
  41962. if (onCompiled) {
  41963. onCompiled(_this);
  41964. }
  41965. });
  41966. }
  41967. };
  41968. /**
  41969. * Initializes the uniform buffer layout for the shader.
  41970. */
  41971. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  41972. // Order is important !
  41973. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  41974. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  41975. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  41976. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  41977. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  41978. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  41979. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  41980. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  41981. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  41982. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  41983. this._uniformBuffer.addUniform("vReflectionSize", 3);
  41984. this._uniformBuffer.addUniform("vBumpInfos", 3);
  41985. this._uniformBuffer.addUniform("albedoMatrix", 16);
  41986. this._uniformBuffer.addUniform("ambientMatrix", 16);
  41987. this._uniformBuffer.addUniform("opacityMatrix", 16);
  41988. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  41989. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  41990. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  41991. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  41992. this._uniformBuffer.addUniform("bumpMatrix", 16);
  41993. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  41994. this._uniformBuffer.addUniform("refractionMatrix", 16);
  41995. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  41996. this._uniformBuffer.addUniform("vReflectionColor", 3);
  41997. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  41998. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  41999. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  42000. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  42001. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  42002. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  42003. this._uniformBuffer.addUniform("pointSize", 1);
  42004. this._uniformBuffer.create();
  42005. };
  42006. /**
  42007. * Unbinds the textures.
  42008. */
  42009. PBRBaseMaterial.prototype.unbind = function () {
  42010. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  42011. this._uniformBuffer.setTexture("reflectionSampler", null);
  42012. }
  42013. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  42014. this._uniformBuffer.setTexture("refractionSampler", null);
  42015. }
  42016. _super.prototype.unbind.call(this);
  42017. };
  42018. /**
  42019. * Binds the submesh data.
  42020. * @param world - The world matrix.
  42021. * @param mesh - The BJS mesh.
  42022. * @param subMesh - A submesh of the BJS mesh.
  42023. */
  42024. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  42025. var scene = this.getScene();
  42026. var defines = subMesh._materialDefines;
  42027. if (!defines) {
  42028. return;
  42029. }
  42030. var effect = subMesh.effect;
  42031. if (!effect) {
  42032. return;
  42033. }
  42034. this._activeEffect = effect;
  42035. // Matrices
  42036. this.bindOnlyWorldMatrix(world);
  42037. // Normal Matrix
  42038. if (defines.OBJECTSPACE_NORMALMAP) {
  42039. world.toNormalMatrix(this._normalMatrix);
  42040. this.bindOnlyNormalMatrix(this._normalMatrix);
  42041. }
  42042. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  42043. // Bones
  42044. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  42045. var reflectionTexture = null;
  42046. if (mustRebind) {
  42047. this._uniformBuffer.bindToEffect(effect, "Material");
  42048. this.bindViewProjection(effect);
  42049. reflectionTexture = this._getReflectionTexture();
  42050. var refractionTexture = this._getRefractionTexture();
  42051. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  42052. // Texture uniforms
  42053. if (scene.texturesEnabled) {
  42054. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  42055. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  42056. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  42057. }
  42058. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  42059. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  42060. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  42061. }
  42062. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  42063. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  42064. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  42065. }
  42066. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  42067. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  42068. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  42069. if (reflectionTexture.boundingBoxSize) {
  42070. var cubeTexture = reflectionTexture;
  42071. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  42072. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  42073. }
  42074. var polynomials = reflectionTexture.sphericalPolynomial;
  42075. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  42076. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  42077. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  42078. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  42079. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  42080. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  42081. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  42082. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  42083. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  42084. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  42085. }
  42086. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  42087. }
  42088. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  42089. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  42090. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  42091. }
  42092. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  42093. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  42094. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  42095. }
  42096. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  42097. if (this._metallicTexture) {
  42098. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  42099. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  42100. }
  42101. else if (this._reflectivityTexture) {
  42102. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  42103. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  42104. }
  42105. if (this._microSurfaceTexture) {
  42106. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  42107. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  42108. }
  42109. }
  42110. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  42111. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  42112. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  42113. if (scene._mirroredCameraPosition) {
  42114. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  42115. }
  42116. else {
  42117. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  42118. }
  42119. }
  42120. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  42121. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  42122. var depth = 1.0;
  42123. if (!refractionTexture.isCube) {
  42124. if (refractionTexture.depth) {
  42125. depth = refractionTexture.depth;
  42126. }
  42127. }
  42128. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  42129. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  42130. }
  42131. }
  42132. // Point size
  42133. if (this.pointsCloud) {
  42134. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  42135. }
  42136. // Colors
  42137. if (defines.METALLICWORKFLOW) {
  42138. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  42139. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  42140. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  42141. }
  42142. else {
  42143. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  42144. }
  42145. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  42146. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  42147. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  42148. // Misc
  42149. this._lightingInfos.x = this._directIntensity;
  42150. this._lightingInfos.y = this._emissiveIntensity;
  42151. this._lightingInfos.z = this._environmentIntensity;
  42152. this._lightingInfos.w = this._specularIntensity;
  42153. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  42154. }
  42155. // Textures
  42156. if (scene.texturesEnabled) {
  42157. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  42158. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  42159. }
  42160. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  42161. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  42162. }
  42163. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  42164. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  42165. }
  42166. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  42167. if (defines.LODBASEDMICROSFURACE) {
  42168. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  42169. }
  42170. else {
  42171. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  42172. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  42173. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  42174. }
  42175. }
  42176. if (defines.ENVIRONMENTBRDF) {
  42177. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  42178. }
  42179. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  42180. if (defines.LODBASEDMICROSFURACE) {
  42181. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  42182. }
  42183. else {
  42184. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  42185. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  42186. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  42187. }
  42188. }
  42189. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  42190. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  42191. }
  42192. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  42193. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  42194. }
  42195. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  42196. if (this._metallicTexture) {
  42197. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  42198. }
  42199. else if (this._reflectivityTexture) {
  42200. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  42201. }
  42202. if (this._microSurfaceTexture) {
  42203. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  42204. }
  42205. }
  42206. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  42207. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  42208. }
  42209. }
  42210. // Clip plane
  42211. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  42212. // Colors
  42213. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  42214. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  42215. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  42216. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  42217. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  42218. }
  42219. if (mustRebind || !this.isFrozen) {
  42220. // Lights
  42221. if (scene.lightsEnabled && !this._disableLighting) {
  42222. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  42223. }
  42224. // View
  42225. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  42226. this.bindView(effect);
  42227. }
  42228. // Fog
  42229. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  42230. // Morph targets
  42231. if (defines.NUM_MORPH_INFLUENCERS) {
  42232. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  42233. }
  42234. // image processing
  42235. this._imageProcessingConfiguration.bind(this._activeEffect);
  42236. // Log. depth
  42237. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  42238. }
  42239. this._uniformBuffer.update();
  42240. this._afterBind(mesh);
  42241. };
  42242. /**
  42243. * Returns the animatable textures.
  42244. * @returns - Array of animatable textures.
  42245. */
  42246. PBRBaseMaterial.prototype.getAnimatables = function () {
  42247. var results = [];
  42248. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  42249. results.push(this._albedoTexture);
  42250. }
  42251. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  42252. results.push(this._ambientTexture);
  42253. }
  42254. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  42255. results.push(this._opacityTexture);
  42256. }
  42257. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  42258. results.push(this._reflectionTexture);
  42259. }
  42260. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  42261. results.push(this._emissiveTexture);
  42262. }
  42263. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  42264. results.push(this._metallicTexture);
  42265. }
  42266. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  42267. results.push(this._reflectivityTexture);
  42268. }
  42269. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  42270. results.push(this._bumpTexture);
  42271. }
  42272. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  42273. results.push(this._lightmapTexture);
  42274. }
  42275. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  42276. results.push(this._refractionTexture);
  42277. }
  42278. return results;
  42279. };
  42280. /**
  42281. * Returns the texture used for reflections.
  42282. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  42283. */
  42284. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  42285. if (this._reflectionTexture) {
  42286. return this._reflectionTexture;
  42287. }
  42288. return this.getScene().environmentTexture;
  42289. };
  42290. /**
  42291. * Returns the texture used for refraction or null if none is used.
  42292. * @returns - Refection texture if present. If no refraction texture and refraction
  42293. * is linked with transparency, returns environment texture. Otherwise, returns null.
  42294. */
  42295. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  42296. if (this._refractionTexture) {
  42297. return this._refractionTexture;
  42298. }
  42299. if (this._linkRefractionWithTransparency) {
  42300. return this.getScene().environmentTexture;
  42301. }
  42302. return null;
  42303. };
  42304. /**
  42305. * Disposes the resources of the material.
  42306. * @param forceDisposeEffect - Forces the disposal of effects.
  42307. * @param forceDisposeTextures - Forces the disposal of all textures.
  42308. */
  42309. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  42310. if (forceDisposeTextures) {
  42311. if (this._albedoTexture) {
  42312. this._albedoTexture.dispose();
  42313. }
  42314. if (this._ambientTexture) {
  42315. this._ambientTexture.dispose();
  42316. }
  42317. if (this._opacityTexture) {
  42318. this._opacityTexture.dispose();
  42319. }
  42320. if (this._reflectionTexture) {
  42321. this._reflectionTexture.dispose();
  42322. }
  42323. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  42324. this._environmentBRDFTexture.dispose();
  42325. }
  42326. if (this._emissiveTexture) {
  42327. this._emissiveTexture.dispose();
  42328. }
  42329. if (this._metallicTexture) {
  42330. this._metallicTexture.dispose();
  42331. }
  42332. if (this._reflectivityTexture) {
  42333. this._reflectivityTexture.dispose();
  42334. }
  42335. if (this._bumpTexture) {
  42336. this._bumpTexture.dispose();
  42337. }
  42338. if (this._lightmapTexture) {
  42339. this._lightmapTexture.dispose();
  42340. }
  42341. if (this._refractionTexture) {
  42342. this._refractionTexture.dispose();
  42343. }
  42344. }
  42345. this._renderTargets.dispose();
  42346. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42347. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42348. }
  42349. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  42350. };
  42351. /**
  42352. * Stores the reflectivity values based on metallic roughness workflow.
  42353. */
  42354. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  42355. __decorate([
  42356. BABYLON.serializeAsImageProcessingConfiguration()
  42357. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  42358. __decorate([
  42359. BABYLON.serialize()
  42360. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  42361. __decorate([
  42362. BABYLON.serialize()
  42363. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  42364. return PBRBaseMaterial;
  42365. }(BABYLON.PushMaterial));
  42366. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  42367. })(BABYLON || (BABYLON = {}));
  42368. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  42369. "use strict";
  42370. var BABYLON;
  42371. (function (BABYLON) {
  42372. /**
  42373. * The Physically based simple base material of BJS.
  42374. *
  42375. * This enables better naming and convention enforcements on top of the pbrMaterial.
  42376. * It is used as the base class for both the specGloss and metalRough conventions.
  42377. */
  42378. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  42379. __extends(PBRBaseSimpleMaterial, _super);
  42380. /**
  42381. * Instantiates a new PBRMaterial instance.
  42382. *
  42383. * @param name The material name
  42384. * @param scene The scene the material will be use in.
  42385. */
  42386. function PBRBaseSimpleMaterial(name, scene) {
  42387. var _this = _super.call(this, name, scene) || this;
  42388. /**
  42389. * Number of Simultaneous lights allowed on the material.
  42390. */
  42391. _this.maxSimultaneousLights = 4;
  42392. /**
  42393. * If sets to true, disables all the lights affecting the material.
  42394. */
  42395. _this.disableLighting = false;
  42396. /**
  42397. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  42398. */
  42399. _this.invertNormalMapX = false;
  42400. /**
  42401. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  42402. */
  42403. _this.invertNormalMapY = false;
  42404. /**
  42405. * Emissivie color used to self-illuminate the model.
  42406. */
  42407. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  42408. /**
  42409. * Occlusion Channel Strenght.
  42410. */
  42411. _this.occlusionStrength = 1.0;
  42412. _this.useLightmapAsShadowmap = false;
  42413. _this._useAlphaFromAlbedoTexture = true;
  42414. _this._useAmbientInGrayScale = true;
  42415. return _this;
  42416. }
  42417. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  42418. /**
  42419. * Gets the current double sided mode.
  42420. */
  42421. get: function () {
  42422. return this._twoSidedLighting;
  42423. },
  42424. /**
  42425. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  42426. */
  42427. set: function (value) {
  42428. if (this._twoSidedLighting === value) {
  42429. return;
  42430. }
  42431. this._twoSidedLighting = value;
  42432. this.backFaceCulling = !value;
  42433. this._markAllSubMeshesAsTexturesDirty();
  42434. },
  42435. enumerable: true,
  42436. configurable: true
  42437. });
  42438. /**
  42439. * Return the active textures of the material.
  42440. */
  42441. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  42442. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42443. if (this.environmentTexture) {
  42444. activeTextures.push(this.environmentTexture);
  42445. }
  42446. if (this.normalTexture) {
  42447. activeTextures.push(this.normalTexture);
  42448. }
  42449. if (this.emissiveTexture) {
  42450. activeTextures.push(this.emissiveTexture);
  42451. }
  42452. if (this.occlusionTexture) {
  42453. activeTextures.push(this.occlusionTexture);
  42454. }
  42455. if (this.lightmapTexture) {
  42456. activeTextures.push(this.lightmapTexture);
  42457. }
  42458. return activeTextures;
  42459. };
  42460. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  42461. if (_super.prototype.hasTexture.call(this, texture)) {
  42462. return true;
  42463. }
  42464. if (this.lightmapTexture === texture) {
  42465. return true;
  42466. }
  42467. return false;
  42468. };
  42469. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  42470. return "PBRBaseSimpleMaterial";
  42471. };
  42472. __decorate([
  42473. BABYLON.serialize(),
  42474. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42475. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  42476. __decorate([
  42477. BABYLON.serialize(),
  42478. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42479. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  42480. __decorate([
  42481. BABYLON.serializeAsTexture(),
  42482. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  42483. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  42484. __decorate([
  42485. BABYLON.serialize(),
  42486. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42487. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  42488. __decorate([
  42489. BABYLON.serialize(),
  42490. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42491. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  42492. __decorate([
  42493. BABYLON.serializeAsTexture(),
  42494. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  42495. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  42496. __decorate([
  42497. BABYLON.serializeAsColor3("emissive"),
  42498. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42499. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  42500. __decorate([
  42501. BABYLON.serializeAsTexture(),
  42502. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42503. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  42504. __decorate([
  42505. BABYLON.serialize(),
  42506. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  42507. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  42508. __decorate([
  42509. BABYLON.serializeAsTexture(),
  42510. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  42511. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  42512. __decorate([
  42513. BABYLON.serialize(),
  42514. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  42515. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  42516. __decorate([
  42517. BABYLON.serialize()
  42518. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  42519. __decorate([
  42520. BABYLON.serializeAsTexture(),
  42521. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  42522. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  42523. __decorate([
  42524. BABYLON.serialize(),
  42525. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42526. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  42527. return PBRBaseSimpleMaterial;
  42528. }(BABYLON.PBRBaseMaterial));
  42529. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  42530. })(BABYLON || (BABYLON = {}));
  42531. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  42532. "use strict";
  42533. var BABYLON;
  42534. (function (BABYLON) {
  42535. /**
  42536. * The Physically based material of BJS.
  42537. *
  42538. * This offers the main features of a standard PBR material.
  42539. * For more information, please refer to the documentation :
  42540. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  42541. */
  42542. var PBRMaterial = /** @class */ (function (_super) {
  42543. __extends(PBRMaterial, _super);
  42544. /**
  42545. * Instantiates a new PBRMaterial instance.
  42546. *
  42547. * @param name The material name
  42548. * @param scene The scene the material will be use in.
  42549. */
  42550. function PBRMaterial(name, scene) {
  42551. var _this = _super.call(this, name, scene) || this;
  42552. /**
  42553. * Intensity of the direct lights e.g. the four lights available in your scene.
  42554. * This impacts both the direct diffuse and specular highlights.
  42555. */
  42556. _this.directIntensity = 1.0;
  42557. /**
  42558. * Intensity of the emissive part of the material.
  42559. * This helps controlling the emissive effect without modifying the emissive color.
  42560. */
  42561. _this.emissiveIntensity = 1.0;
  42562. /**
  42563. * Intensity of the environment e.g. how much the environment will light the object
  42564. * either through harmonics for rough material or through the refelction for shiny ones.
  42565. */
  42566. _this.environmentIntensity = 1.0;
  42567. /**
  42568. * This is a special control allowing the reduction of the specular highlights coming from the
  42569. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  42570. */
  42571. _this.specularIntensity = 1.0;
  42572. /**
  42573. * Debug Control allowing disabling the bump map on this material.
  42574. */
  42575. _this.disableBumpMap = false;
  42576. /**
  42577. * AKA Occlusion Texture Intensity in other nomenclature.
  42578. */
  42579. _this.ambientTextureStrength = 1.0;
  42580. /**
  42581. * The color of a material in ambient lighting.
  42582. */
  42583. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  42584. /**
  42585. * AKA Diffuse Color in other nomenclature.
  42586. */
  42587. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  42588. /**
  42589. * AKA Specular Color in other nomenclature.
  42590. */
  42591. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  42592. /**
  42593. * The color reflected from the material.
  42594. */
  42595. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  42596. /**
  42597. * The color emitted from the material.
  42598. */
  42599. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  42600. /**
  42601. * AKA Glossiness in other nomenclature.
  42602. */
  42603. _this.microSurface = 1.0;
  42604. /**
  42605. * source material index of refraction (IOR)' / 'destination material IOR.
  42606. */
  42607. _this.indexOfRefraction = 0.66;
  42608. /**
  42609. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  42610. */
  42611. _this.invertRefractionY = false;
  42612. /**
  42613. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  42614. * Materials half opaque for instance using refraction could benefit from this control.
  42615. */
  42616. _this.linkRefractionWithTransparency = false;
  42617. _this.useLightmapAsShadowmap = false;
  42618. /**
  42619. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  42620. */
  42621. _this.useAlphaFromAlbedoTexture = false;
  42622. /**
  42623. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  42624. */
  42625. _this.forceAlphaTest = false;
  42626. /**
  42627. * Defines the alpha limits in alpha test mode.
  42628. */
  42629. _this.alphaCutOff = 0.4;
  42630. /**
  42631. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  42632. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  42633. */
  42634. _this.useSpecularOverAlpha = true;
  42635. /**
  42636. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  42637. */
  42638. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  42639. /**
  42640. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  42641. */
  42642. _this.useRoughnessFromMetallicTextureAlpha = true;
  42643. /**
  42644. * Specifies if the metallic texture contains the roughness information in its green channel.
  42645. */
  42646. _this.useRoughnessFromMetallicTextureGreen = false;
  42647. /**
  42648. * Specifies if the metallic texture contains the metallness information in its blue channel.
  42649. */
  42650. _this.useMetallnessFromMetallicTextureBlue = false;
  42651. /**
  42652. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  42653. */
  42654. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  42655. /**
  42656. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  42657. */
  42658. _this.useAmbientInGrayScale = false;
  42659. /**
  42660. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  42661. * The material will try to infer what glossiness each pixel should be.
  42662. */
  42663. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  42664. /**
  42665. * BJS is using an harcoded light falloff based on a manually sets up range.
  42666. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  42667. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  42668. */
  42669. _this.usePhysicalLightFalloff = true;
  42670. /**
  42671. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  42672. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  42673. */
  42674. _this.useRadianceOverAlpha = true;
  42675. /**
  42676. * Allows using an object space normal map (instead of tangent space).
  42677. */
  42678. _this.useObjectSpaceNormalMap = false;
  42679. /**
  42680. * Allows using the bump map in parallax mode.
  42681. */
  42682. _this.useParallax = false;
  42683. /**
  42684. * Allows using the bump map in parallax occlusion mode.
  42685. */
  42686. _this.useParallaxOcclusion = false;
  42687. /**
  42688. * Controls the scale bias of the parallax mode.
  42689. */
  42690. _this.parallaxScaleBias = 0.05;
  42691. /**
  42692. * If sets to true, disables all the lights affecting the material.
  42693. */
  42694. _this.disableLighting = false;
  42695. /**
  42696. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  42697. */
  42698. _this.forceIrradianceInFragment = false;
  42699. /**
  42700. * Number of Simultaneous lights allowed on the material.
  42701. */
  42702. _this.maxSimultaneousLights = 4;
  42703. /**
  42704. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  42705. */
  42706. _this.invertNormalMapX = false;
  42707. /**
  42708. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  42709. */
  42710. _this.invertNormalMapY = false;
  42711. /**
  42712. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  42713. */
  42714. _this.twoSidedLighting = false;
  42715. /**
  42716. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42717. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  42718. */
  42719. _this.useAlphaFresnel = false;
  42720. /**
  42721. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42722. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  42723. */
  42724. _this.useLinearAlphaFresnel = false;
  42725. /**
  42726. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42727. * And/Or occlude the blended part.
  42728. */
  42729. _this.environmentBRDFTexture = null;
  42730. /**
  42731. * Force normal to face away from face.
  42732. */
  42733. _this.forceNormalForward = false;
  42734. /**
  42735. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  42736. * makes the reflect vector face the model (under horizon).
  42737. */
  42738. _this.useHorizonOcclusion = true;
  42739. /**
  42740. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  42741. * too much the area relying on ambient texture to define their ambient occlusion.
  42742. */
  42743. _this.useRadianceOcclusion = true;
  42744. /**
  42745. * If set to true, no lighting calculations will be applied.
  42746. */
  42747. _this.unlit = false;
  42748. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  42749. return _this;
  42750. }
  42751. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  42752. /**
  42753. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  42754. */
  42755. get: function () {
  42756. return this._PBRMATERIAL_OPAQUE;
  42757. },
  42758. enumerable: true,
  42759. configurable: true
  42760. });
  42761. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  42762. /**
  42763. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  42764. */
  42765. get: function () {
  42766. return this._PBRMATERIAL_ALPHATEST;
  42767. },
  42768. enumerable: true,
  42769. configurable: true
  42770. });
  42771. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  42772. /**
  42773. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42774. */
  42775. get: function () {
  42776. return this._PBRMATERIAL_ALPHABLEND;
  42777. },
  42778. enumerable: true,
  42779. configurable: true
  42780. });
  42781. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  42782. /**
  42783. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42784. * They are also discarded below the alpha cutoff threshold to improve performances.
  42785. */
  42786. get: function () {
  42787. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  42788. },
  42789. enumerable: true,
  42790. configurable: true
  42791. });
  42792. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  42793. /**
  42794. * Gets the image processing configuration used either in this material.
  42795. */
  42796. get: function () {
  42797. return this._imageProcessingConfiguration;
  42798. },
  42799. /**
  42800. * Sets the Default image processing configuration used either in the this material.
  42801. *
  42802. * If sets to null, the scene one is in use.
  42803. */
  42804. set: function (value) {
  42805. this._attachImageProcessingConfiguration(value);
  42806. // Ensure the effect will be rebuilt.
  42807. this._markAllSubMeshesAsTexturesDirty();
  42808. },
  42809. enumerable: true,
  42810. configurable: true
  42811. });
  42812. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  42813. /**
  42814. * Gets wether the color curves effect is enabled.
  42815. */
  42816. get: function () {
  42817. return this.imageProcessingConfiguration.colorCurvesEnabled;
  42818. },
  42819. /**
  42820. * Sets wether the color curves effect is enabled.
  42821. */
  42822. set: function (value) {
  42823. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  42824. },
  42825. enumerable: true,
  42826. configurable: true
  42827. });
  42828. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  42829. /**
  42830. * Gets wether the color grading effect is enabled.
  42831. */
  42832. get: function () {
  42833. return this.imageProcessingConfiguration.colorGradingEnabled;
  42834. },
  42835. /**
  42836. * Gets wether the color grading effect is enabled.
  42837. */
  42838. set: function (value) {
  42839. this.imageProcessingConfiguration.colorGradingEnabled = value;
  42840. },
  42841. enumerable: true,
  42842. configurable: true
  42843. });
  42844. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  42845. /**
  42846. * Gets wether tonemapping is enabled or not.
  42847. */
  42848. get: function () {
  42849. return this._imageProcessingConfiguration.toneMappingEnabled;
  42850. },
  42851. /**
  42852. * Sets wether tonemapping is enabled or not
  42853. */
  42854. set: function (value) {
  42855. this._imageProcessingConfiguration.toneMappingEnabled = value;
  42856. },
  42857. enumerable: true,
  42858. configurable: true
  42859. });
  42860. ;
  42861. ;
  42862. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  42863. /**
  42864. * The camera exposure used on this material.
  42865. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42866. * This corresponds to a photographic exposure.
  42867. */
  42868. get: function () {
  42869. return this._imageProcessingConfiguration.exposure;
  42870. },
  42871. /**
  42872. * The camera exposure used on this material.
  42873. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42874. * This corresponds to a photographic exposure.
  42875. */
  42876. set: function (value) {
  42877. this._imageProcessingConfiguration.exposure = value;
  42878. },
  42879. enumerable: true,
  42880. configurable: true
  42881. });
  42882. ;
  42883. ;
  42884. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  42885. /**
  42886. * Gets The camera contrast used on this material.
  42887. */
  42888. get: function () {
  42889. return this._imageProcessingConfiguration.contrast;
  42890. },
  42891. /**
  42892. * Sets The camera contrast used on this material.
  42893. */
  42894. set: function (value) {
  42895. this._imageProcessingConfiguration.contrast = value;
  42896. },
  42897. enumerable: true,
  42898. configurable: true
  42899. });
  42900. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  42901. /**
  42902. * Gets the Color Grading 2D Lookup Texture.
  42903. */
  42904. get: function () {
  42905. return this._imageProcessingConfiguration.colorGradingTexture;
  42906. },
  42907. /**
  42908. * Sets the Color Grading 2D Lookup Texture.
  42909. */
  42910. set: function (value) {
  42911. this._imageProcessingConfiguration.colorGradingTexture = value;
  42912. },
  42913. enumerable: true,
  42914. configurable: true
  42915. });
  42916. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  42917. /**
  42918. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42919. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42920. * 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;
  42921. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42922. */
  42923. get: function () {
  42924. return this._imageProcessingConfiguration.colorCurves;
  42925. },
  42926. /**
  42927. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42928. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42929. * 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;
  42930. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42931. */
  42932. set: function (value) {
  42933. this._imageProcessingConfiguration.colorCurves = value;
  42934. },
  42935. enumerable: true,
  42936. configurable: true
  42937. });
  42938. /**
  42939. * Returns the name of this material class.
  42940. */
  42941. PBRMaterial.prototype.getClassName = function () {
  42942. return "PBRMaterial";
  42943. };
  42944. /**
  42945. * Returns an array of the actively used textures.
  42946. * @returns - Array of BaseTextures
  42947. */
  42948. PBRMaterial.prototype.getActiveTextures = function () {
  42949. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42950. if (this._albedoTexture) {
  42951. activeTextures.push(this._albedoTexture);
  42952. }
  42953. if (this._ambientTexture) {
  42954. activeTextures.push(this._ambientTexture);
  42955. }
  42956. if (this._opacityTexture) {
  42957. activeTextures.push(this._opacityTexture);
  42958. }
  42959. if (this._reflectionTexture) {
  42960. activeTextures.push(this._reflectionTexture);
  42961. }
  42962. if (this._emissiveTexture) {
  42963. activeTextures.push(this._emissiveTexture);
  42964. }
  42965. if (this._reflectivityTexture) {
  42966. activeTextures.push(this._reflectivityTexture);
  42967. }
  42968. if (this._metallicTexture) {
  42969. activeTextures.push(this._metallicTexture);
  42970. }
  42971. if (this._microSurfaceTexture) {
  42972. activeTextures.push(this._microSurfaceTexture);
  42973. }
  42974. if (this._bumpTexture) {
  42975. activeTextures.push(this._bumpTexture);
  42976. }
  42977. if (this._lightmapTexture) {
  42978. activeTextures.push(this._lightmapTexture);
  42979. }
  42980. if (this._refractionTexture) {
  42981. activeTextures.push(this._refractionTexture);
  42982. }
  42983. return activeTextures;
  42984. };
  42985. /**
  42986. * Checks to see if a texture is used in the material.
  42987. * @param texture - Base texture to use.
  42988. * @returns - Boolean specifying if a texture is used in the material.
  42989. */
  42990. PBRMaterial.prototype.hasTexture = function (texture) {
  42991. if (_super.prototype.hasTexture.call(this, texture)) {
  42992. return true;
  42993. }
  42994. if (this._albedoTexture === texture) {
  42995. return true;
  42996. }
  42997. if (this._ambientTexture === texture) {
  42998. return true;
  42999. }
  43000. if (this._opacityTexture === texture) {
  43001. return true;
  43002. }
  43003. if (this._reflectionTexture === texture) {
  43004. return true;
  43005. }
  43006. if (this._reflectivityTexture === texture) {
  43007. return true;
  43008. }
  43009. if (this._metallicTexture === texture) {
  43010. return true;
  43011. }
  43012. if (this._microSurfaceTexture === texture) {
  43013. return true;
  43014. }
  43015. if (this._bumpTexture === texture) {
  43016. return true;
  43017. }
  43018. if (this._lightmapTexture === texture) {
  43019. return true;
  43020. }
  43021. if (this._refractionTexture === texture) {
  43022. return true;
  43023. }
  43024. return false;
  43025. };
  43026. /**
  43027. * Makes a duplicate of the current material.
  43028. * @param name - name to use for the new material.
  43029. */
  43030. PBRMaterial.prototype.clone = function (name) {
  43031. var _this = this;
  43032. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  43033. clone.id = name;
  43034. clone.name = name;
  43035. return clone;
  43036. };
  43037. /**
  43038. * Serializes this PBR Material.
  43039. * @returns - An object with the serialized material.
  43040. */
  43041. PBRMaterial.prototype.serialize = function () {
  43042. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  43043. serializationObject.customType = "BABYLON.PBRMaterial";
  43044. return serializationObject;
  43045. };
  43046. // Statics
  43047. /**
  43048. * Parses a PBR Material from a serialized object.
  43049. * @param source - Serialized object.
  43050. * @param scene - BJS scene instance.
  43051. * @param rootUrl - url for the scene object
  43052. * @returns - PBRMaterial
  43053. */
  43054. PBRMaterial.Parse = function (source, scene, rootUrl) {
  43055. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  43056. };
  43057. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  43058. /**
  43059. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  43060. */
  43061. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  43062. /**
  43063. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  43064. */
  43065. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  43066. /**
  43067. * 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.
  43068. * They are also discarded below the alpha cutoff threshold to improve performances.
  43069. */
  43070. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  43071. __decorate([
  43072. BABYLON.serialize(),
  43073. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43074. ], PBRMaterial.prototype, "directIntensity", void 0);
  43075. __decorate([
  43076. BABYLON.serialize(),
  43077. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43078. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  43079. __decorate([
  43080. BABYLON.serialize(),
  43081. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43082. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  43083. __decorate([
  43084. BABYLON.serialize(),
  43085. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43086. ], PBRMaterial.prototype, "specularIntensity", void 0);
  43087. __decorate([
  43088. BABYLON.serialize(),
  43089. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43090. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  43091. __decorate([
  43092. BABYLON.serializeAsTexture(),
  43093. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43094. ], PBRMaterial.prototype, "albedoTexture", void 0);
  43095. __decorate([
  43096. BABYLON.serializeAsTexture(),
  43097. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43098. ], PBRMaterial.prototype, "ambientTexture", void 0);
  43099. __decorate([
  43100. BABYLON.serialize(),
  43101. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43102. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  43103. __decorate([
  43104. BABYLON.serializeAsTexture(),
  43105. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43106. ], PBRMaterial.prototype, "opacityTexture", void 0);
  43107. __decorate([
  43108. BABYLON.serializeAsTexture(),
  43109. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43110. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  43111. __decorate([
  43112. BABYLON.serializeAsTexture(),
  43113. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43114. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  43115. __decorate([
  43116. BABYLON.serializeAsTexture(),
  43117. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43118. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  43119. __decorate([
  43120. BABYLON.serializeAsTexture(),
  43121. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43122. ], PBRMaterial.prototype, "metallicTexture", void 0);
  43123. __decorate([
  43124. BABYLON.serialize(),
  43125. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43126. ], PBRMaterial.prototype, "metallic", void 0);
  43127. __decorate([
  43128. BABYLON.serialize(),
  43129. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43130. ], PBRMaterial.prototype, "roughness", void 0);
  43131. __decorate([
  43132. BABYLON.serializeAsTexture(),
  43133. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43134. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  43135. __decorate([
  43136. BABYLON.serializeAsTexture(),
  43137. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43138. ], PBRMaterial.prototype, "bumpTexture", void 0);
  43139. __decorate([
  43140. BABYLON.serializeAsTexture(),
  43141. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  43142. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  43143. __decorate([
  43144. BABYLON.serializeAsTexture(),
  43145. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43146. ], PBRMaterial.prototype, "refractionTexture", void 0);
  43147. __decorate([
  43148. BABYLON.serializeAsColor3("ambient"),
  43149. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43150. ], PBRMaterial.prototype, "ambientColor", void 0);
  43151. __decorate([
  43152. BABYLON.serializeAsColor3("albedo"),
  43153. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43154. ], PBRMaterial.prototype, "albedoColor", void 0);
  43155. __decorate([
  43156. BABYLON.serializeAsColor3("reflectivity"),
  43157. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43158. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  43159. __decorate([
  43160. BABYLON.serializeAsColor3("reflection"),
  43161. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43162. ], PBRMaterial.prototype, "reflectionColor", void 0);
  43163. __decorate([
  43164. BABYLON.serializeAsColor3("emissive"),
  43165. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43166. ], PBRMaterial.prototype, "emissiveColor", void 0);
  43167. __decorate([
  43168. BABYLON.serialize(),
  43169. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43170. ], PBRMaterial.prototype, "microSurface", void 0);
  43171. __decorate([
  43172. BABYLON.serialize(),
  43173. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43174. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  43175. __decorate([
  43176. BABYLON.serialize(),
  43177. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43178. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  43179. __decorate([
  43180. BABYLON.serialize(),
  43181. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43182. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  43183. __decorate([
  43184. BABYLON.serialize(),
  43185. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43186. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  43187. __decorate([
  43188. BABYLON.serialize(),
  43189. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43190. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  43191. __decorate([
  43192. BABYLON.serialize(),
  43193. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43194. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  43195. __decorate([
  43196. BABYLON.serialize(),
  43197. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43198. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  43199. __decorate([
  43200. BABYLON.serialize(),
  43201. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43202. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  43203. __decorate([
  43204. BABYLON.serialize(),
  43205. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43206. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  43207. __decorate([
  43208. BABYLON.serialize(),
  43209. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43210. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  43211. __decorate([
  43212. BABYLON.serialize(),
  43213. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43214. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  43215. __decorate([
  43216. BABYLON.serialize(),
  43217. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43218. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  43219. __decorate([
  43220. BABYLON.serialize(),
  43221. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43222. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  43223. __decorate([
  43224. BABYLON.serialize(),
  43225. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43226. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  43227. __decorate([
  43228. BABYLON.serialize(),
  43229. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43230. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  43231. __decorate([
  43232. BABYLON.serialize(),
  43233. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43234. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  43235. __decorate([
  43236. BABYLON.serialize(),
  43237. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43238. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  43239. __decorate([
  43240. BABYLON.serialize(),
  43241. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43242. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  43243. __decorate([
  43244. BABYLON.serialize(),
  43245. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43246. ], PBRMaterial.prototype, "useParallax", void 0);
  43247. __decorate([
  43248. BABYLON.serialize(),
  43249. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43250. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  43251. __decorate([
  43252. BABYLON.serialize(),
  43253. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43254. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  43255. __decorate([
  43256. BABYLON.serialize(),
  43257. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43258. ], PBRMaterial.prototype, "disableLighting", void 0);
  43259. __decorate([
  43260. BABYLON.serialize(),
  43261. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43262. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  43263. __decorate([
  43264. BABYLON.serialize(),
  43265. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43266. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  43267. __decorate([
  43268. BABYLON.serialize(),
  43269. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43270. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  43271. __decorate([
  43272. BABYLON.serialize(),
  43273. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43274. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  43275. __decorate([
  43276. BABYLON.serialize(),
  43277. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43278. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  43279. __decorate([
  43280. BABYLON.serialize(),
  43281. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43282. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  43283. __decorate([
  43284. BABYLON.serialize(),
  43285. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43286. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  43287. __decorate([
  43288. BABYLON.serializeAsTexture(),
  43289. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43290. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  43291. __decorate([
  43292. BABYLON.serialize(),
  43293. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43294. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  43295. __decorate([
  43296. BABYLON.serialize(),
  43297. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43298. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  43299. __decorate([
  43300. BABYLON.serialize(),
  43301. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43302. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  43303. __decorate([
  43304. BABYLON.serialize(),
  43305. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43306. ], PBRMaterial.prototype, "unlit", void 0);
  43307. return PBRMaterial;
  43308. }(BABYLON.PBRBaseMaterial));
  43309. BABYLON.PBRMaterial = PBRMaterial;
  43310. })(BABYLON || (BABYLON = {}));
  43311. //# sourceMappingURL=babylon.pbrMaterial.js.map
  43312. "use strict";
  43313. var BABYLON;
  43314. (function (BABYLON) {
  43315. /**
  43316. * The PBR material of BJS following the metal roughness convention.
  43317. *
  43318. * This fits to the PBR convention in the GLTF definition:
  43319. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  43320. */
  43321. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  43322. __extends(PBRMetallicRoughnessMaterial, _super);
  43323. /**
  43324. * Instantiates a new PBRMetalRoughnessMaterial instance.
  43325. *
  43326. * @param name The material name
  43327. * @param scene The scene the material will be use in.
  43328. */
  43329. function PBRMetallicRoughnessMaterial(name, scene) {
  43330. var _this = _super.call(this, name, scene) || this;
  43331. _this._useRoughnessFromMetallicTextureAlpha = false;
  43332. _this._useRoughnessFromMetallicTextureGreen = true;
  43333. _this._useMetallnessFromMetallicTextureBlue = true;
  43334. _this.metallic = 1.0;
  43335. _this.roughness = 1.0;
  43336. return _this;
  43337. }
  43338. /**
  43339. * Return the currrent class name of the material.
  43340. */
  43341. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  43342. return "PBRMetallicRoughnessMaterial";
  43343. };
  43344. /**
  43345. * Return the active textures of the material.
  43346. */
  43347. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  43348. var activeTextures = _super.prototype.getActiveTextures.call(this);
  43349. if (this.baseTexture) {
  43350. activeTextures.push(this.baseTexture);
  43351. }
  43352. if (this.metallicRoughnessTexture) {
  43353. activeTextures.push(this.metallicRoughnessTexture);
  43354. }
  43355. return activeTextures;
  43356. };
  43357. /**
  43358. * Checks to see if a texture is used in the material.
  43359. * @param texture - Base texture to use.
  43360. * @returns - Boolean specifying if a texture is used in the material.
  43361. */
  43362. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  43363. if (_super.prototype.hasTexture.call(this, texture)) {
  43364. return true;
  43365. }
  43366. if (this.baseTexture === texture) {
  43367. return true;
  43368. }
  43369. if (this.metallicRoughnessTexture === texture) {
  43370. return true;
  43371. }
  43372. return false;
  43373. };
  43374. /**
  43375. * Makes a duplicate of the current material.
  43376. * @param name - name to use for the new material.
  43377. */
  43378. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  43379. var _this = this;
  43380. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  43381. clone.id = name;
  43382. clone.name = name;
  43383. return clone;
  43384. };
  43385. /**
  43386. * Serialize the material to a parsable JSON object.
  43387. */
  43388. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  43389. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  43390. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  43391. return serializationObject;
  43392. };
  43393. /**
  43394. * Parses a JSON object correponding to the serialize function.
  43395. */
  43396. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  43397. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  43398. };
  43399. __decorate([
  43400. BABYLON.serializeAsColor3(),
  43401. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  43402. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  43403. __decorate([
  43404. BABYLON.serializeAsTexture(),
  43405. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  43406. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  43407. __decorate([
  43408. BABYLON.serialize(),
  43409. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43410. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  43411. __decorate([
  43412. BABYLON.serialize(),
  43413. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43414. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  43415. __decorate([
  43416. BABYLON.serializeAsTexture(),
  43417. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  43418. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  43419. return PBRMetallicRoughnessMaterial;
  43420. }(BABYLON.PBRBaseSimpleMaterial));
  43421. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  43422. })(BABYLON || (BABYLON = {}));
  43423. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  43424. "use strict";
  43425. var BABYLON;
  43426. (function (BABYLON) {
  43427. /**
  43428. * The PBR material of BJS following the specular glossiness convention.
  43429. *
  43430. * This fits to the PBR convention in the GLTF definition:
  43431. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  43432. */
  43433. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  43434. __extends(PBRSpecularGlossinessMaterial, _super);
  43435. /**
  43436. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  43437. *
  43438. * @param name The material name
  43439. * @param scene The scene the material will be use in.
  43440. */
  43441. function PBRSpecularGlossinessMaterial(name, scene) {
  43442. var _this = _super.call(this, name, scene) || this;
  43443. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  43444. return _this;
  43445. }
  43446. /**
  43447. * Return the currrent class name of the material.
  43448. */
  43449. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  43450. return "PBRSpecularGlossinessMaterial";
  43451. };
  43452. /**
  43453. * Return the active textures of the material.
  43454. */
  43455. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  43456. var activeTextures = _super.prototype.getActiveTextures.call(this);
  43457. if (this.diffuseTexture) {
  43458. activeTextures.push(this.diffuseTexture);
  43459. }
  43460. if (this.specularGlossinessTexture) {
  43461. activeTextures.push(this.specularGlossinessTexture);
  43462. }
  43463. return activeTextures;
  43464. };
  43465. /**
  43466. * Checks to see if a texture is used in the material.
  43467. * @param texture - Base texture to use.
  43468. * @returns - Boolean specifying if a texture is used in the material.
  43469. */
  43470. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  43471. if (_super.prototype.hasTexture.call(this, texture)) {
  43472. return true;
  43473. }
  43474. if (this.diffuseTexture === texture) {
  43475. return true;
  43476. }
  43477. if (this.specularGlossinessTexture === texture) {
  43478. return true;
  43479. }
  43480. return false;
  43481. };
  43482. /**
  43483. * Makes a duplicate of the current material.
  43484. * @param name - name to use for the new material.
  43485. */
  43486. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  43487. var _this = this;
  43488. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  43489. clone.id = name;
  43490. clone.name = name;
  43491. return clone;
  43492. };
  43493. /**
  43494. * Serialize the material to a parsable JSON object.
  43495. */
  43496. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  43497. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  43498. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  43499. return serializationObject;
  43500. };
  43501. /**
  43502. * Parses a JSON object correponding to the serialize function.
  43503. */
  43504. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  43505. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  43506. };
  43507. __decorate([
  43508. BABYLON.serializeAsColor3("diffuse"),
  43509. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  43510. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  43511. __decorate([
  43512. BABYLON.serializeAsTexture(),
  43513. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  43514. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  43515. __decorate([
  43516. BABYLON.serializeAsColor3("specular"),
  43517. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  43518. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  43519. __decorate([
  43520. BABYLON.serialize(),
  43521. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  43522. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  43523. __decorate([
  43524. BABYLON.serializeAsTexture(),
  43525. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  43526. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  43527. return PBRSpecularGlossinessMaterial;
  43528. }(BABYLON.PBRBaseSimpleMaterial));
  43529. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  43530. })(BABYLON || (BABYLON = {}));
  43531. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  43532. "use strict";
  43533. var BABYLON;
  43534. (function (BABYLON) {
  43535. BABYLON.CameraInputTypes = {};
  43536. var CameraInputsManager = /** @class */ (function () {
  43537. function CameraInputsManager(camera) {
  43538. this.attached = {};
  43539. this.camera = camera;
  43540. this.checkInputs = function () { };
  43541. }
  43542. /**
  43543. * Add an input method to a camera.
  43544. * builtin inputs example: camera.inputs.addGamepad();
  43545. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  43546. * @param input camera input method
  43547. */
  43548. CameraInputsManager.prototype.add = function (input) {
  43549. var type = input.getSimpleName();
  43550. if (this.attached[type]) {
  43551. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  43552. return;
  43553. }
  43554. this.attached[type] = input;
  43555. input.camera = this.camera;
  43556. //for checkInputs, we are dynamically creating a function
  43557. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  43558. if (input.checkInputs) {
  43559. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  43560. }
  43561. if (this.attachedElement) {
  43562. input.attachControl(this.attachedElement);
  43563. }
  43564. };
  43565. /**
  43566. * Remove a specific input method from a camera
  43567. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  43568. * @param inputToRemove camera input method
  43569. */
  43570. CameraInputsManager.prototype.remove = function (inputToRemove) {
  43571. for (var cam in this.attached) {
  43572. var input = this.attached[cam];
  43573. if (input === inputToRemove) {
  43574. input.detachControl(this.attachedElement);
  43575. input.camera = null;
  43576. delete this.attached[cam];
  43577. this.rebuildInputCheck();
  43578. }
  43579. }
  43580. };
  43581. CameraInputsManager.prototype.removeByType = function (inputType) {
  43582. for (var cam in this.attached) {
  43583. var input = this.attached[cam];
  43584. if (input.getClassName() === inputType) {
  43585. input.detachControl(this.attachedElement);
  43586. input.camera = null;
  43587. delete this.attached[cam];
  43588. this.rebuildInputCheck();
  43589. }
  43590. }
  43591. };
  43592. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  43593. var current = this.checkInputs;
  43594. return function () {
  43595. current();
  43596. fn();
  43597. };
  43598. };
  43599. CameraInputsManager.prototype.attachInput = function (input) {
  43600. if (this.attachedElement) {
  43601. input.attachControl(this.attachedElement, this.noPreventDefault);
  43602. }
  43603. };
  43604. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  43605. if (noPreventDefault === void 0) { noPreventDefault = false; }
  43606. if (this.attachedElement) {
  43607. return;
  43608. }
  43609. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  43610. this.attachedElement = element;
  43611. this.noPreventDefault = noPreventDefault;
  43612. for (var cam in this.attached) {
  43613. this.attached[cam].attachControl(element, noPreventDefault);
  43614. }
  43615. };
  43616. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  43617. if (disconnect === void 0) { disconnect = false; }
  43618. if (this.attachedElement !== element) {
  43619. return;
  43620. }
  43621. for (var cam in this.attached) {
  43622. this.attached[cam].detachControl(element);
  43623. if (disconnect) {
  43624. this.attached[cam].camera = null;
  43625. }
  43626. }
  43627. this.attachedElement = null;
  43628. };
  43629. CameraInputsManager.prototype.rebuildInputCheck = function () {
  43630. this.checkInputs = function () { };
  43631. for (var cam in this.attached) {
  43632. var input = this.attached[cam];
  43633. if (input.checkInputs) {
  43634. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  43635. }
  43636. }
  43637. };
  43638. /**
  43639. * Remove all attached input methods from a camera
  43640. */
  43641. CameraInputsManager.prototype.clear = function () {
  43642. if (this.attachedElement) {
  43643. this.detachElement(this.attachedElement, true);
  43644. }
  43645. this.attached = {};
  43646. this.attachedElement = null;
  43647. this.checkInputs = function () { };
  43648. };
  43649. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  43650. var inputs = {};
  43651. for (var cam in this.attached) {
  43652. var input = this.attached[cam];
  43653. var res = BABYLON.SerializationHelper.Serialize(input);
  43654. inputs[input.getClassName()] = res;
  43655. }
  43656. serializedCamera.inputsmgr = inputs;
  43657. };
  43658. CameraInputsManager.prototype.parse = function (parsedCamera) {
  43659. var parsedInputs = parsedCamera.inputsmgr;
  43660. if (parsedInputs) {
  43661. this.clear();
  43662. for (var n in parsedInputs) {
  43663. var construct = BABYLON.CameraInputTypes[n];
  43664. if (construct) {
  43665. var parsedinput = parsedInputs[n];
  43666. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  43667. this.add(input);
  43668. }
  43669. }
  43670. }
  43671. else {
  43672. //2016-03-08 this part is for managing backward compatibility
  43673. for (var n in this.attached) {
  43674. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  43675. if (construct) {
  43676. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  43677. this.remove(this.attached[n]);
  43678. this.add(input);
  43679. }
  43680. }
  43681. }
  43682. };
  43683. return CameraInputsManager;
  43684. }());
  43685. BABYLON.CameraInputsManager = CameraInputsManager;
  43686. })(BABYLON || (BABYLON = {}));
  43687. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  43688. "use strict";
  43689. var BABYLON;
  43690. (function (BABYLON) {
  43691. var TargetCamera = /** @class */ (function (_super) {
  43692. __extends(TargetCamera, _super);
  43693. function TargetCamera(name, position, scene) {
  43694. var _this = _super.call(this, name, position, scene) || this;
  43695. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  43696. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  43697. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  43698. _this.speed = 2.0;
  43699. _this.noRotationConstraint = false;
  43700. _this.lockedTarget = null;
  43701. _this._currentTarget = BABYLON.Vector3.Zero();
  43702. _this._viewMatrix = BABYLON.Matrix.Zero();
  43703. _this._camMatrix = BABYLON.Matrix.Zero();
  43704. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  43705. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  43706. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  43707. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  43708. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  43709. _this._lookAtTemp = BABYLON.Matrix.Zero();
  43710. _this._tempMatrix = BABYLON.Matrix.Zero();
  43711. return _this;
  43712. }
  43713. TargetCamera.prototype.getFrontPosition = function (distance) {
  43714. this.getWorldMatrix();
  43715. var direction = this.getTarget().subtract(this.position);
  43716. direction.normalize();
  43717. direction.scaleInPlace(distance);
  43718. return this.globalPosition.add(direction);
  43719. };
  43720. TargetCamera.prototype._getLockedTargetPosition = function () {
  43721. if (!this.lockedTarget) {
  43722. return null;
  43723. }
  43724. if (this.lockedTarget.absolutePosition) {
  43725. this.lockedTarget.computeWorldMatrix();
  43726. }
  43727. return this.lockedTarget.absolutePosition || this.lockedTarget;
  43728. };
  43729. TargetCamera.prototype.storeState = function () {
  43730. this._storedPosition = this.position.clone();
  43731. this._storedRotation = this.rotation.clone();
  43732. if (this.rotationQuaternion) {
  43733. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  43734. }
  43735. return _super.prototype.storeState.call(this);
  43736. };
  43737. /**
  43738. * Restored camera state. You must call storeState() first
  43739. */
  43740. TargetCamera.prototype._restoreStateValues = function () {
  43741. if (!_super.prototype._restoreStateValues.call(this)) {
  43742. return false;
  43743. }
  43744. this.position = this._storedPosition.clone();
  43745. this.rotation = this._storedRotation.clone();
  43746. if (this.rotationQuaternion) {
  43747. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  43748. }
  43749. this.cameraDirection.copyFromFloats(0, 0, 0);
  43750. this.cameraRotation.copyFromFloats(0, 0);
  43751. return true;
  43752. };
  43753. // Cache
  43754. TargetCamera.prototype._initCache = function () {
  43755. _super.prototype._initCache.call(this);
  43756. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43757. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43758. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43759. };
  43760. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  43761. if (!ignoreParentClass) {
  43762. _super.prototype._updateCache.call(this);
  43763. }
  43764. var lockedTargetPosition = this._getLockedTargetPosition();
  43765. if (!lockedTargetPosition) {
  43766. this._cache.lockedTarget = null;
  43767. }
  43768. else {
  43769. if (!this._cache.lockedTarget) {
  43770. this._cache.lockedTarget = lockedTargetPosition.clone();
  43771. }
  43772. else {
  43773. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  43774. }
  43775. }
  43776. this._cache.rotation.copyFrom(this.rotation);
  43777. if (this.rotationQuaternion)
  43778. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43779. };
  43780. // Synchronized
  43781. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  43782. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  43783. return false;
  43784. }
  43785. var lockedTargetPosition = this._getLockedTargetPosition();
  43786. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  43787. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  43788. };
  43789. // Methods
  43790. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  43791. var engine = this.getEngine();
  43792. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  43793. };
  43794. // Target
  43795. TargetCamera.prototype.setTarget = function (target) {
  43796. this.upVector.normalize();
  43797. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  43798. this._camMatrix.invert();
  43799. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  43800. var vDir = target.subtract(this.position);
  43801. if (vDir.x >= 0.0) {
  43802. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  43803. }
  43804. else {
  43805. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  43806. }
  43807. this.rotation.z = 0;
  43808. if (isNaN(this.rotation.x)) {
  43809. this.rotation.x = 0;
  43810. }
  43811. if (isNaN(this.rotation.y)) {
  43812. this.rotation.y = 0;
  43813. }
  43814. if (isNaN(this.rotation.z)) {
  43815. this.rotation.z = 0;
  43816. }
  43817. if (this.rotationQuaternion) {
  43818. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  43819. }
  43820. };
  43821. /**
  43822. * Return the current target position of the camera. This value is expressed in local space.
  43823. */
  43824. TargetCamera.prototype.getTarget = function () {
  43825. return this._currentTarget;
  43826. };
  43827. TargetCamera.prototype._decideIfNeedsToMove = function () {
  43828. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  43829. };
  43830. TargetCamera.prototype._updatePosition = function () {
  43831. if (this.parent) {
  43832. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  43833. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  43834. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  43835. return;
  43836. }
  43837. this.position.addInPlace(this.cameraDirection);
  43838. };
  43839. TargetCamera.prototype._checkInputs = function () {
  43840. var needToMove = this._decideIfNeedsToMove();
  43841. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  43842. // Move
  43843. if (needToMove) {
  43844. this._updatePosition();
  43845. }
  43846. // Rotate
  43847. if (needToRotate) {
  43848. this.rotation.x += this.cameraRotation.x;
  43849. this.rotation.y += this.cameraRotation.y;
  43850. //rotate, if quaternion is set and rotation was used
  43851. if (this.rotationQuaternion) {
  43852. var len = this.rotation.lengthSquared();
  43853. if (len) {
  43854. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  43855. }
  43856. }
  43857. if (!this.noRotationConstraint) {
  43858. var limit = (Math.PI / 2) * 0.95;
  43859. if (this.rotation.x > limit)
  43860. this.rotation.x = limit;
  43861. if (this.rotation.x < -limit)
  43862. this.rotation.x = -limit;
  43863. }
  43864. }
  43865. // Inertia
  43866. if (needToMove) {
  43867. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  43868. this.cameraDirection.x = 0;
  43869. }
  43870. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  43871. this.cameraDirection.y = 0;
  43872. }
  43873. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  43874. this.cameraDirection.z = 0;
  43875. }
  43876. this.cameraDirection.scaleInPlace(this.inertia);
  43877. }
  43878. if (needToRotate) {
  43879. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  43880. this.cameraRotation.x = 0;
  43881. }
  43882. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  43883. this.cameraRotation.y = 0;
  43884. }
  43885. this.cameraRotation.scaleInPlace(this.inertia);
  43886. }
  43887. _super.prototype._checkInputs.call(this);
  43888. };
  43889. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  43890. if (this.rotationQuaternion) {
  43891. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  43892. }
  43893. else {
  43894. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  43895. }
  43896. //update the up vector!
  43897. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  43898. };
  43899. TargetCamera.prototype._getViewMatrix = function () {
  43900. if (this.lockedTarget) {
  43901. this.setTarget(this._getLockedTargetPosition());
  43902. }
  43903. // Compute
  43904. this._updateCameraRotationMatrix();
  43905. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  43906. // Computing target and final matrix
  43907. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  43908. if (this.getScene().useRightHandedSystem) {
  43909. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  43910. }
  43911. else {
  43912. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  43913. }
  43914. return this._viewMatrix;
  43915. };
  43916. /**
  43917. * @override
  43918. * Override Camera.createRigCamera
  43919. */
  43920. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  43921. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  43922. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  43923. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  43924. if (!this.rotationQuaternion) {
  43925. this.rotationQuaternion = new BABYLON.Quaternion();
  43926. }
  43927. rigCamera._cameraRigParams = {};
  43928. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  43929. }
  43930. return rigCamera;
  43931. }
  43932. return null;
  43933. };
  43934. /**
  43935. * @override
  43936. * Override Camera._updateRigCameras
  43937. */
  43938. TargetCamera.prototype._updateRigCameras = function () {
  43939. var camLeft = this._rigCameras[0];
  43940. var camRight = this._rigCameras[1];
  43941. switch (this.cameraRigMode) {
  43942. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  43943. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  43944. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  43945. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  43946. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  43947. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  43948. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  43949. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  43950. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  43951. camLeft.setTarget(this.getTarget());
  43952. camRight.setTarget(this.getTarget());
  43953. break;
  43954. case BABYLON.Camera.RIG_MODE_VR:
  43955. if (camLeft.rotationQuaternion) {
  43956. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43957. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43958. }
  43959. else {
  43960. camLeft.rotation.copyFrom(this.rotation);
  43961. camRight.rotation.copyFrom(this.rotation);
  43962. }
  43963. camLeft.position.copyFrom(this.position);
  43964. camRight.position.copyFrom(this.position);
  43965. break;
  43966. }
  43967. _super.prototype._updateRigCameras.call(this);
  43968. };
  43969. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  43970. if (!this._rigCamTransformMatrix) {
  43971. this._rigCamTransformMatrix = new BABYLON.Matrix();
  43972. }
  43973. var target = this.getTarget();
  43974. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  43975. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  43976. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  43977. };
  43978. TargetCamera.prototype.getClassName = function () {
  43979. return "TargetCamera";
  43980. };
  43981. __decorate([
  43982. BABYLON.serializeAsVector3()
  43983. ], TargetCamera.prototype, "rotation", void 0);
  43984. __decorate([
  43985. BABYLON.serialize()
  43986. ], TargetCamera.prototype, "speed", void 0);
  43987. __decorate([
  43988. BABYLON.serializeAsMeshReference("lockedTargetId")
  43989. ], TargetCamera.prototype, "lockedTarget", void 0);
  43990. return TargetCamera;
  43991. }(BABYLON.Camera));
  43992. BABYLON.TargetCamera = TargetCamera;
  43993. })(BABYLON || (BABYLON = {}));
  43994. //# sourceMappingURL=babylon.targetCamera.js.map
  43995. "use strict";
  43996. var BABYLON;
  43997. (function (BABYLON) {
  43998. var FreeCameraMouseInput = /** @class */ (function () {
  43999. function FreeCameraMouseInput(touchEnabled) {
  44000. if (touchEnabled === void 0) { touchEnabled = true; }
  44001. this.touchEnabled = touchEnabled;
  44002. this.buttons = [0, 1, 2];
  44003. this.angularSensibility = 2000.0;
  44004. this.previousPosition = null;
  44005. }
  44006. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  44007. var _this = this;
  44008. var engine = this.camera.getEngine();
  44009. if (!this._pointerInput) {
  44010. this._pointerInput = function (p, s) {
  44011. var evt = p.event;
  44012. if (engine.isInVRExclusivePointerMode) {
  44013. return;
  44014. }
  44015. if (!_this.touchEnabled && evt.pointerType === "touch") {
  44016. return;
  44017. }
  44018. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  44019. return;
  44020. }
  44021. var srcElement = (evt.srcElement || evt.target);
  44022. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  44023. try {
  44024. srcElement.setPointerCapture(evt.pointerId);
  44025. }
  44026. catch (e) {
  44027. //Nothing to do with the error. Execution will continue.
  44028. }
  44029. _this.previousPosition = {
  44030. x: evt.clientX,
  44031. y: evt.clientY
  44032. };
  44033. if (!noPreventDefault) {
  44034. evt.preventDefault();
  44035. element.focus();
  44036. }
  44037. }
  44038. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  44039. try {
  44040. srcElement.releasePointerCapture(evt.pointerId);
  44041. }
  44042. catch (e) {
  44043. //Nothing to do with the error.
  44044. }
  44045. _this.previousPosition = null;
  44046. if (!noPreventDefault) {
  44047. evt.preventDefault();
  44048. }
  44049. }
  44050. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  44051. if (!_this.previousPosition || engine.isPointerLock) {
  44052. return;
  44053. }
  44054. var offsetX = evt.clientX - _this.previousPosition.x;
  44055. var offsetY = evt.clientY - _this.previousPosition.y;
  44056. if (_this.camera.getScene().useRightHandedSystem) {
  44057. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  44058. }
  44059. else {
  44060. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  44061. }
  44062. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  44063. _this.previousPosition = {
  44064. x: evt.clientX,
  44065. y: evt.clientY
  44066. };
  44067. if (!noPreventDefault) {
  44068. evt.preventDefault();
  44069. }
  44070. }
  44071. };
  44072. }
  44073. this._onMouseMove = function (evt) {
  44074. if (!engine.isPointerLock) {
  44075. return;
  44076. }
  44077. if (engine.isInVRExclusivePointerMode) {
  44078. return;
  44079. }
  44080. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  44081. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  44082. if (_this.camera.getScene().useRightHandedSystem) {
  44083. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  44084. }
  44085. else {
  44086. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  44087. }
  44088. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  44089. _this.previousPosition = null;
  44090. if (!noPreventDefault) {
  44091. evt.preventDefault();
  44092. }
  44093. };
  44094. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  44095. element.addEventListener("mousemove", this._onMouseMove, false);
  44096. };
  44097. FreeCameraMouseInput.prototype.detachControl = function (element) {
  44098. if (this._observer && element) {
  44099. this.camera.getScene().onPointerObservable.remove(this._observer);
  44100. if (this._onMouseMove) {
  44101. element.removeEventListener("mousemove", this._onMouseMove);
  44102. }
  44103. this._observer = null;
  44104. this._onMouseMove = null;
  44105. this.previousPosition = null;
  44106. }
  44107. };
  44108. FreeCameraMouseInput.prototype.getClassName = function () {
  44109. return "FreeCameraMouseInput";
  44110. };
  44111. FreeCameraMouseInput.prototype.getSimpleName = function () {
  44112. return "mouse";
  44113. };
  44114. __decorate([
  44115. BABYLON.serialize()
  44116. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  44117. __decorate([
  44118. BABYLON.serialize()
  44119. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  44120. return FreeCameraMouseInput;
  44121. }());
  44122. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  44123. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  44124. })(BABYLON || (BABYLON = {}));
  44125. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  44126. "use strict";
  44127. var BABYLON;
  44128. (function (BABYLON) {
  44129. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  44130. function FreeCameraKeyboardMoveInput() {
  44131. this._keys = new Array();
  44132. this.keysUp = [38];
  44133. this.keysDown = [40];
  44134. this.keysLeft = [37];
  44135. this.keysRight = [39];
  44136. }
  44137. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  44138. var _this = this;
  44139. if (this._onCanvasBlurObserver) {
  44140. return;
  44141. }
  44142. this._scene = this.camera.getScene();
  44143. this._engine = this._scene.getEngine();
  44144. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  44145. _this._keys = [];
  44146. });
  44147. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  44148. var evt = info.event;
  44149. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  44150. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  44151. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  44152. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  44153. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  44154. var index = _this._keys.indexOf(evt.keyCode);
  44155. if (index === -1) {
  44156. _this._keys.push(evt.keyCode);
  44157. }
  44158. if (!noPreventDefault) {
  44159. evt.preventDefault();
  44160. }
  44161. }
  44162. }
  44163. else {
  44164. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  44165. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  44166. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  44167. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  44168. var index = _this._keys.indexOf(evt.keyCode);
  44169. if (index >= 0) {
  44170. _this._keys.splice(index, 1);
  44171. }
  44172. if (!noPreventDefault) {
  44173. evt.preventDefault();
  44174. }
  44175. }
  44176. }
  44177. });
  44178. };
  44179. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  44180. if (this._scene) {
  44181. if (this._onKeyboardObserver) {
  44182. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  44183. }
  44184. if (this._onCanvasBlurObserver) {
  44185. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  44186. }
  44187. this._onKeyboardObserver = null;
  44188. this._onCanvasBlurObserver = null;
  44189. }
  44190. this._keys = [];
  44191. };
  44192. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  44193. if (this._onKeyboardObserver) {
  44194. var camera = this.camera;
  44195. // Keyboard
  44196. for (var index = 0; index < this._keys.length; index++) {
  44197. var keyCode = this._keys[index];
  44198. var speed = camera._computeLocalCameraSpeed();
  44199. if (this.keysLeft.indexOf(keyCode) !== -1) {
  44200. camera._localDirection.copyFromFloats(-speed, 0, 0);
  44201. }
  44202. else if (this.keysUp.indexOf(keyCode) !== -1) {
  44203. camera._localDirection.copyFromFloats(0, 0, speed);
  44204. }
  44205. else if (this.keysRight.indexOf(keyCode) !== -1) {
  44206. camera._localDirection.copyFromFloats(speed, 0, 0);
  44207. }
  44208. else if (this.keysDown.indexOf(keyCode) !== -1) {
  44209. camera._localDirection.copyFromFloats(0, 0, -speed);
  44210. }
  44211. if (camera.getScene().useRightHandedSystem) {
  44212. camera._localDirection.z *= -1;
  44213. }
  44214. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  44215. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  44216. camera.cameraDirection.addInPlace(camera._transformedDirection);
  44217. }
  44218. }
  44219. };
  44220. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  44221. return "FreeCameraKeyboardMoveInput";
  44222. };
  44223. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  44224. this._keys = [];
  44225. };
  44226. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  44227. return "keyboard";
  44228. };
  44229. __decorate([
  44230. BABYLON.serialize()
  44231. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  44232. __decorate([
  44233. BABYLON.serialize()
  44234. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  44235. __decorate([
  44236. BABYLON.serialize()
  44237. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  44238. __decorate([
  44239. BABYLON.serialize()
  44240. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  44241. return FreeCameraKeyboardMoveInput;
  44242. }());
  44243. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  44244. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  44245. })(BABYLON || (BABYLON = {}));
  44246. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  44247. "use strict";
  44248. var BABYLON;
  44249. (function (BABYLON) {
  44250. var FreeCameraInputsManager = /** @class */ (function (_super) {
  44251. __extends(FreeCameraInputsManager, _super);
  44252. function FreeCameraInputsManager(camera) {
  44253. return _super.call(this, camera) || this;
  44254. }
  44255. FreeCameraInputsManager.prototype.addKeyboard = function () {
  44256. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  44257. return this;
  44258. };
  44259. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  44260. if (touchEnabled === void 0) { touchEnabled = true; }
  44261. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  44262. return this;
  44263. };
  44264. FreeCameraInputsManager.prototype.addGamepad = function () {
  44265. this.add(new BABYLON.FreeCameraGamepadInput());
  44266. return this;
  44267. };
  44268. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  44269. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  44270. return this;
  44271. };
  44272. FreeCameraInputsManager.prototype.addTouch = function () {
  44273. this.add(new BABYLON.FreeCameraTouchInput());
  44274. return this;
  44275. };
  44276. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  44277. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  44278. return this;
  44279. };
  44280. return FreeCameraInputsManager;
  44281. }(BABYLON.CameraInputsManager));
  44282. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  44283. })(BABYLON || (BABYLON = {}));
  44284. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  44285. "use strict";
  44286. var BABYLON;
  44287. (function (BABYLON) {
  44288. var FreeCamera = /** @class */ (function (_super) {
  44289. __extends(FreeCamera, _super);
  44290. function FreeCamera(name, position, scene) {
  44291. var _this = _super.call(this, name, position, scene) || this;
  44292. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  44293. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  44294. _this.checkCollisions = false;
  44295. _this.applyGravity = false;
  44296. _this._needMoveForGravity = false;
  44297. _this._oldPosition = BABYLON.Vector3.Zero();
  44298. _this._diffPosition = BABYLON.Vector3.Zero();
  44299. _this._newPosition = BABYLON.Vector3.Zero();
  44300. // Collisions
  44301. _this._collisionMask = -1;
  44302. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  44303. if (collidedMesh === void 0) { collidedMesh = null; }
  44304. //TODO move this to the collision coordinator!
  44305. if (_this.getScene().workerCollisions)
  44306. newPosition.multiplyInPlace(_this._collider._radius);
  44307. var updatePosition = function (newPos) {
  44308. _this._newPosition.copyFrom(newPos);
  44309. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  44310. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  44311. _this.position.addInPlace(_this._diffPosition);
  44312. if (_this.onCollide && collidedMesh) {
  44313. _this.onCollide(collidedMesh);
  44314. }
  44315. }
  44316. };
  44317. updatePosition(newPosition);
  44318. };
  44319. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  44320. _this.inputs.addKeyboard().addMouse();
  44321. return _this;
  44322. }
  44323. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  44324. //-- begin properties for backward compatibility for inputs
  44325. /**
  44326. * Gets the input sensibility for a mouse input. (default is 2000.0)
  44327. * Higher values reduce sensitivity.
  44328. */
  44329. get: function () {
  44330. var mouse = this.inputs.attached["mouse"];
  44331. if (mouse)
  44332. return mouse.angularSensibility;
  44333. return 0;
  44334. },
  44335. /**
  44336. * Sets the input sensibility for a mouse input. (default is 2000.0)
  44337. * Higher values reduce sensitivity.
  44338. */
  44339. set: function (value) {
  44340. var mouse = this.inputs.attached["mouse"];
  44341. if (mouse)
  44342. mouse.angularSensibility = value;
  44343. },
  44344. enumerable: true,
  44345. configurable: true
  44346. });
  44347. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  44348. get: function () {
  44349. var keyboard = this.inputs.attached["keyboard"];
  44350. if (keyboard)
  44351. return keyboard.keysUp;
  44352. return [];
  44353. },
  44354. set: function (value) {
  44355. var keyboard = this.inputs.attached["keyboard"];
  44356. if (keyboard)
  44357. keyboard.keysUp = value;
  44358. },
  44359. enumerable: true,
  44360. configurable: true
  44361. });
  44362. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  44363. get: function () {
  44364. var keyboard = this.inputs.attached["keyboard"];
  44365. if (keyboard)
  44366. return keyboard.keysDown;
  44367. return [];
  44368. },
  44369. set: function (value) {
  44370. var keyboard = this.inputs.attached["keyboard"];
  44371. if (keyboard)
  44372. keyboard.keysDown = value;
  44373. },
  44374. enumerable: true,
  44375. configurable: true
  44376. });
  44377. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  44378. get: function () {
  44379. var keyboard = this.inputs.attached["keyboard"];
  44380. if (keyboard)
  44381. return keyboard.keysLeft;
  44382. return [];
  44383. },
  44384. set: function (value) {
  44385. var keyboard = this.inputs.attached["keyboard"];
  44386. if (keyboard)
  44387. keyboard.keysLeft = value;
  44388. },
  44389. enumerable: true,
  44390. configurable: true
  44391. });
  44392. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  44393. get: function () {
  44394. var keyboard = this.inputs.attached["keyboard"];
  44395. if (keyboard)
  44396. return keyboard.keysRight;
  44397. return [];
  44398. },
  44399. set: function (value) {
  44400. var keyboard = this.inputs.attached["keyboard"];
  44401. if (keyboard)
  44402. keyboard.keysRight = value;
  44403. },
  44404. enumerable: true,
  44405. configurable: true
  44406. });
  44407. // Controls
  44408. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  44409. this.inputs.attachElement(element, noPreventDefault);
  44410. };
  44411. FreeCamera.prototype.detachControl = function (element) {
  44412. this.inputs.detachElement(element);
  44413. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  44414. this.cameraRotation = new BABYLON.Vector2(0, 0);
  44415. };
  44416. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  44417. get: function () {
  44418. return this._collisionMask;
  44419. },
  44420. set: function (mask) {
  44421. this._collisionMask = !isNaN(mask) ? mask : -1;
  44422. },
  44423. enumerable: true,
  44424. configurable: true
  44425. });
  44426. FreeCamera.prototype._collideWithWorld = function (displacement) {
  44427. var globalPosition;
  44428. if (this.parent) {
  44429. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  44430. }
  44431. else {
  44432. globalPosition = this.position;
  44433. }
  44434. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  44435. this._oldPosition.addInPlace(this.ellipsoidOffset);
  44436. if (!this._collider) {
  44437. this._collider = new BABYLON.Collider();
  44438. }
  44439. this._collider._radius = this.ellipsoid;
  44440. this._collider.collisionMask = this._collisionMask;
  44441. //no need for clone, as long as gravity is not on.
  44442. var actualDisplacement = displacement;
  44443. //add gravity to the direction to prevent the dual-collision checking
  44444. if (this.applyGravity) {
  44445. //this prevents mending with cameraDirection, a global variable of the free camera class.
  44446. actualDisplacement = displacement.add(this.getScene().gravity);
  44447. }
  44448. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  44449. };
  44450. FreeCamera.prototype._checkInputs = function () {
  44451. if (!this._localDirection) {
  44452. this._localDirection = BABYLON.Vector3.Zero();
  44453. this._transformedDirection = BABYLON.Vector3.Zero();
  44454. }
  44455. this.inputs.checkInputs();
  44456. _super.prototype._checkInputs.call(this);
  44457. };
  44458. FreeCamera.prototype._decideIfNeedsToMove = function () {
  44459. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  44460. };
  44461. FreeCamera.prototype._updatePosition = function () {
  44462. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  44463. this._collideWithWorld(this.cameraDirection);
  44464. }
  44465. else {
  44466. _super.prototype._updatePosition.call(this);
  44467. }
  44468. };
  44469. FreeCamera.prototype.dispose = function () {
  44470. this.inputs.clear();
  44471. _super.prototype.dispose.call(this);
  44472. };
  44473. FreeCamera.prototype.getClassName = function () {
  44474. return "FreeCamera";
  44475. };
  44476. __decorate([
  44477. BABYLON.serializeAsVector3()
  44478. ], FreeCamera.prototype, "ellipsoid", void 0);
  44479. __decorate([
  44480. BABYLON.serializeAsVector3()
  44481. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  44482. __decorate([
  44483. BABYLON.serialize()
  44484. ], FreeCamera.prototype, "checkCollisions", void 0);
  44485. __decorate([
  44486. BABYLON.serialize()
  44487. ], FreeCamera.prototype, "applyGravity", void 0);
  44488. return FreeCamera;
  44489. }(BABYLON.TargetCamera));
  44490. BABYLON.FreeCamera = FreeCamera;
  44491. })(BABYLON || (BABYLON = {}));
  44492. //# sourceMappingURL=babylon.freeCamera.js.map
  44493. "use strict";
  44494. var BABYLON;
  44495. (function (BABYLON) {
  44496. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  44497. function ArcRotateCameraKeyboardMoveInput() {
  44498. this._keys = new Array();
  44499. this.keysUp = [38];
  44500. this.keysDown = [40];
  44501. this.keysLeft = [37];
  44502. this.keysRight = [39];
  44503. this.keysReset = [220];
  44504. this.panningSensibility = 50.0;
  44505. this.zoomingSensibility = 25.0;
  44506. this.useAltToZoom = true;
  44507. }
  44508. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  44509. var _this = this;
  44510. if (this._onCanvasBlurObserver) {
  44511. return;
  44512. }
  44513. this._scene = this.camera.getScene();
  44514. this._engine = this._scene.getEngine();
  44515. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  44516. _this._keys = [];
  44517. });
  44518. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  44519. var evt = info.event;
  44520. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  44521. _this._ctrlPressed = evt.ctrlKey;
  44522. _this._altPressed = evt.altKey;
  44523. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  44524. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  44525. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  44526. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  44527. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  44528. var index = _this._keys.indexOf(evt.keyCode);
  44529. if (index === -1) {
  44530. _this._keys.push(evt.keyCode);
  44531. }
  44532. if (evt.preventDefault) {
  44533. if (!noPreventDefault) {
  44534. evt.preventDefault();
  44535. }
  44536. }
  44537. }
  44538. }
  44539. else {
  44540. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  44541. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  44542. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  44543. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  44544. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  44545. var index = _this._keys.indexOf(evt.keyCode);
  44546. if (index >= 0) {
  44547. _this._keys.splice(index, 1);
  44548. }
  44549. if (evt.preventDefault) {
  44550. if (!noPreventDefault) {
  44551. evt.preventDefault();
  44552. }
  44553. }
  44554. }
  44555. }
  44556. });
  44557. };
  44558. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  44559. if (this._scene) {
  44560. if (this._onKeyboardObserver) {
  44561. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  44562. }
  44563. if (this._onCanvasBlurObserver) {
  44564. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  44565. }
  44566. this._onKeyboardObserver = null;
  44567. this._onCanvasBlurObserver = null;
  44568. }
  44569. this._keys = [];
  44570. };
  44571. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  44572. if (this._onKeyboardObserver) {
  44573. var camera = this.camera;
  44574. for (var index = 0; index < this._keys.length; index++) {
  44575. var keyCode = this._keys[index];
  44576. if (this.keysLeft.indexOf(keyCode) !== -1) {
  44577. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44578. camera.inertialPanningX -= 1 / this.panningSensibility;
  44579. }
  44580. else {
  44581. camera.inertialAlphaOffset -= 0.01;
  44582. }
  44583. }
  44584. else if (this.keysUp.indexOf(keyCode) !== -1) {
  44585. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44586. camera.inertialPanningY += 1 / this.panningSensibility;
  44587. }
  44588. else if (this._altPressed && this.useAltToZoom) {
  44589. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  44590. }
  44591. else {
  44592. camera.inertialBetaOffset -= 0.01;
  44593. }
  44594. }
  44595. else if (this.keysRight.indexOf(keyCode) !== -1) {
  44596. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44597. camera.inertialPanningX += 1 / this.panningSensibility;
  44598. }
  44599. else {
  44600. camera.inertialAlphaOffset += 0.01;
  44601. }
  44602. }
  44603. else if (this.keysDown.indexOf(keyCode) !== -1) {
  44604. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44605. camera.inertialPanningY -= 1 / this.panningSensibility;
  44606. }
  44607. else if (this._altPressed && this.useAltToZoom) {
  44608. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  44609. }
  44610. else {
  44611. camera.inertialBetaOffset += 0.01;
  44612. }
  44613. }
  44614. else if (this.keysReset.indexOf(keyCode) !== -1) {
  44615. camera.restoreState();
  44616. }
  44617. }
  44618. }
  44619. };
  44620. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  44621. return "ArcRotateCameraKeyboardMoveInput";
  44622. };
  44623. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  44624. return "keyboard";
  44625. };
  44626. __decorate([
  44627. BABYLON.serialize()
  44628. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  44629. __decorate([
  44630. BABYLON.serialize()
  44631. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  44632. __decorate([
  44633. BABYLON.serialize()
  44634. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  44635. __decorate([
  44636. BABYLON.serialize()
  44637. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  44638. __decorate([
  44639. BABYLON.serialize()
  44640. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  44641. __decorate([
  44642. BABYLON.serialize()
  44643. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  44644. __decorate([
  44645. BABYLON.serialize()
  44646. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  44647. __decorate([
  44648. BABYLON.serialize()
  44649. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  44650. return ArcRotateCameraKeyboardMoveInput;
  44651. }());
  44652. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  44653. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  44654. })(BABYLON || (BABYLON = {}));
  44655. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  44656. "use strict";
  44657. var BABYLON;
  44658. (function (BABYLON) {
  44659. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  44660. function ArcRotateCameraMouseWheelInput() {
  44661. this.wheelPrecision = 3.0;
  44662. /**
  44663. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  44664. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  44665. */
  44666. this.wheelDeltaPercentage = 0;
  44667. }
  44668. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  44669. var _this = this;
  44670. this._wheel = function (p, s) {
  44671. //sanity check - this should be a PointerWheel event.
  44672. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  44673. return;
  44674. var event = p.event;
  44675. var delta = 0;
  44676. if (event.wheelDelta) {
  44677. delta = _this.wheelDeltaPercentage ? (event.wheelDelta * 0.01) * _this.camera.radius * _this.wheelDeltaPercentage : event.wheelDelta / (_this.wheelPrecision * 40);
  44678. }
  44679. else if (event.detail) {
  44680. delta = -event.detail / _this.wheelPrecision;
  44681. }
  44682. if (delta)
  44683. _this.camera.inertialRadiusOffset += delta;
  44684. if (event.preventDefault) {
  44685. if (!noPreventDefault) {
  44686. event.preventDefault();
  44687. }
  44688. }
  44689. };
  44690. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  44691. };
  44692. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  44693. if (this._observer && element) {
  44694. this.camera.getScene().onPointerObservable.remove(this._observer);
  44695. this._observer = null;
  44696. this._wheel = null;
  44697. }
  44698. };
  44699. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  44700. return "ArcRotateCameraMouseWheelInput";
  44701. };
  44702. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  44703. return "mousewheel";
  44704. };
  44705. __decorate([
  44706. BABYLON.serialize()
  44707. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  44708. __decorate([
  44709. BABYLON.serialize()
  44710. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  44711. return ArcRotateCameraMouseWheelInput;
  44712. }());
  44713. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  44714. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  44715. })(BABYLON || (BABYLON = {}));
  44716. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  44717. "use strict";
  44718. var BABYLON;
  44719. (function (BABYLON) {
  44720. var ArcRotateCameraPointersInput = /** @class */ (function () {
  44721. function ArcRotateCameraPointersInput() {
  44722. this.buttons = [0, 1, 2];
  44723. this.angularSensibilityX = 1000.0;
  44724. this.angularSensibilityY = 1000.0;
  44725. this.pinchPrecision = 12.0;
  44726. /**
  44727. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  44728. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  44729. */
  44730. this.pinchDeltaPercentage = 0;
  44731. this.panningSensibility = 1000.0;
  44732. this.multiTouchPanning = true;
  44733. this.multiTouchPanAndZoom = true;
  44734. this._isPanClick = false;
  44735. this.pinchInwards = true;
  44736. }
  44737. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  44738. var _this = this;
  44739. var engine = this.camera.getEngine();
  44740. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  44741. var pointA = null;
  44742. var pointB = null;
  44743. var previousPinchSquaredDistance = 0;
  44744. var initialDistance = 0;
  44745. var twoFingerActivityCount = 0;
  44746. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  44747. this._pointerInput = function (p, s) {
  44748. var evt = p.event;
  44749. var isTouch = p.event.pointerType === "touch";
  44750. if (engine.isInVRExclusivePointerMode) {
  44751. return;
  44752. }
  44753. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  44754. return;
  44755. }
  44756. var srcElement = (evt.srcElement || evt.target);
  44757. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  44758. try {
  44759. srcElement.setPointerCapture(evt.pointerId);
  44760. }
  44761. catch (e) {
  44762. //Nothing to do with the error. Execution will continue.
  44763. }
  44764. // Manage panning with pan button click
  44765. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  44766. // manage pointers
  44767. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  44768. if (pointA === null) {
  44769. pointA = cacheSoloPointer;
  44770. }
  44771. else if (pointB === null) {
  44772. pointB = cacheSoloPointer;
  44773. }
  44774. if (!noPreventDefault) {
  44775. evt.preventDefault();
  44776. element.focus();
  44777. }
  44778. }
  44779. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  44780. _this.camera.restoreState();
  44781. }
  44782. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  44783. try {
  44784. srcElement.releasePointerCapture(evt.pointerId);
  44785. }
  44786. catch (e) {
  44787. //Nothing to do with the error.
  44788. }
  44789. cacheSoloPointer = null;
  44790. previousPinchSquaredDistance = 0;
  44791. previousMultiTouchPanPosition.isPaning = false;
  44792. previousMultiTouchPanPosition.isPinching = false;
  44793. twoFingerActivityCount = 0;
  44794. initialDistance = 0;
  44795. if (!isTouch) {
  44796. pointB = null; // Mouse and pen are mono pointer
  44797. }
  44798. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  44799. //but emptying completly pointers collection is required to fix a bug on iPhone :
  44800. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  44801. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  44802. if (engine.badOS) {
  44803. pointA = pointB = null;
  44804. }
  44805. else {
  44806. //only remove the impacted pointer in case of multitouch allowing on most
  44807. //platforms switching from rotate to zoom and pan seamlessly.
  44808. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  44809. pointA = pointB;
  44810. pointB = null;
  44811. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  44812. }
  44813. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  44814. pointB = null;
  44815. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  44816. }
  44817. else {
  44818. pointA = pointB = null;
  44819. }
  44820. }
  44821. if (!noPreventDefault) {
  44822. evt.preventDefault();
  44823. }
  44824. }
  44825. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  44826. if (!noPreventDefault) {
  44827. evt.preventDefault();
  44828. }
  44829. // One button down
  44830. if (pointA && pointB === null && cacheSoloPointer) {
  44831. if (_this.panningSensibility !== 0 &&
  44832. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  44833. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  44834. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  44835. }
  44836. else {
  44837. var offsetX = evt.clientX - cacheSoloPointer.x;
  44838. var offsetY = evt.clientY - cacheSoloPointer.y;
  44839. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  44840. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  44841. }
  44842. cacheSoloPointer.x = evt.clientX;
  44843. cacheSoloPointer.y = evt.clientY;
  44844. }
  44845. else if (pointA && pointB) {
  44846. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  44847. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  44848. ed.x = evt.clientX;
  44849. ed.y = evt.clientY;
  44850. var direction = _this.pinchInwards ? 1 : -1;
  44851. var distX = pointA.x - pointB.x;
  44852. var distY = pointA.y - pointB.y;
  44853. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  44854. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  44855. if (previousPinchSquaredDistance === 0) {
  44856. initialDistance = pinchDistance;
  44857. previousPinchSquaredDistance = pinchSquaredDistance;
  44858. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  44859. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  44860. return;
  44861. }
  44862. if (_this.multiTouchPanAndZoom) {
  44863. if (_this.pinchDeltaPercentage) {
  44864. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  44865. }
  44866. else {
  44867. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  44868. (_this.pinchPrecision *
  44869. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  44870. direction);
  44871. }
  44872. if (_this.panningSensibility !== 0) {
  44873. var pointersCenterX = (pointA.x + pointB.x) / 2;
  44874. var pointersCenterY = (pointA.y + pointB.y) / 2;
  44875. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  44876. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  44877. previousMultiTouchPanPosition.x = pointersCenterX;
  44878. previousMultiTouchPanPosition.y = pointersCenterY;
  44879. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  44880. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  44881. }
  44882. }
  44883. else {
  44884. twoFingerActivityCount++;
  44885. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  44886. if (_this.pinchDeltaPercentage) {
  44887. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  44888. }
  44889. else {
  44890. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  44891. (_this.pinchPrecision *
  44892. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  44893. direction);
  44894. }
  44895. previousMultiTouchPanPosition.isPaning = false;
  44896. previousMultiTouchPanPosition.isPinching = true;
  44897. }
  44898. else {
  44899. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  44900. if (!previousMultiTouchPanPosition.isPaning) {
  44901. previousMultiTouchPanPosition.isPaning = true;
  44902. previousMultiTouchPanPosition.isPinching = false;
  44903. previousMultiTouchPanPosition.x = ed.x;
  44904. previousMultiTouchPanPosition.y = ed.y;
  44905. return;
  44906. }
  44907. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  44908. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  44909. }
  44910. }
  44911. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  44912. previousMultiTouchPanPosition.x = ed.x;
  44913. previousMultiTouchPanPosition.y = ed.y;
  44914. }
  44915. }
  44916. previousPinchSquaredDistance = pinchSquaredDistance;
  44917. }
  44918. }
  44919. };
  44920. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  44921. this._onContextMenu = function (evt) {
  44922. evt.preventDefault();
  44923. };
  44924. if (!this.camera._useCtrlForPanning) {
  44925. element.addEventListener("contextmenu", this._onContextMenu, false);
  44926. }
  44927. this._onLostFocus = function () {
  44928. //this._keys = [];
  44929. pointA = pointB = null;
  44930. previousPinchSquaredDistance = 0;
  44931. previousMultiTouchPanPosition.isPaning = false;
  44932. previousMultiTouchPanPosition.isPinching = false;
  44933. twoFingerActivityCount = 0;
  44934. cacheSoloPointer = null;
  44935. initialDistance = 0;
  44936. };
  44937. this._onMouseMove = function (evt) {
  44938. if (!engine.isPointerLock) {
  44939. return;
  44940. }
  44941. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  44942. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  44943. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  44944. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  44945. if (!noPreventDefault) {
  44946. evt.preventDefault();
  44947. }
  44948. };
  44949. this._onGestureStart = function (e) {
  44950. if (window.MSGesture === undefined) {
  44951. return;
  44952. }
  44953. if (!_this._MSGestureHandler) {
  44954. _this._MSGestureHandler = new MSGesture();
  44955. _this._MSGestureHandler.target = element;
  44956. }
  44957. _this._MSGestureHandler.addPointer(e.pointerId);
  44958. };
  44959. this._onGesture = function (e) {
  44960. _this.camera.radius *= e.scale;
  44961. if (e.preventDefault) {
  44962. if (!noPreventDefault) {
  44963. e.stopPropagation();
  44964. e.preventDefault();
  44965. }
  44966. }
  44967. };
  44968. element.addEventListener("mousemove", this._onMouseMove, false);
  44969. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  44970. element.addEventListener("MSGestureChange", this._onGesture, false);
  44971. BABYLON.Tools.RegisterTopRootEvents([
  44972. { name: "blur", handler: this._onLostFocus }
  44973. ]);
  44974. };
  44975. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  44976. if (this._onLostFocus) {
  44977. BABYLON.Tools.UnregisterTopRootEvents([
  44978. { name: "blur", handler: this._onLostFocus }
  44979. ]);
  44980. }
  44981. if (element && this._observer) {
  44982. this.camera.getScene().onPointerObservable.remove(this._observer);
  44983. this._observer = null;
  44984. if (this._onContextMenu) {
  44985. element.removeEventListener("contextmenu", this._onContextMenu);
  44986. }
  44987. if (this._onMouseMove) {
  44988. element.removeEventListener("mousemove", this._onMouseMove);
  44989. }
  44990. if (this._onGestureStart) {
  44991. element.removeEventListener("MSPointerDown", this._onGestureStart);
  44992. }
  44993. if (this._onGesture) {
  44994. element.removeEventListener("MSGestureChange", this._onGesture);
  44995. }
  44996. this._isPanClick = false;
  44997. this.pinchInwards = true;
  44998. this._onMouseMove = null;
  44999. this._onGestureStart = null;
  45000. this._onGesture = null;
  45001. this._MSGestureHandler = null;
  45002. this._onLostFocus = null;
  45003. this._onContextMenu = null;
  45004. }
  45005. };
  45006. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  45007. return "ArcRotateCameraPointersInput";
  45008. };
  45009. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  45010. return "pointers";
  45011. };
  45012. __decorate([
  45013. BABYLON.serialize()
  45014. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  45015. __decorate([
  45016. BABYLON.serialize()
  45017. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  45018. __decorate([
  45019. BABYLON.serialize()
  45020. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  45021. __decorate([
  45022. BABYLON.serialize()
  45023. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  45024. __decorate([
  45025. BABYLON.serialize()
  45026. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  45027. __decorate([
  45028. BABYLON.serialize()
  45029. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  45030. __decorate([
  45031. BABYLON.serialize()
  45032. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  45033. __decorate([
  45034. BABYLON.serialize()
  45035. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  45036. return ArcRotateCameraPointersInput;
  45037. }());
  45038. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  45039. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  45040. })(BABYLON || (BABYLON = {}));
  45041. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  45042. "use strict";
  45043. var BABYLON;
  45044. (function (BABYLON) {
  45045. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  45046. __extends(ArcRotateCameraInputsManager, _super);
  45047. function ArcRotateCameraInputsManager(camera) {
  45048. return _super.call(this, camera) || this;
  45049. }
  45050. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  45051. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  45052. return this;
  45053. };
  45054. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  45055. this.add(new BABYLON.ArcRotateCameraPointersInput());
  45056. return this;
  45057. };
  45058. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  45059. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  45060. return this;
  45061. };
  45062. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  45063. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  45064. return this;
  45065. };
  45066. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  45067. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  45068. return this;
  45069. };
  45070. return ArcRotateCameraInputsManager;
  45071. }(BABYLON.CameraInputsManager));
  45072. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  45073. })(BABYLON || (BABYLON = {}));
  45074. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  45075. "use strict";
  45076. var BABYLON;
  45077. (function (BABYLON) {
  45078. var ArcRotateCamera = /** @class */ (function (_super) {
  45079. __extends(ArcRotateCamera, _super);
  45080. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  45081. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  45082. _this.inertialAlphaOffset = 0;
  45083. _this.inertialBetaOffset = 0;
  45084. _this.inertialRadiusOffset = 0;
  45085. _this.lowerAlphaLimit = null;
  45086. _this.upperAlphaLimit = null;
  45087. _this.lowerBetaLimit = 0.01;
  45088. _this.upperBetaLimit = Math.PI;
  45089. _this.lowerRadiusLimit = null;
  45090. _this.upperRadiusLimit = null;
  45091. _this.inertialPanningX = 0;
  45092. _this.inertialPanningY = 0;
  45093. _this.pinchToPanMaxDistance = 20;
  45094. _this.panningDistanceLimit = null;
  45095. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  45096. _this.panningInertia = 0.9;
  45097. //-- end properties for backward compatibility for inputs
  45098. _this.zoomOnFactor = 1;
  45099. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  45100. _this.allowUpsideDown = true;
  45101. _this._viewMatrix = new BABYLON.Matrix();
  45102. // Panning
  45103. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  45104. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  45105. _this.checkCollisions = false;
  45106. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  45107. _this._previousPosition = BABYLON.Vector3.Zero();
  45108. _this._collisionVelocity = BABYLON.Vector3.Zero();
  45109. _this._newPosition = BABYLON.Vector3.Zero();
  45110. _this._computationVector = BABYLON.Vector3.Zero();
  45111. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  45112. if (collidedMesh === void 0) { collidedMesh = null; }
  45113. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  45114. newPosition.multiplyInPlace(_this._collider._radius);
  45115. }
  45116. if (!collidedMesh) {
  45117. _this._previousPosition.copyFrom(_this.position);
  45118. }
  45119. else {
  45120. _this.setPosition(newPosition);
  45121. if (_this.onCollide) {
  45122. _this.onCollide(collidedMesh);
  45123. }
  45124. }
  45125. // Recompute because of constraints
  45126. var cosa = Math.cos(_this.alpha);
  45127. var sina = Math.sin(_this.alpha);
  45128. var cosb = Math.cos(_this.beta);
  45129. var sinb = Math.sin(_this.beta);
  45130. if (sinb === 0) {
  45131. sinb = 0.0001;
  45132. }
  45133. var target = _this._getTargetPosition();
  45134. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  45135. target.addToRef(_this._computationVector, _this._newPosition);
  45136. _this.position.copyFrom(_this._newPosition);
  45137. var up = _this.upVector;
  45138. if (_this.allowUpsideDown && _this.beta < 0) {
  45139. up = up.clone();
  45140. up = up.negate();
  45141. }
  45142. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  45143. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  45144. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  45145. _this._collisionTriggered = false;
  45146. };
  45147. _this._target = BABYLON.Vector3.Zero();
  45148. if (target) {
  45149. _this.setTarget(target);
  45150. }
  45151. _this.alpha = alpha;
  45152. _this.beta = beta;
  45153. _this.radius = radius;
  45154. _this.getViewMatrix();
  45155. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  45156. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  45157. return _this;
  45158. }
  45159. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  45160. get: function () {
  45161. return this._target;
  45162. },
  45163. set: function (value) {
  45164. this.setTarget(value);
  45165. },
  45166. enumerable: true,
  45167. configurable: true
  45168. });
  45169. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  45170. //-- begin properties for backward compatibility for inputs
  45171. get: function () {
  45172. var pointers = this.inputs.attached["pointers"];
  45173. if (pointers)
  45174. return pointers.angularSensibilityX;
  45175. return 0;
  45176. },
  45177. set: function (value) {
  45178. var pointers = this.inputs.attached["pointers"];
  45179. if (pointers) {
  45180. pointers.angularSensibilityX = value;
  45181. }
  45182. },
  45183. enumerable: true,
  45184. configurable: true
  45185. });
  45186. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  45187. get: function () {
  45188. var pointers = this.inputs.attached["pointers"];
  45189. if (pointers)
  45190. return pointers.angularSensibilityY;
  45191. return 0;
  45192. },
  45193. set: function (value) {
  45194. var pointers = this.inputs.attached["pointers"];
  45195. if (pointers) {
  45196. pointers.angularSensibilityY = value;
  45197. }
  45198. },
  45199. enumerable: true,
  45200. configurable: true
  45201. });
  45202. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  45203. get: function () {
  45204. var pointers = this.inputs.attached["pointers"];
  45205. if (pointers)
  45206. return pointers.pinchPrecision;
  45207. return 0;
  45208. },
  45209. set: function (value) {
  45210. var pointers = this.inputs.attached["pointers"];
  45211. if (pointers) {
  45212. pointers.pinchPrecision = value;
  45213. }
  45214. },
  45215. enumerable: true,
  45216. configurable: true
  45217. });
  45218. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  45219. get: function () {
  45220. var pointers = this.inputs.attached["pointers"];
  45221. if (pointers)
  45222. return pointers.pinchDeltaPercentage;
  45223. return 0;
  45224. },
  45225. set: function (value) {
  45226. var pointers = this.inputs.attached["pointers"];
  45227. if (pointers) {
  45228. pointers.pinchDeltaPercentage = value;
  45229. }
  45230. },
  45231. enumerable: true,
  45232. configurable: true
  45233. });
  45234. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  45235. get: function () {
  45236. var pointers = this.inputs.attached["pointers"];
  45237. if (pointers)
  45238. return pointers.panningSensibility;
  45239. return 0;
  45240. },
  45241. set: function (value) {
  45242. var pointers = this.inputs.attached["pointers"];
  45243. if (pointers) {
  45244. pointers.panningSensibility = value;
  45245. }
  45246. },
  45247. enumerable: true,
  45248. configurable: true
  45249. });
  45250. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  45251. get: function () {
  45252. var keyboard = this.inputs.attached["keyboard"];
  45253. if (keyboard)
  45254. return keyboard.keysUp;
  45255. return [];
  45256. },
  45257. set: function (value) {
  45258. var keyboard = this.inputs.attached["keyboard"];
  45259. if (keyboard)
  45260. keyboard.keysUp = value;
  45261. },
  45262. enumerable: true,
  45263. configurable: true
  45264. });
  45265. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  45266. get: function () {
  45267. var keyboard = this.inputs.attached["keyboard"];
  45268. if (keyboard)
  45269. return keyboard.keysDown;
  45270. return [];
  45271. },
  45272. set: function (value) {
  45273. var keyboard = this.inputs.attached["keyboard"];
  45274. if (keyboard)
  45275. keyboard.keysDown = value;
  45276. },
  45277. enumerable: true,
  45278. configurable: true
  45279. });
  45280. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  45281. get: function () {
  45282. var keyboard = this.inputs.attached["keyboard"];
  45283. if (keyboard)
  45284. return keyboard.keysLeft;
  45285. return [];
  45286. },
  45287. set: function (value) {
  45288. var keyboard = this.inputs.attached["keyboard"];
  45289. if (keyboard)
  45290. keyboard.keysLeft = value;
  45291. },
  45292. enumerable: true,
  45293. configurable: true
  45294. });
  45295. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  45296. get: function () {
  45297. var keyboard = this.inputs.attached["keyboard"];
  45298. if (keyboard)
  45299. return keyboard.keysRight;
  45300. return [];
  45301. },
  45302. set: function (value) {
  45303. var keyboard = this.inputs.attached["keyboard"];
  45304. if (keyboard)
  45305. keyboard.keysRight = value;
  45306. },
  45307. enumerable: true,
  45308. configurable: true
  45309. });
  45310. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  45311. get: function () {
  45312. var mousewheel = this.inputs.attached["mousewheel"];
  45313. if (mousewheel)
  45314. return mousewheel.wheelPrecision;
  45315. return 0;
  45316. },
  45317. set: function (value) {
  45318. var mousewheel = this.inputs.attached["mousewheel"];
  45319. if (mousewheel)
  45320. mousewheel.wheelPrecision = value;
  45321. },
  45322. enumerable: true,
  45323. configurable: true
  45324. });
  45325. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  45326. get: function () {
  45327. var mousewheel = this.inputs.attached["mousewheel"];
  45328. if (mousewheel)
  45329. return mousewheel.wheelDeltaPercentage;
  45330. return 0;
  45331. },
  45332. set: function (value) {
  45333. var mousewheel = this.inputs.attached["mousewheel"];
  45334. if (mousewheel)
  45335. mousewheel.wheelDeltaPercentage = value;
  45336. },
  45337. enumerable: true,
  45338. configurable: true
  45339. });
  45340. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  45341. get: function () {
  45342. return this._bouncingBehavior;
  45343. },
  45344. enumerable: true,
  45345. configurable: true
  45346. });
  45347. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  45348. get: function () {
  45349. return this._bouncingBehavior != null;
  45350. },
  45351. set: function (value) {
  45352. if (value === this.useBouncingBehavior) {
  45353. return;
  45354. }
  45355. if (value) {
  45356. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  45357. this.addBehavior(this._bouncingBehavior);
  45358. }
  45359. else if (this._bouncingBehavior) {
  45360. this.removeBehavior(this._bouncingBehavior);
  45361. this._bouncingBehavior = null;
  45362. }
  45363. },
  45364. enumerable: true,
  45365. configurable: true
  45366. });
  45367. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  45368. get: function () {
  45369. return this._framingBehavior;
  45370. },
  45371. enumerable: true,
  45372. configurable: true
  45373. });
  45374. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  45375. get: function () {
  45376. return this._framingBehavior != null;
  45377. },
  45378. set: function (value) {
  45379. if (value === this.useFramingBehavior) {
  45380. return;
  45381. }
  45382. if (value) {
  45383. this._framingBehavior = new BABYLON.FramingBehavior();
  45384. this.addBehavior(this._framingBehavior);
  45385. }
  45386. else if (this._framingBehavior) {
  45387. this.removeBehavior(this._framingBehavior);
  45388. this._framingBehavior = null;
  45389. }
  45390. },
  45391. enumerable: true,
  45392. configurable: true
  45393. });
  45394. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  45395. get: function () {
  45396. return this._autoRotationBehavior;
  45397. },
  45398. enumerable: true,
  45399. configurable: true
  45400. });
  45401. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  45402. get: function () {
  45403. return this._autoRotationBehavior != null;
  45404. },
  45405. set: function (value) {
  45406. if (value === this.useAutoRotationBehavior) {
  45407. return;
  45408. }
  45409. if (value) {
  45410. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  45411. this.addBehavior(this._autoRotationBehavior);
  45412. }
  45413. else if (this._autoRotationBehavior) {
  45414. this.removeBehavior(this._autoRotationBehavior);
  45415. this._autoRotationBehavior = null;
  45416. }
  45417. },
  45418. enumerable: true,
  45419. configurable: true
  45420. });
  45421. // Cache
  45422. ArcRotateCamera.prototype._initCache = function () {
  45423. _super.prototype._initCache.call(this);
  45424. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  45425. this._cache.alpha = undefined;
  45426. this._cache.beta = undefined;
  45427. this._cache.radius = undefined;
  45428. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  45429. };
  45430. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  45431. if (!ignoreParentClass) {
  45432. _super.prototype._updateCache.call(this);
  45433. }
  45434. this._cache._target.copyFrom(this._getTargetPosition());
  45435. this._cache.alpha = this.alpha;
  45436. this._cache.beta = this.beta;
  45437. this._cache.radius = this.radius;
  45438. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  45439. };
  45440. ArcRotateCamera.prototype._getTargetPosition = function () {
  45441. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  45442. var pos = this._targetHost.getAbsolutePosition();
  45443. if (this._targetBoundingCenter) {
  45444. pos.addToRef(this._targetBoundingCenter, this._target);
  45445. }
  45446. else {
  45447. this._target.copyFrom(pos);
  45448. }
  45449. }
  45450. var lockedTargetPosition = this._getLockedTargetPosition();
  45451. if (lockedTargetPosition) {
  45452. return lockedTargetPosition;
  45453. }
  45454. return this._target;
  45455. };
  45456. ArcRotateCamera.prototype.storeState = function () {
  45457. this._storedAlpha = this.alpha;
  45458. this._storedBeta = this.beta;
  45459. this._storedRadius = this.radius;
  45460. this._storedTarget = this._getTargetPosition().clone();
  45461. return _super.prototype.storeState.call(this);
  45462. };
  45463. /**
  45464. * Restored camera state. You must call storeState() first
  45465. */
  45466. ArcRotateCamera.prototype._restoreStateValues = function () {
  45467. if (!_super.prototype._restoreStateValues.call(this)) {
  45468. return false;
  45469. }
  45470. this.alpha = this._storedAlpha;
  45471. this.beta = this._storedBeta;
  45472. this.radius = this._storedRadius;
  45473. this.setTarget(this._storedTarget.clone());
  45474. this.inertialAlphaOffset = 0;
  45475. this.inertialBetaOffset = 0;
  45476. this.inertialRadiusOffset = 0;
  45477. this.inertialPanningX = 0;
  45478. this.inertialPanningY = 0;
  45479. return true;
  45480. };
  45481. // Synchronized
  45482. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  45483. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  45484. return false;
  45485. return this._cache._target.equals(this._getTargetPosition())
  45486. && this._cache.alpha === this.alpha
  45487. && this._cache.beta === this.beta
  45488. && this._cache.radius === this.radius
  45489. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  45490. };
  45491. // Methods
  45492. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  45493. var _this = this;
  45494. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  45495. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  45496. this._useCtrlForPanning = useCtrlForPanning;
  45497. this._panningMouseButton = panningMouseButton;
  45498. this.inputs.attachElement(element, noPreventDefault);
  45499. this._reset = function () {
  45500. _this.inertialAlphaOffset = 0;
  45501. _this.inertialBetaOffset = 0;
  45502. _this.inertialRadiusOffset = 0;
  45503. _this.inertialPanningX = 0;
  45504. _this.inertialPanningY = 0;
  45505. };
  45506. };
  45507. ArcRotateCamera.prototype.detachControl = function (element) {
  45508. this.inputs.detachElement(element);
  45509. if (this._reset) {
  45510. this._reset();
  45511. }
  45512. };
  45513. ArcRotateCamera.prototype._checkInputs = function () {
  45514. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  45515. if (this._collisionTriggered) {
  45516. return;
  45517. }
  45518. this.inputs.checkInputs();
  45519. // Inertia
  45520. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  45521. if (this.getScene().useRightHandedSystem) {
  45522. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  45523. }
  45524. else {
  45525. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  45526. }
  45527. this.beta += this.inertialBetaOffset;
  45528. this.radius -= this.inertialRadiusOffset;
  45529. this.inertialAlphaOffset *= this.inertia;
  45530. this.inertialBetaOffset *= this.inertia;
  45531. this.inertialRadiusOffset *= this.inertia;
  45532. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  45533. this.inertialAlphaOffset = 0;
  45534. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  45535. this.inertialBetaOffset = 0;
  45536. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  45537. this.inertialRadiusOffset = 0;
  45538. }
  45539. // Panning inertia
  45540. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  45541. if (!this._localDirection) {
  45542. this._localDirection = BABYLON.Vector3.Zero();
  45543. this._transformedDirection = BABYLON.Vector3.Zero();
  45544. }
  45545. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  45546. this._localDirection.multiplyInPlace(this.panningAxis);
  45547. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  45548. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  45549. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  45550. if (!this.panningAxis.y) {
  45551. this._transformedDirection.y = 0;
  45552. }
  45553. if (!this._targetHost) {
  45554. if (this.panningDistanceLimit) {
  45555. this._transformedDirection.addInPlace(this._target);
  45556. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  45557. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  45558. this._target.copyFrom(this._transformedDirection);
  45559. }
  45560. }
  45561. else {
  45562. this._target.addInPlace(this._transformedDirection);
  45563. }
  45564. }
  45565. this.inertialPanningX *= this.panningInertia;
  45566. this.inertialPanningY *= this.panningInertia;
  45567. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  45568. this.inertialPanningX = 0;
  45569. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  45570. this.inertialPanningY = 0;
  45571. }
  45572. // Limits
  45573. this._checkLimits();
  45574. _super.prototype._checkInputs.call(this);
  45575. };
  45576. ArcRotateCamera.prototype._checkLimits = function () {
  45577. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  45578. if (this.allowUpsideDown && this.beta > Math.PI) {
  45579. this.beta = this.beta - (2 * Math.PI);
  45580. }
  45581. }
  45582. else {
  45583. if (this.beta < this.lowerBetaLimit) {
  45584. this.beta = this.lowerBetaLimit;
  45585. }
  45586. }
  45587. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  45588. if (this.allowUpsideDown && this.beta < -Math.PI) {
  45589. this.beta = this.beta + (2 * Math.PI);
  45590. }
  45591. }
  45592. else {
  45593. if (this.beta > this.upperBetaLimit) {
  45594. this.beta = this.upperBetaLimit;
  45595. }
  45596. }
  45597. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  45598. this.alpha = this.lowerAlphaLimit;
  45599. }
  45600. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  45601. this.alpha = this.upperAlphaLimit;
  45602. }
  45603. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  45604. this.radius = this.lowerRadiusLimit;
  45605. }
  45606. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  45607. this.radius = this.upperRadiusLimit;
  45608. }
  45609. };
  45610. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  45611. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  45612. this.radius = this._computationVector.length();
  45613. if (this.radius === 0) {
  45614. this.radius = 0.0001; // Just to avoid division by zero
  45615. }
  45616. // Alpha
  45617. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  45618. if (this._computationVector.z < 0) {
  45619. this.alpha = 2 * Math.PI - this.alpha;
  45620. }
  45621. // Beta
  45622. this.beta = Math.acos(this._computationVector.y / this.radius);
  45623. this._checkLimits();
  45624. };
  45625. ArcRotateCamera.prototype.setPosition = function (position) {
  45626. if (this.position.equals(position)) {
  45627. return;
  45628. }
  45629. this.position.copyFrom(position);
  45630. this.rebuildAnglesAndRadius();
  45631. };
  45632. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  45633. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  45634. if (allowSamePosition === void 0) { allowSamePosition = false; }
  45635. if (target.getBoundingInfo) {
  45636. if (toBoundingCenter) {
  45637. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  45638. }
  45639. else {
  45640. this._targetBoundingCenter = null;
  45641. }
  45642. this._targetHost = target;
  45643. this._target = this._getTargetPosition();
  45644. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  45645. }
  45646. else {
  45647. var newTarget = target;
  45648. var currentTarget = this._getTargetPosition();
  45649. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  45650. return;
  45651. }
  45652. this._targetHost = null;
  45653. this._target = newTarget;
  45654. this._targetBoundingCenter = null;
  45655. this.onMeshTargetChangedObservable.notifyObservers(null);
  45656. }
  45657. this.rebuildAnglesAndRadius();
  45658. };
  45659. ArcRotateCamera.prototype._getViewMatrix = function () {
  45660. // Compute
  45661. var cosa = Math.cos(this.alpha);
  45662. var sina = Math.sin(this.alpha);
  45663. var cosb = Math.cos(this.beta);
  45664. var sinb = Math.sin(this.beta);
  45665. if (sinb === 0) {
  45666. sinb = 0.0001;
  45667. }
  45668. var target = this._getTargetPosition();
  45669. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  45670. target.addToRef(this._computationVector, this._newPosition);
  45671. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  45672. if (!this._collider) {
  45673. this._collider = new BABYLON.Collider();
  45674. }
  45675. this._collider._radius = this.collisionRadius;
  45676. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  45677. this._collisionTriggered = true;
  45678. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  45679. }
  45680. else {
  45681. this.position.copyFrom(this._newPosition);
  45682. var up = this.upVector;
  45683. if (this.allowUpsideDown && sinb < 0) {
  45684. up = up.clone();
  45685. up = up.negate();
  45686. }
  45687. if (this.getScene().useRightHandedSystem) {
  45688. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  45689. }
  45690. else {
  45691. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  45692. }
  45693. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  45694. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  45695. }
  45696. this._currentTarget = target;
  45697. return this._viewMatrix;
  45698. };
  45699. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  45700. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  45701. meshes = meshes || this.getScene().meshes;
  45702. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  45703. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  45704. this.radius = distance * this.zoomOnFactor;
  45705. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  45706. };
  45707. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  45708. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  45709. var meshesOrMinMaxVector;
  45710. var distance;
  45711. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  45712. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  45713. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  45714. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  45715. }
  45716. else {
  45717. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  45718. meshesOrMinMaxVector = minMaxVectorAndDistance;
  45719. distance = minMaxVectorAndDistance.distance;
  45720. }
  45721. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  45722. if (!doNotUpdateMaxZ) {
  45723. this.maxZ = distance * 2;
  45724. }
  45725. };
  45726. /**
  45727. * @override
  45728. * Override Camera.createRigCamera
  45729. */
  45730. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  45731. var alphaShift = 0;
  45732. switch (this.cameraRigMode) {
  45733. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  45734. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  45735. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  45736. case BABYLON.Camera.RIG_MODE_VR:
  45737. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  45738. break;
  45739. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  45740. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  45741. break;
  45742. }
  45743. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  45744. rigCam._cameraRigParams = {};
  45745. return rigCam;
  45746. };
  45747. /**
  45748. * @override
  45749. * Override Camera._updateRigCameras
  45750. */
  45751. ArcRotateCamera.prototype._updateRigCameras = function () {
  45752. var camLeft = this._rigCameras[0];
  45753. var camRight = this._rigCameras[1];
  45754. camLeft.beta = camRight.beta = this.beta;
  45755. camLeft.radius = camRight.radius = this.radius;
  45756. switch (this.cameraRigMode) {
  45757. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  45758. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  45759. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  45760. case BABYLON.Camera.RIG_MODE_VR:
  45761. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  45762. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  45763. break;
  45764. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  45765. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  45766. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  45767. break;
  45768. }
  45769. _super.prototype._updateRigCameras.call(this);
  45770. };
  45771. ArcRotateCamera.prototype.dispose = function () {
  45772. this.inputs.clear();
  45773. _super.prototype.dispose.call(this);
  45774. };
  45775. ArcRotateCamera.prototype.getClassName = function () {
  45776. return "ArcRotateCamera";
  45777. };
  45778. __decorate([
  45779. BABYLON.serialize()
  45780. ], ArcRotateCamera.prototype, "alpha", void 0);
  45781. __decorate([
  45782. BABYLON.serialize()
  45783. ], ArcRotateCamera.prototype, "beta", void 0);
  45784. __decorate([
  45785. BABYLON.serialize()
  45786. ], ArcRotateCamera.prototype, "radius", void 0);
  45787. __decorate([
  45788. BABYLON.serializeAsVector3("target")
  45789. ], ArcRotateCamera.prototype, "_target", void 0);
  45790. __decorate([
  45791. BABYLON.serialize()
  45792. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  45793. __decorate([
  45794. BABYLON.serialize()
  45795. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  45796. __decorate([
  45797. BABYLON.serialize()
  45798. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  45799. __decorate([
  45800. BABYLON.serialize()
  45801. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  45802. __decorate([
  45803. BABYLON.serialize()
  45804. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  45805. __decorate([
  45806. BABYLON.serialize()
  45807. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  45808. __decorate([
  45809. BABYLON.serialize()
  45810. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  45811. __decorate([
  45812. BABYLON.serialize()
  45813. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  45814. __decorate([
  45815. BABYLON.serialize()
  45816. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  45817. __decorate([
  45818. BABYLON.serialize()
  45819. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  45820. __decorate([
  45821. BABYLON.serialize()
  45822. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  45823. __decorate([
  45824. BABYLON.serialize()
  45825. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  45826. __decorate([
  45827. BABYLON.serialize()
  45828. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  45829. __decorate([
  45830. BABYLON.serializeAsVector3()
  45831. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  45832. __decorate([
  45833. BABYLON.serialize()
  45834. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  45835. __decorate([
  45836. BABYLON.serialize()
  45837. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  45838. __decorate([
  45839. BABYLON.serialize()
  45840. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  45841. return ArcRotateCamera;
  45842. }(BABYLON.TargetCamera));
  45843. BABYLON.ArcRotateCamera = ArcRotateCamera;
  45844. })(BABYLON || (BABYLON = {}));
  45845. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  45846. "use strict";
  45847. var BABYLON;
  45848. (function (BABYLON) {
  45849. /**
  45850. * The HemisphericLight simulates the ambient environment light,
  45851. * so the passed direction is the light reflection direction, not the incoming direction.
  45852. */
  45853. var HemisphericLight = /** @class */ (function (_super) {
  45854. __extends(HemisphericLight, _super);
  45855. /**
  45856. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  45857. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  45858. * The HemisphericLight can't cast shadows.
  45859. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45860. * @param name The friendly name of the light
  45861. * @param direction The direction of the light reflection
  45862. * @param scene The scene the light belongs to
  45863. */
  45864. function HemisphericLight(name, direction, scene) {
  45865. var _this = _super.call(this, name, scene) || this;
  45866. /**
  45867. * The groundColor is the light in the opposite direction to the one specified during creation.
  45868. * 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.
  45869. */
  45870. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  45871. _this.direction = direction || BABYLON.Vector3.Up();
  45872. return _this;
  45873. }
  45874. HemisphericLight.prototype._buildUniformLayout = function () {
  45875. this._uniformBuffer.addUniform("vLightData", 4);
  45876. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45877. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45878. this._uniformBuffer.addUniform("vLightGround", 3);
  45879. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45880. this._uniformBuffer.addUniform("depthValues", 2);
  45881. this._uniformBuffer.create();
  45882. };
  45883. /**
  45884. * Returns the string "HemisphericLight".
  45885. * @return The class name
  45886. */
  45887. HemisphericLight.prototype.getClassName = function () {
  45888. return "HemisphericLight";
  45889. };
  45890. /**
  45891. * Sets the HemisphericLight direction towards the passed target (Vector3).
  45892. * Returns the updated direction.
  45893. * @param target The target the direction should point to
  45894. * @return The computed direction
  45895. */
  45896. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  45897. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  45898. return this.direction;
  45899. };
  45900. /**
  45901. * Returns the shadow generator associated to the light.
  45902. * @returns Always null for hemispheric lights because it does not support shadows.
  45903. */
  45904. HemisphericLight.prototype.getShadowGenerator = function () {
  45905. return null;
  45906. };
  45907. /**
  45908. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  45909. * @param effect The effect to update
  45910. * @param lightIndex The index of the light in the effect to update
  45911. * @returns The hemispheric light
  45912. */
  45913. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  45914. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  45915. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  45916. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  45917. return this;
  45918. };
  45919. /**
  45920. * @ignore internal use only.
  45921. */
  45922. HemisphericLight.prototype._getWorldMatrix = function () {
  45923. if (!this._worldMatrix) {
  45924. this._worldMatrix = BABYLON.Matrix.Identity();
  45925. }
  45926. return this._worldMatrix;
  45927. };
  45928. /**
  45929. * Returns the integer 3.
  45930. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45931. */
  45932. HemisphericLight.prototype.getTypeID = function () {
  45933. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  45934. };
  45935. __decorate([
  45936. BABYLON.serializeAsColor3()
  45937. ], HemisphericLight.prototype, "groundColor", void 0);
  45938. __decorate([
  45939. BABYLON.serializeAsVector3()
  45940. ], HemisphericLight.prototype, "direction", void 0);
  45941. return HemisphericLight;
  45942. }(BABYLON.Light));
  45943. BABYLON.HemisphericLight = HemisphericLight;
  45944. })(BABYLON || (BABYLON = {}));
  45945. //# sourceMappingURL=babylon.hemisphericLight.js.map
  45946. "use strict";
  45947. var BABYLON;
  45948. (function (BABYLON) {
  45949. /**
  45950. * Base implementation of @see IShadowLight
  45951. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  45952. */
  45953. var ShadowLight = /** @class */ (function (_super) {
  45954. __extends(ShadowLight, _super);
  45955. function ShadowLight() {
  45956. var _this = _super !== null && _super.apply(this, arguments) || this;
  45957. _this._needProjectionMatrixCompute = true;
  45958. return _this;
  45959. }
  45960. ShadowLight.prototype._setPosition = function (value) {
  45961. this._position = value;
  45962. };
  45963. Object.defineProperty(ShadowLight.prototype, "position", {
  45964. /**
  45965. * Sets the position the shadow will be casted from. Also use as the light position for both
  45966. * point and spot lights.
  45967. */
  45968. get: function () {
  45969. return this._position;
  45970. },
  45971. /**
  45972. * Sets the position the shadow will be casted from. Also use as the light position for both
  45973. * point and spot lights.
  45974. */
  45975. set: function (value) {
  45976. this._setPosition(value);
  45977. },
  45978. enumerable: true,
  45979. configurable: true
  45980. });
  45981. ShadowLight.prototype._setDirection = function (value) {
  45982. this._direction = value;
  45983. };
  45984. Object.defineProperty(ShadowLight.prototype, "direction", {
  45985. /**
  45986. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  45987. * Also use as the light direction on spot and directional lights.
  45988. */
  45989. get: function () {
  45990. return this._direction;
  45991. },
  45992. /**
  45993. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  45994. * Also use as the light direction on spot and directional lights.
  45995. */
  45996. set: function (value) {
  45997. this._setDirection(value);
  45998. },
  45999. enumerable: true,
  46000. configurable: true
  46001. });
  46002. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  46003. /**
  46004. * Gets the shadow projection clipping minimum z value.
  46005. */
  46006. get: function () {
  46007. return this._shadowMinZ;
  46008. },
  46009. /**
  46010. * Sets the shadow projection clipping minimum z value.
  46011. */
  46012. set: function (value) {
  46013. this._shadowMinZ = value;
  46014. this.forceProjectionMatrixCompute();
  46015. },
  46016. enumerable: true,
  46017. configurable: true
  46018. });
  46019. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  46020. /**
  46021. * Sets the shadow projection clipping maximum z value.
  46022. */
  46023. get: function () {
  46024. return this._shadowMaxZ;
  46025. },
  46026. /**
  46027. * Gets the shadow projection clipping maximum z value.
  46028. */
  46029. set: function (value) {
  46030. this._shadowMaxZ = value;
  46031. this.forceProjectionMatrixCompute();
  46032. },
  46033. enumerable: true,
  46034. configurable: true
  46035. });
  46036. /**
  46037. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  46038. * @returns true if the information has been computed, false if it does not need to (no parenting)
  46039. */
  46040. ShadowLight.prototype.computeTransformedInformation = function () {
  46041. if (this.parent && this.parent.getWorldMatrix) {
  46042. if (!this.transformedPosition) {
  46043. this.transformedPosition = BABYLON.Vector3.Zero();
  46044. }
  46045. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  46046. // In case the direction is present.
  46047. if (this.direction) {
  46048. if (!this.transformedDirection) {
  46049. this.transformedDirection = BABYLON.Vector3.Zero();
  46050. }
  46051. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  46052. }
  46053. return true;
  46054. }
  46055. return false;
  46056. };
  46057. /**
  46058. * Return the depth scale used for the shadow map.
  46059. * @returns the depth scale.
  46060. */
  46061. ShadowLight.prototype.getDepthScale = function () {
  46062. return 50.0;
  46063. };
  46064. /**
  46065. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  46066. * @param faceIndex The index of the face we are computed the direction to generate shadow
  46067. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  46068. */
  46069. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  46070. return this.transformedDirection ? this.transformedDirection : this.direction;
  46071. };
  46072. /**
  46073. * Returns the ShadowLight absolute position in the World.
  46074. * @returns the position vector in world space
  46075. */
  46076. ShadowLight.prototype.getAbsolutePosition = function () {
  46077. return this.transformedPosition ? this.transformedPosition : this.position;
  46078. };
  46079. /**
  46080. * Sets the ShadowLight direction toward the passed target.
  46081. * @param target The point tot target in local space
  46082. * @returns the updated ShadowLight direction
  46083. */
  46084. ShadowLight.prototype.setDirectionToTarget = function (target) {
  46085. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  46086. return this.direction;
  46087. };
  46088. /**
  46089. * Returns the light rotation in euler definition.
  46090. * @returns the x y z rotation in local space.
  46091. */
  46092. ShadowLight.prototype.getRotation = function () {
  46093. this.direction.normalize();
  46094. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  46095. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  46096. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  46097. };
  46098. /**
  46099. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  46100. * @returns true if a cube texture needs to be use
  46101. */
  46102. ShadowLight.prototype.needCube = function () {
  46103. return false;
  46104. };
  46105. /**
  46106. * Detects if the projection matrix requires to be recomputed this frame.
  46107. * @returns true if it requires to be recomputed otherwise, false.
  46108. */
  46109. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  46110. return this._needProjectionMatrixCompute;
  46111. };
  46112. /**
  46113. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  46114. */
  46115. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  46116. this._needProjectionMatrixCompute = true;
  46117. };
  46118. /**
  46119. * Get the world matrix of the sahdow lights.
  46120. * @ignore Internal Use Only
  46121. */
  46122. ShadowLight.prototype._getWorldMatrix = function () {
  46123. if (!this._worldMatrix) {
  46124. this._worldMatrix = BABYLON.Matrix.Identity();
  46125. }
  46126. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  46127. return this._worldMatrix;
  46128. };
  46129. /**
  46130. * Gets the minZ used for shadow according to both the scene and the light.
  46131. * @param activeCamera The camera we are returning the min for
  46132. * @returns the depth min z
  46133. */
  46134. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  46135. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  46136. };
  46137. /**
  46138. * Gets the maxZ used for shadow according to both the scene and the light.
  46139. * @param activeCamera The camera we are returning the max for
  46140. * @returns the depth max z
  46141. */
  46142. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  46143. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  46144. };
  46145. /**
  46146. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  46147. * @param matrix The materix to updated with the projection information
  46148. * @param viewMatrix The transform matrix of the light
  46149. * @param renderList The list of mesh to render in the map
  46150. * @returns The current light
  46151. */
  46152. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46153. if (this.customProjectionMatrixBuilder) {
  46154. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  46155. }
  46156. else {
  46157. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  46158. }
  46159. return this;
  46160. };
  46161. __decorate([
  46162. BABYLON.serializeAsVector3()
  46163. ], ShadowLight.prototype, "position", null);
  46164. __decorate([
  46165. BABYLON.serializeAsVector3()
  46166. ], ShadowLight.prototype, "direction", null);
  46167. __decorate([
  46168. BABYLON.serialize()
  46169. ], ShadowLight.prototype, "shadowMinZ", null);
  46170. __decorate([
  46171. BABYLON.serialize()
  46172. ], ShadowLight.prototype, "shadowMaxZ", null);
  46173. return ShadowLight;
  46174. }(BABYLON.Light));
  46175. BABYLON.ShadowLight = ShadowLight;
  46176. })(BABYLON || (BABYLON = {}));
  46177. //# sourceMappingURL=babylon.shadowLight.js.map
  46178. "use strict";
  46179. var BABYLON;
  46180. (function (BABYLON) {
  46181. /**
  46182. * A point light is a light defined by an unique point in world space.
  46183. * The light is emitted in every direction from this point.
  46184. * A good example of a point light is a standard light bulb.
  46185. * Documentation: https://doc.babylonjs.com/babylon101/lights
  46186. */
  46187. var PointLight = /** @class */ (function (_super) {
  46188. __extends(PointLight, _super);
  46189. /**
  46190. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  46191. * A PointLight emits the light in every direction.
  46192. * It can cast shadows.
  46193. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  46194. * ```javascript
  46195. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  46196. * ```
  46197. * Documentation : http://doc.babylonjs.com/tutorials/lights
  46198. * @param name The light friendly name
  46199. * @param position The position of the point light in the scene
  46200. * @param scene The scene the lights belongs to
  46201. */
  46202. function PointLight(name, position, scene) {
  46203. var _this = _super.call(this, name, scene) || this;
  46204. _this._shadowAngle = Math.PI / 2;
  46205. _this.position = position;
  46206. return _this;
  46207. }
  46208. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  46209. /**
  46210. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  46211. * This specifies what angle the shadow will use to be created.
  46212. *
  46213. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  46214. */
  46215. get: function () {
  46216. return this._shadowAngle;
  46217. },
  46218. /**
  46219. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  46220. * This specifies what angle the shadow will use to be created.
  46221. *
  46222. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  46223. */
  46224. set: function (value) {
  46225. this._shadowAngle = value;
  46226. this.forceProjectionMatrixCompute();
  46227. },
  46228. enumerable: true,
  46229. configurable: true
  46230. });
  46231. Object.defineProperty(PointLight.prototype, "direction", {
  46232. /**
  46233. * Gets the direction if it has been set.
  46234. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  46235. */
  46236. get: function () {
  46237. return this._direction;
  46238. },
  46239. /**
  46240. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  46241. */
  46242. set: function (value) {
  46243. var previousNeedCube = this.needCube();
  46244. this._direction = value;
  46245. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  46246. this._shadowGenerator.recreateShadowMap();
  46247. }
  46248. },
  46249. enumerable: true,
  46250. configurable: true
  46251. });
  46252. /**
  46253. * Returns the string "PointLight"
  46254. * @returns the class name
  46255. */
  46256. PointLight.prototype.getClassName = function () {
  46257. return "PointLight";
  46258. };
  46259. /**
  46260. * Returns the integer 0.
  46261. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  46262. */
  46263. PointLight.prototype.getTypeID = function () {
  46264. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  46265. };
  46266. /**
  46267. * Specifies wether or not the shadowmap should be a cube texture.
  46268. * @returns true if the shadowmap needs to be a cube texture.
  46269. */
  46270. PointLight.prototype.needCube = function () {
  46271. return !this.direction;
  46272. };
  46273. /**
  46274. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  46275. * @param faceIndex The index of the face we are computed the direction to generate shadow
  46276. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  46277. */
  46278. PointLight.prototype.getShadowDirection = function (faceIndex) {
  46279. if (this.direction) {
  46280. return _super.prototype.getShadowDirection.call(this, faceIndex);
  46281. }
  46282. else {
  46283. switch (faceIndex) {
  46284. case 0:
  46285. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  46286. case 1:
  46287. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  46288. case 2:
  46289. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  46290. case 3:
  46291. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  46292. case 4:
  46293. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  46294. case 5:
  46295. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  46296. }
  46297. }
  46298. return BABYLON.Vector3.Zero();
  46299. };
  46300. /**
  46301. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  46302. * - fov = PI / 2
  46303. * - aspect ratio : 1.0
  46304. * - z-near and far equal to the active camera minZ and maxZ.
  46305. * Returns the PointLight.
  46306. */
  46307. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46308. var activeCamera = this.getScene().activeCamera;
  46309. if (!activeCamera) {
  46310. return;
  46311. }
  46312. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  46313. };
  46314. PointLight.prototype._buildUniformLayout = function () {
  46315. this._uniformBuffer.addUniform("vLightData", 4);
  46316. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  46317. this._uniformBuffer.addUniform("vLightSpecular", 3);
  46318. this._uniformBuffer.addUniform("shadowsInfo", 3);
  46319. this._uniformBuffer.addUniform("depthValues", 2);
  46320. this._uniformBuffer.create();
  46321. };
  46322. /**
  46323. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  46324. * @param effect The effect to update
  46325. * @param lightIndex The index of the light in the effect to update
  46326. * @returns The point light
  46327. */
  46328. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  46329. if (this.computeTransformedInformation()) {
  46330. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  46331. return this;
  46332. }
  46333. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  46334. return this;
  46335. };
  46336. __decorate([
  46337. BABYLON.serialize()
  46338. ], PointLight.prototype, "shadowAngle", null);
  46339. return PointLight;
  46340. }(BABYLON.ShadowLight));
  46341. BABYLON.PointLight = PointLight;
  46342. })(BABYLON || (BABYLON = {}));
  46343. //# sourceMappingURL=babylon.pointLight.js.map
  46344. "use strict";
  46345. var BABYLON;
  46346. (function (BABYLON) {
  46347. /**
  46348. * A directional light is defined by a direction (what a surprise!).
  46349. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  46350. * 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.
  46351. * Documentation: https://doc.babylonjs.com/babylon101/lights
  46352. */
  46353. var DirectionalLight = /** @class */ (function (_super) {
  46354. __extends(DirectionalLight, _super);
  46355. /**
  46356. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  46357. * The directional light is emitted from everywhere in the given direction.
  46358. * It can cast shawdows.
  46359. * Documentation : http://doc.babylonjs.com/tutorials/lights
  46360. * @param name The friendly name of the light
  46361. * @param direction The direction of the light
  46362. * @param scene The scene the light belongs to
  46363. */
  46364. function DirectionalLight(name, direction, scene) {
  46365. var _this = _super.call(this, name, scene) || this;
  46366. _this._shadowFrustumSize = 0;
  46367. _this._shadowOrthoScale = 0.1;
  46368. /**
  46369. * Automatically compute the projection matrix to best fit (including all the casters)
  46370. * on each frame.
  46371. */
  46372. _this.autoUpdateExtends = true;
  46373. // Cache
  46374. _this._orthoLeft = Number.MAX_VALUE;
  46375. _this._orthoRight = Number.MIN_VALUE;
  46376. _this._orthoTop = Number.MIN_VALUE;
  46377. _this._orthoBottom = Number.MAX_VALUE;
  46378. _this.position = direction.scale(-1.0);
  46379. _this.direction = direction;
  46380. return _this;
  46381. }
  46382. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  46383. /**
  46384. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  46385. */
  46386. get: function () {
  46387. return this._shadowFrustumSize;
  46388. },
  46389. /**
  46390. * Specifies a fix frustum size for the shadow generation.
  46391. */
  46392. set: function (value) {
  46393. this._shadowFrustumSize = value;
  46394. this.forceProjectionMatrixCompute();
  46395. },
  46396. enumerable: true,
  46397. configurable: true
  46398. });
  46399. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  46400. /**
  46401. * Gets the shadow projection scale against the optimal computed one.
  46402. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  46403. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  46404. */
  46405. get: function () {
  46406. return this._shadowOrthoScale;
  46407. },
  46408. /**
  46409. * Sets the shadow projection scale against the optimal computed one.
  46410. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  46411. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  46412. */
  46413. set: function (value) {
  46414. this._shadowOrthoScale = value;
  46415. this.forceProjectionMatrixCompute();
  46416. },
  46417. enumerable: true,
  46418. configurable: true
  46419. });
  46420. /**
  46421. * Returns the string "DirectionalLight".
  46422. * @return The class name
  46423. */
  46424. DirectionalLight.prototype.getClassName = function () {
  46425. return "DirectionalLight";
  46426. };
  46427. /**
  46428. * Returns the integer 1.
  46429. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  46430. */
  46431. DirectionalLight.prototype.getTypeID = function () {
  46432. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  46433. };
  46434. /**
  46435. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  46436. * Returns the DirectionalLight Shadow projection matrix.
  46437. */
  46438. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46439. if (this.shadowFrustumSize > 0) {
  46440. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  46441. }
  46442. else {
  46443. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  46444. }
  46445. };
  46446. /**
  46447. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  46448. * Returns the DirectionalLight Shadow projection matrix.
  46449. */
  46450. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  46451. var activeCamera = this.getScene().activeCamera;
  46452. if (!activeCamera) {
  46453. return;
  46454. }
  46455. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  46456. };
  46457. /**
  46458. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  46459. * Returns the DirectionalLight Shadow projection matrix.
  46460. */
  46461. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46462. var activeCamera = this.getScene().activeCamera;
  46463. if (!activeCamera) {
  46464. return;
  46465. }
  46466. // Check extends
  46467. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  46468. var tempVector3 = BABYLON.Vector3.Zero();
  46469. this._orthoLeft = Number.MAX_VALUE;
  46470. this._orthoRight = Number.MIN_VALUE;
  46471. this._orthoTop = Number.MIN_VALUE;
  46472. this._orthoBottom = Number.MAX_VALUE;
  46473. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  46474. var mesh = renderList[meshIndex];
  46475. if (!mesh) {
  46476. continue;
  46477. }
  46478. var boundingInfo = mesh.getBoundingInfo();
  46479. var boundingBox = boundingInfo.boundingBox;
  46480. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  46481. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  46482. if (tempVector3.x < this._orthoLeft)
  46483. this._orthoLeft = tempVector3.x;
  46484. if (tempVector3.y < this._orthoBottom)
  46485. this._orthoBottom = tempVector3.y;
  46486. if (tempVector3.x > this._orthoRight)
  46487. this._orthoRight = tempVector3.x;
  46488. if (tempVector3.y > this._orthoTop)
  46489. this._orthoTop = tempVector3.y;
  46490. }
  46491. }
  46492. }
  46493. var xOffset = this._orthoRight - this._orthoLeft;
  46494. var yOffset = this._orthoTop - this._orthoBottom;
  46495. 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);
  46496. };
  46497. DirectionalLight.prototype._buildUniformLayout = function () {
  46498. this._uniformBuffer.addUniform("vLightData", 4);
  46499. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  46500. this._uniformBuffer.addUniform("vLightSpecular", 3);
  46501. this._uniformBuffer.addUniform("shadowsInfo", 3);
  46502. this._uniformBuffer.addUniform("depthValues", 2);
  46503. this._uniformBuffer.create();
  46504. };
  46505. /**
  46506. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  46507. * @param effect The effect to update
  46508. * @param lightIndex The index of the light in the effect to update
  46509. * @returns The directional light
  46510. */
  46511. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  46512. if (this.computeTransformedInformation()) {
  46513. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  46514. return this;
  46515. }
  46516. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  46517. return this;
  46518. };
  46519. /**
  46520. * Gets the minZ used for shadow according to both the scene and the light.
  46521. *
  46522. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  46523. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  46524. * @param activeCamera The camera we are returning the min for
  46525. * @returns the depth min z
  46526. */
  46527. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  46528. return 1;
  46529. };
  46530. /**
  46531. * Gets the maxZ used for shadow according to both the scene and the light.
  46532. *
  46533. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  46534. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  46535. * @param activeCamera The camera we are returning the max for
  46536. * @returns the depth max z
  46537. */
  46538. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  46539. return 1;
  46540. };
  46541. __decorate([
  46542. BABYLON.serialize()
  46543. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  46544. __decorate([
  46545. BABYLON.serialize()
  46546. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  46547. __decorate([
  46548. BABYLON.serialize()
  46549. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  46550. return DirectionalLight;
  46551. }(BABYLON.ShadowLight));
  46552. BABYLON.DirectionalLight = DirectionalLight;
  46553. })(BABYLON || (BABYLON = {}));
  46554. //# sourceMappingURL=babylon.directionalLight.js.map
  46555. "use strict";
  46556. var BABYLON;
  46557. (function (BABYLON) {
  46558. /**
  46559. * A spot light is defined by a position, a direction, an angle, and an exponent.
  46560. * These values define a cone of light starting from the position, emitting toward the direction.
  46561. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  46562. * and the exponent defines the speed of the decay of the light with distance (reach).
  46563. * Documentation: https://doc.babylonjs.com/babylon101/lights
  46564. */
  46565. var SpotLight = /** @class */ (function (_super) {
  46566. __extends(SpotLight, _super);
  46567. /**
  46568. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  46569. * It can cast shadows.
  46570. * Documentation : http://doc.babylonjs.com/tutorials/lights
  46571. * @param name The light friendly name
  46572. * @param position The position of the spot light in the scene
  46573. * @param direction The direction of the light in the scene
  46574. * @param angle The cone angle of the light in Radians
  46575. * @param exponent The light decay speed with the distance from the emission spot
  46576. * @param scene The scene the lights belongs to
  46577. */
  46578. function SpotLight(name, position, direction, angle, exponent, scene) {
  46579. var _this = _super.call(this, name, scene) || this;
  46580. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  46581. _this._projectionTextureLightNear = 1e-6;
  46582. _this._projectionTextureLightFar = 1000.0;
  46583. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  46584. _this._projectionTextureViewLightDirty = true;
  46585. _this._projectionTextureProjectionLightDirty = true;
  46586. _this._projectionTextureDirty = true;
  46587. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  46588. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  46589. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  46590. _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);
  46591. _this.position = position;
  46592. _this.direction = direction;
  46593. _this.angle = angle;
  46594. _this.exponent = exponent;
  46595. return _this;
  46596. }
  46597. Object.defineProperty(SpotLight.prototype, "angle", {
  46598. /**
  46599. * Gets the cone angle of the spot light in Radians.
  46600. */
  46601. get: function () {
  46602. return this._angle;
  46603. },
  46604. /**
  46605. * Sets the cone angle of the spot light in Radians.
  46606. */
  46607. set: function (value) {
  46608. this._angle = value;
  46609. this._projectionTextureProjectionLightDirty = true;
  46610. this.forceProjectionMatrixCompute();
  46611. },
  46612. enumerable: true,
  46613. configurable: true
  46614. });
  46615. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  46616. /**
  46617. * Allows scaling the angle of the light for shadow generation only.
  46618. */
  46619. get: function () {
  46620. return this._shadowAngleScale;
  46621. },
  46622. /**
  46623. * Allows scaling the angle of the light for shadow generation only.
  46624. */
  46625. set: function (value) {
  46626. this._shadowAngleScale = value;
  46627. this.forceProjectionMatrixCompute();
  46628. },
  46629. enumerable: true,
  46630. configurable: true
  46631. });
  46632. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  46633. /**
  46634. * Allows reading the projecton texture
  46635. */
  46636. get: function () {
  46637. return this._projectionTextureMatrix;
  46638. },
  46639. enumerable: true,
  46640. configurable: true
  46641. });
  46642. ;
  46643. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  46644. /**
  46645. * Gets the near clip of the Spotlight for texture projection.
  46646. */
  46647. get: function () {
  46648. return this._projectionTextureLightNear;
  46649. },
  46650. /**
  46651. * Sets the near clip of the Spotlight for texture projection.
  46652. */
  46653. set: function (value) {
  46654. this._projectionTextureLightNear = value;
  46655. this._projectionTextureProjectionLightDirty = true;
  46656. },
  46657. enumerable: true,
  46658. configurable: true
  46659. });
  46660. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  46661. /**
  46662. * Gets the far clip of the Spotlight for texture projection.
  46663. */
  46664. get: function () {
  46665. return this._projectionTextureLightFar;
  46666. },
  46667. /**
  46668. * Sets the far clip of the Spotlight for texture projection.
  46669. */
  46670. set: function (value) {
  46671. this._projectionTextureLightFar = value;
  46672. this._projectionTextureProjectionLightDirty = true;
  46673. },
  46674. enumerable: true,
  46675. configurable: true
  46676. });
  46677. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  46678. /**
  46679. * Gets the Up vector of the Spotlight for texture projection.
  46680. */
  46681. get: function () {
  46682. return this._projectionTextureUpDirection;
  46683. },
  46684. /**
  46685. * Sets the Up vector of the Spotlight for texture projection.
  46686. */
  46687. set: function (value) {
  46688. this._projectionTextureUpDirection = value;
  46689. this._projectionTextureProjectionLightDirty = true;
  46690. },
  46691. enumerable: true,
  46692. configurable: true
  46693. });
  46694. ;
  46695. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  46696. /**
  46697. * Gets the projection texture of the light.
  46698. */
  46699. get: function () {
  46700. return this._projectionTexture;
  46701. },
  46702. /**
  46703. * Sets the projection texture of the light.
  46704. */
  46705. set: function (value) {
  46706. this._projectionTexture = value;
  46707. this._projectionTextureDirty = true;
  46708. },
  46709. enumerable: true,
  46710. configurable: true
  46711. });
  46712. /**
  46713. * Returns the string "SpotLight".
  46714. * @returns the class name
  46715. */
  46716. SpotLight.prototype.getClassName = function () {
  46717. return "SpotLight";
  46718. };
  46719. /**
  46720. * Returns the integer 2.
  46721. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  46722. */
  46723. SpotLight.prototype.getTypeID = function () {
  46724. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  46725. };
  46726. /**
  46727. * Overrides the direction setter to recompute the projection texture view light Matrix.
  46728. */
  46729. SpotLight.prototype._setDirection = function (value) {
  46730. _super.prototype._setDirection.call(this, value);
  46731. this._projectionTextureViewLightDirty = true;
  46732. };
  46733. /**
  46734. * Overrides the position setter to recompute the projection texture view light Matrix.
  46735. */
  46736. SpotLight.prototype._setPosition = function (value) {
  46737. _super.prototype._setPosition.call(this, value);
  46738. this._projectionTextureViewLightDirty = true;
  46739. };
  46740. /**
  46741. * 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.
  46742. * Returns the SpotLight.
  46743. */
  46744. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46745. var activeCamera = this.getScene().activeCamera;
  46746. if (!activeCamera) {
  46747. return;
  46748. }
  46749. this._shadowAngleScale = this._shadowAngleScale || 1;
  46750. var angle = this._shadowAngleScale * this._angle;
  46751. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  46752. };
  46753. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  46754. this._projectionTextureViewLightDirty = false;
  46755. this._projectionTextureDirty = true;
  46756. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  46757. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  46758. };
  46759. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  46760. this._projectionTextureProjectionLightDirty = false;
  46761. this._projectionTextureDirty = true;
  46762. var light_far = this.projectionTextureLightFar;
  46763. var light_near = this.projectionTextureLightNear;
  46764. var P = light_far / (light_far - light_near);
  46765. var Q = -P * light_near;
  46766. var S = 1.0 / Math.tan(this._angle / 2.0);
  46767. var A = 1.0;
  46768. 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);
  46769. };
  46770. /**
  46771. * Main function for light texture projection matrix computing.
  46772. */
  46773. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  46774. this._projectionTextureDirty = false;
  46775. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  46776. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  46777. };
  46778. SpotLight.prototype._buildUniformLayout = function () {
  46779. this._uniformBuffer.addUniform("vLightData", 4);
  46780. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  46781. this._uniformBuffer.addUniform("vLightSpecular", 3);
  46782. this._uniformBuffer.addUniform("vLightDirection", 3);
  46783. this._uniformBuffer.addUniform("shadowsInfo", 3);
  46784. this._uniformBuffer.addUniform("depthValues", 2);
  46785. this._uniformBuffer.create();
  46786. };
  46787. /**
  46788. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  46789. * @param effect The effect to update
  46790. * @param lightIndex The index of the light in the effect to update
  46791. * @returns The spot light
  46792. */
  46793. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  46794. var normalizeDirection;
  46795. if (this.computeTransformedInformation()) {
  46796. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  46797. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  46798. }
  46799. else {
  46800. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  46801. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  46802. }
  46803. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  46804. if (this.projectionTexture && this.projectionTexture.isReady()) {
  46805. if (this._projectionTextureViewLightDirty) {
  46806. this._computeProjectionTextureViewLightMatrix();
  46807. }
  46808. if (this._projectionTextureProjectionLightDirty) {
  46809. this._computeProjectionTextureProjectionLightMatrix();
  46810. }
  46811. if (this._projectionTextureDirty) {
  46812. this._computeProjectionTextureMatrix();
  46813. }
  46814. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  46815. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  46816. }
  46817. return this;
  46818. };
  46819. /**
  46820. * Disposes the light and the associated resources.
  46821. */
  46822. SpotLight.prototype.dispose = function () {
  46823. _super.prototype.dispose.call(this);
  46824. if (this._projectionTexture) {
  46825. this._projectionTexture.dispose();
  46826. }
  46827. };
  46828. __decorate([
  46829. BABYLON.serialize()
  46830. ], SpotLight.prototype, "angle", null);
  46831. __decorate([
  46832. BABYLON.serialize()
  46833. ], SpotLight.prototype, "shadowAngleScale", null);
  46834. __decorate([
  46835. BABYLON.serialize()
  46836. ], SpotLight.prototype, "exponent", void 0);
  46837. __decorate([
  46838. BABYLON.serialize()
  46839. ], SpotLight.prototype, "projectionTextureLightNear", null);
  46840. __decorate([
  46841. BABYLON.serialize()
  46842. ], SpotLight.prototype, "projectionTextureLightFar", null);
  46843. __decorate([
  46844. BABYLON.serialize()
  46845. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  46846. __decorate([
  46847. BABYLON.serializeAsTexture("projectedLightTexture")
  46848. ], SpotLight.prototype, "_projectionTexture", void 0);
  46849. return SpotLight;
  46850. }(BABYLON.ShadowLight));
  46851. BABYLON.SpotLight = SpotLight;
  46852. })(BABYLON || (BABYLON = {}));
  46853. //# sourceMappingURL=babylon.spotLight.js.map
  46854. "use strict";
  46855. var BABYLON;
  46856. (function (BABYLON) {
  46857. /**
  46858. * Class used to override all child animations of a given target
  46859. */
  46860. var AnimationPropertiesOverride = /** @class */ (function () {
  46861. function AnimationPropertiesOverride() {
  46862. /**
  46863. * Gets or sets a value indicating if animation blending must be used
  46864. */
  46865. this.enableBlending = false;
  46866. /**
  46867. * Gets or sets the blending speed to use when enableBlending is true
  46868. */
  46869. this.blendingSpeed = 0.01;
  46870. /**
  46871. * Gets or sets the default loop mode to use
  46872. */
  46873. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  46874. }
  46875. return AnimationPropertiesOverride;
  46876. }());
  46877. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  46878. })(BABYLON || (BABYLON = {}));
  46879. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  46880. "use strict";
  46881. var BABYLON;
  46882. (function (BABYLON) {
  46883. var AnimationRange = /** @class */ (function () {
  46884. function AnimationRange(name, from, to) {
  46885. this.name = name;
  46886. this.from = from;
  46887. this.to = to;
  46888. }
  46889. AnimationRange.prototype.clone = function () {
  46890. return new AnimationRange(this.name, this.from, this.to);
  46891. };
  46892. return AnimationRange;
  46893. }());
  46894. BABYLON.AnimationRange = AnimationRange;
  46895. /**
  46896. * Composed of a frame, and an action function
  46897. */
  46898. var AnimationEvent = /** @class */ (function () {
  46899. function AnimationEvent(frame, action, onlyOnce) {
  46900. this.frame = frame;
  46901. this.action = action;
  46902. this.onlyOnce = onlyOnce;
  46903. this.isDone = false;
  46904. }
  46905. return AnimationEvent;
  46906. }());
  46907. BABYLON.AnimationEvent = AnimationEvent;
  46908. var PathCursor = /** @class */ (function () {
  46909. function PathCursor(path) {
  46910. this.path = path;
  46911. this._onchange = new Array();
  46912. this.value = 0;
  46913. this.animations = new Array();
  46914. }
  46915. PathCursor.prototype.getPoint = function () {
  46916. var point = this.path.getPointAtLengthPosition(this.value);
  46917. return new BABYLON.Vector3(point.x, 0, point.y);
  46918. };
  46919. PathCursor.prototype.moveAhead = function (step) {
  46920. if (step === void 0) { step = 0.002; }
  46921. this.move(step);
  46922. return this;
  46923. };
  46924. PathCursor.prototype.moveBack = function (step) {
  46925. if (step === void 0) { step = 0.002; }
  46926. this.move(-step);
  46927. return this;
  46928. };
  46929. PathCursor.prototype.move = function (step) {
  46930. if (Math.abs(step) > 1) {
  46931. throw "step size should be less than 1.";
  46932. }
  46933. this.value += step;
  46934. this.ensureLimits();
  46935. this.raiseOnChange();
  46936. return this;
  46937. };
  46938. PathCursor.prototype.ensureLimits = function () {
  46939. while (this.value > 1) {
  46940. this.value -= 1;
  46941. }
  46942. while (this.value < 0) {
  46943. this.value += 1;
  46944. }
  46945. return this;
  46946. };
  46947. // used by animation engine
  46948. PathCursor.prototype.raiseOnChange = function () {
  46949. var _this = this;
  46950. this._onchange.forEach(function (f) { return f(_this); });
  46951. return this;
  46952. };
  46953. PathCursor.prototype.onchange = function (f) {
  46954. this._onchange.push(f);
  46955. return this;
  46956. };
  46957. return PathCursor;
  46958. }());
  46959. BABYLON.PathCursor = PathCursor;
  46960. var AnimationKeyInterpolation;
  46961. (function (AnimationKeyInterpolation) {
  46962. /**
  46963. * Do not interpolate between keys and use the start key value only. Tangents are ignored.
  46964. */
  46965. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  46966. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  46967. var Animation = /** @class */ (function () {
  46968. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  46969. this.name = name;
  46970. this.targetProperty = targetProperty;
  46971. this.framePerSecond = framePerSecond;
  46972. this.dataType = dataType;
  46973. this.loopMode = loopMode;
  46974. this.enableBlending = enableBlending;
  46975. this._runtimeAnimations = new Array();
  46976. // The set of event that will be linked to this animation
  46977. this._events = new Array();
  46978. this.blendingSpeed = 0.01;
  46979. this._ranges = {};
  46980. this.targetPropertyPath = targetProperty.split(".");
  46981. this.dataType = dataType;
  46982. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  46983. }
  46984. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  46985. var dataType = undefined;
  46986. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  46987. dataType = Animation.ANIMATIONTYPE_FLOAT;
  46988. }
  46989. else if (from instanceof BABYLON.Quaternion) {
  46990. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  46991. }
  46992. else if (from instanceof BABYLON.Vector3) {
  46993. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  46994. }
  46995. else if (from instanceof BABYLON.Vector2) {
  46996. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  46997. }
  46998. else if (from instanceof BABYLON.Color3) {
  46999. dataType = Animation.ANIMATIONTYPE_COLOR3;
  47000. }
  47001. else if (from instanceof BABYLON.Size) {
  47002. dataType = Animation.ANIMATIONTYPE_SIZE;
  47003. }
  47004. if (dataType == undefined) {
  47005. return null;
  47006. }
  47007. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  47008. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  47009. animation.setKeys(keys);
  47010. if (easingFunction !== undefined) {
  47011. animation.setEasingFunction(easingFunction);
  47012. }
  47013. return animation;
  47014. };
  47015. /**
  47016. * Sets up an animation.
  47017. * @param property the property to animate
  47018. * @param animationType the animation type to apply
  47019. * @param easingFunction the easing function used in the animation
  47020. * @returns The created animation
  47021. */
  47022. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  47023. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  47024. animation.setEasingFunction(easingFunction);
  47025. return animation;
  47026. };
  47027. /**
  47028. * Create and start an animation on a node
  47029. * @param {string} name defines the name of the global animation that will be run on all nodes
  47030. * @param {BABYLON.Node} node defines the root node where the animation will take place
  47031. * @param {string} targetProperty defines property to animate
  47032. * @param {number} framePerSecond defines the number of frame per second yo use
  47033. * @param {number} totalFrame defines the number of frames in total
  47034. * @param {any} from defines the initial value
  47035. * @param {any} to defines the final value
  47036. * @param {number} loopMode defines which loop mode you want to use (off by default)
  47037. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  47038. * @param onAnimationEnd defines the callback to call when animation end
  47039. * @returns the animatable created for this animation
  47040. */
  47041. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  47042. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  47043. if (!animation) {
  47044. return null;
  47045. }
  47046. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  47047. };
  47048. /**
  47049. * Create and start an animation on a node and its descendants
  47050. * @param {string} name defines the name of the global animation that will be run on all nodes
  47051. * @param {BABYLON.Node} node defines the root node where the animation will take place
  47052. * @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.
  47053. * @param {string} targetProperty defines property to animate
  47054. * @param {number} framePerSecond defines the number of frame per second yo use
  47055. * @param {number} totalFrame defines the number of frames in total
  47056. * @param {any} from defines the initial value
  47057. * @param {any} to defines the final value
  47058. * @param {number} loopMode defines which loop mode you want to use (off by default)
  47059. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  47060. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  47061. * @returns the list of animatables created for all nodes
  47062. * @example https://www.babylonjs-playground.com/#MH0VLI
  47063. */
  47064. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  47065. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  47066. if (!animation) {
  47067. return null;
  47068. }
  47069. var scene = node.getScene();
  47070. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  47071. };
  47072. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  47073. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  47074. if (!animation) {
  47075. return null;
  47076. }
  47077. node.animations.push(animation);
  47078. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  47079. };
  47080. /**
  47081. * Transition property of the Camera to the target Value.
  47082. * @param property The property to transition
  47083. * @param targetValue The target Value of the property
  47084. * @param host The object where the property to animate belongs
  47085. * @param scene Scene used to run the animation
  47086. * @param frameRate Framerate (in frame/s) to use
  47087. * @param transition The transition type we want to use
  47088. * @param duration The duration of the animation, in milliseconds
  47089. * @param onAnimationEnd Call back trigger at the end of the animation.
  47090. */
  47091. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  47092. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  47093. if (duration <= 0) {
  47094. host[property] = targetValue;
  47095. if (onAnimationEnd) {
  47096. onAnimationEnd();
  47097. }
  47098. return null;
  47099. }
  47100. var endFrame = frameRate * (duration / 1000);
  47101. transition.setKeys([{
  47102. frame: 0,
  47103. value: host[property].clone ? host[property].clone() : host[property]
  47104. },
  47105. {
  47106. frame: endFrame,
  47107. value: targetValue
  47108. }]);
  47109. if (!host.animations) {
  47110. host.animations = [];
  47111. }
  47112. host.animations.push(transition);
  47113. var animation = scene.beginAnimation(host, 0, endFrame, false);
  47114. animation.onAnimationEnd = onAnimationEnd;
  47115. return animation;
  47116. };
  47117. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  47118. /**
  47119. * Return the array of runtime animations currently using this animation
  47120. */
  47121. get: function () {
  47122. return this._runtimeAnimations;
  47123. },
  47124. enumerable: true,
  47125. configurable: true
  47126. });
  47127. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  47128. get: function () {
  47129. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  47130. var runtimeAnimation = _a[_i];
  47131. if (!runtimeAnimation.isStopped) {
  47132. return true;
  47133. }
  47134. }
  47135. return false;
  47136. },
  47137. enumerable: true,
  47138. configurable: true
  47139. });
  47140. // Methods
  47141. /**
  47142. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  47143. */
  47144. Animation.prototype.toString = function (fullDetails) {
  47145. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  47146. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  47147. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  47148. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  47149. if (fullDetails) {
  47150. ret += ", Ranges: {";
  47151. var first = true;
  47152. for (var name in this._ranges) {
  47153. if (first) {
  47154. ret += ", ";
  47155. first = false;
  47156. }
  47157. ret += name;
  47158. }
  47159. ret += "}";
  47160. }
  47161. return ret;
  47162. };
  47163. /**
  47164. * Add an event to this animation.
  47165. */
  47166. Animation.prototype.addEvent = function (event) {
  47167. this._events.push(event);
  47168. };
  47169. /**
  47170. * Remove all events found at the given frame
  47171. * @param frame
  47172. */
  47173. Animation.prototype.removeEvents = function (frame) {
  47174. for (var index = 0; index < this._events.length; index++) {
  47175. if (this._events[index].frame === frame) {
  47176. this._events.splice(index, 1);
  47177. index--;
  47178. }
  47179. }
  47180. };
  47181. Animation.prototype.getEvents = function () {
  47182. return this._events;
  47183. };
  47184. Animation.prototype.createRange = function (name, from, to) {
  47185. // check name not already in use; could happen for bones after serialized
  47186. if (!this._ranges[name]) {
  47187. this._ranges[name] = new AnimationRange(name, from, to);
  47188. }
  47189. };
  47190. Animation.prototype.deleteRange = function (name, deleteFrames) {
  47191. if (deleteFrames === void 0) { deleteFrames = true; }
  47192. var range = this._ranges[name];
  47193. if (!range) {
  47194. return;
  47195. }
  47196. if (deleteFrames) {
  47197. var from = range.from;
  47198. var to = range.to;
  47199. // this loop MUST go high to low for multiple splices to work
  47200. for (var key = this._keys.length - 1; key >= 0; key--) {
  47201. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  47202. this._keys.splice(key, 1);
  47203. }
  47204. }
  47205. }
  47206. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  47207. };
  47208. Animation.prototype.getRange = function (name) {
  47209. return this._ranges[name];
  47210. };
  47211. Animation.prototype.getKeys = function () {
  47212. return this._keys;
  47213. };
  47214. Animation.prototype.getHighestFrame = function () {
  47215. var ret = 0;
  47216. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  47217. if (ret < this._keys[key].frame) {
  47218. ret = this._keys[key].frame;
  47219. }
  47220. }
  47221. return ret;
  47222. };
  47223. Animation.prototype.getEasingFunction = function () {
  47224. return this._easingFunction;
  47225. };
  47226. Animation.prototype.setEasingFunction = function (easingFunction) {
  47227. this._easingFunction = easingFunction;
  47228. };
  47229. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  47230. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  47231. };
  47232. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  47233. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  47234. };
  47235. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  47236. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  47237. };
  47238. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  47239. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  47240. };
  47241. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  47242. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  47243. };
  47244. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  47245. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  47246. };
  47247. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  47248. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  47249. };
  47250. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  47251. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  47252. };
  47253. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  47254. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  47255. };
  47256. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  47257. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  47258. };
  47259. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  47260. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  47261. };
  47262. Animation.prototype.clone = function () {
  47263. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  47264. clone.enableBlending = this.enableBlending;
  47265. clone.blendingSpeed = this.blendingSpeed;
  47266. if (this._keys) {
  47267. clone.setKeys(this._keys);
  47268. }
  47269. if (this._ranges) {
  47270. clone._ranges = {};
  47271. for (var name in this._ranges) {
  47272. var range = this._ranges[name];
  47273. if (!range) {
  47274. continue;
  47275. }
  47276. clone._ranges[name] = range.clone();
  47277. }
  47278. }
  47279. return clone;
  47280. };
  47281. Animation.prototype.setKeys = function (values) {
  47282. this._keys = values.slice(0);
  47283. };
  47284. Animation.prototype.serialize = function () {
  47285. var serializationObject = {};
  47286. serializationObject.name = this.name;
  47287. serializationObject.property = this.targetProperty;
  47288. serializationObject.framePerSecond = this.framePerSecond;
  47289. serializationObject.dataType = this.dataType;
  47290. serializationObject.loopBehavior = this.loopMode;
  47291. serializationObject.enableBlending = this.enableBlending;
  47292. serializationObject.blendingSpeed = this.blendingSpeed;
  47293. var dataType = this.dataType;
  47294. serializationObject.keys = [];
  47295. var keys = this.getKeys();
  47296. for (var index = 0; index < keys.length; index++) {
  47297. var animationKey = keys[index];
  47298. var key = {};
  47299. key.frame = animationKey.frame;
  47300. switch (dataType) {
  47301. case Animation.ANIMATIONTYPE_FLOAT:
  47302. key.values = [animationKey.value];
  47303. break;
  47304. case Animation.ANIMATIONTYPE_QUATERNION:
  47305. case Animation.ANIMATIONTYPE_MATRIX:
  47306. case Animation.ANIMATIONTYPE_VECTOR3:
  47307. case Animation.ANIMATIONTYPE_COLOR3:
  47308. key.values = animationKey.value.asArray();
  47309. break;
  47310. }
  47311. serializationObject.keys.push(key);
  47312. }
  47313. serializationObject.ranges = [];
  47314. for (var name in this._ranges) {
  47315. var source = this._ranges[name];
  47316. if (!source) {
  47317. continue;
  47318. }
  47319. var range = {};
  47320. range.name = name;
  47321. range.from = source.from;
  47322. range.to = source.to;
  47323. serializationObject.ranges.push(range);
  47324. }
  47325. return serializationObject;
  47326. };
  47327. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  47328. get: function () {
  47329. return Animation._ANIMATIONTYPE_FLOAT;
  47330. },
  47331. enumerable: true,
  47332. configurable: true
  47333. });
  47334. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  47335. get: function () {
  47336. return Animation._ANIMATIONTYPE_VECTOR3;
  47337. },
  47338. enumerable: true,
  47339. configurable: true
  47340. });
  47341. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  47342. get: function () {
  47343. return Animation._ANIMATIONTYPE_VECTOR2;
  47344. },
  47345. enumerable: true,
  47346. configurable: true
  47347. });
  47348. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  47349. get: function () {
  47350. return Animation._ANIMATIONTYPE_SIZE;
  47351. },
  47352. enumerable: true,
  47353. configurable: true
  47354. });
  47355. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  47356. get: function () {
  47357. return Animation._ANIMATIONTYPE_QUATERNION;
  47358. },
  47359. enumerable: true,
  47360. configurable: true
  47361. });
  47362. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  47363. get: function () {
  47364. return Animation._ANIMATIONTYPE_MATRIX;
  47365. },
  47366. enumerable: true,
  47367. configurable: true
  47368. });
  47369. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  47370. get: function () {
  47371. return Animation._ANIMATIONTYPE_COLOR3;
  47372. },
  47373. enumerable: true,
  47374. configurable: true
  47375. });
  47376. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  47377. get: function () {
  47378. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  47379. },
  47380. enumerable: true,
  47381. configurable: true
  47382. });
  47383. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  47384. get: function () {
  47385. return Animation._ANIMATIONLOOPMODE_CYCLE;
  47386. },
  47387. enumerable: true,
  47388. configurable: true
  47389. });
  47390. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  47391. get: function () {
  47392. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  47393. },
  47394. enumerable: true,
  47395. configurable: true
  47396. });
  47397. Animation.Parse = function (parsedAnimation) {
  47398. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  47399. var dataType = parsedAnimation.dataType;
  47400. var keys = [];
  47401. var data;
  47402. var index;
  47403. if (parsedAnimation.enableBlending) {
  47404. animation.enableBlending = parsedAnimation.enableBlending;
  47405. }
  47406. if (parsedAnimation.blendingSpeed) {
  47407. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  47408. }
  47409. for (index = 0; index < parsedAnimation.keys.length; index++) {
  47410. var key = parsedAnimation.keys[index];
  47411. var inTangent;
  47412. var outTangent;
  47413. switch (dataType) {
  47414. case Animation.ANIMATIONTYPE_FLOAT:
  47415. data = key.values[0];
  47416. if (key.values.length >= 1) {
  47417. inTangent = key.values[1];
  47418. }
  47419. if (key.values.length >= 2) {
  47420. outTangent = key.values[2];
  47421. }
  47422. break;
  47423. case Animation.ANIMATIONTYPE_QUATERNION:
  47424. data = BABYLON.Quaternion.FromArray(key.values);
  47425. if (key.values.length >= 8) {
  47426. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  47427. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  47428. inTangent = _inTangent;
  47429. }
  47430. }
  47431. if (key.values.length >= 12) {
  47432. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  47433. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  47434. outTangent = _outTangent;
  47435. }
  47436. }
  47437. break;
  47438. case Animation.ANIMATIONTYPE_MATRIX:
  47439. data = BABYLON.Matrix.FromArray(key.values);
  47440. break;
  47441. case Animation.ANIMATIONTYPE_COLOR3:
  47442. data = BABYLON.Color3.FromArray(key.values);
  47443. break;
  47444. case Animation.ANIMATIONTYPE_VECTOR3:
  47445. default:
  47446. data = BABYLON.Vector3.FromArray(key.values);
  47447. break;
  47448. }
  47449. var keyData = {};
  47450. keyData.frame = key.frame;
  47451. keyData.value = data;
  47452. if (inTangent != undefined) {
  47453. keyData.inTangent = inTangent;
  47454. }
  47455. if (outTangent != undefined) {
  47456. keyData.outTangent = outTangent;
  47457. }
  47458. keys.push(keyData);
  47459. }
  47460. animation.setKeys(keys);
  47461. if (parsedAnimation.ranges) {
  47462. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  47463. data = parsedAnimation.ranges[index];
  47464. animation.createRange(data.name, data.from, data.to);
  47465. }
  47466. }
  47467. return animation;
  47468. };
  47469. Animation.AppendSerializedAnimations = function (source, destination) {
  47470. if (source.animations) {
  47471. destination.animations = [];
  47472. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  47473. var animation = source.animations[animationIndex];
  47474. destination.animations.push(animation.serialize());
  47475. }
  47476. }
  47477. };
  47478. Animation.AllowMatricesInterpolation = false;
  47479. // Statics
  47480. Animation._ANIMATIONTYPE_FLOAT = 0;
  47481. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  47482. Animation._ANIMATIONTYPE_QUATERNION = 2;
  47483. Animation._ANIMATIONTYPE_MATRIX = 3;
  47484. Animation._ANIMATIONTYPE_COLOR3 = 4;
  47485. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  47486. Animation._ANIMATIONTYPE_SIZE = 6;
  47487. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  47488. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  47489. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  47490. return Animation;
  47491. }());
  47492. BABYLON.Animation = Animation;
  47493. })(BABYLON || (BABYLON = {}));
  47494. //# sourceMappingURL=babylon.animation.js.map
  47495. "use strict";
  47496. var BABYLON;
  47497. (function (BABYLON) {
  47498. /**
  47499. * This class defines the direct association between an animation and a target
  47500. */
  47501. var TargetedAnimation = /** @class */ (function () {
  47502. function TargetedAnimation() {
  47503. }
  47504. return TargetedAnimation;
  47505. }());
  47506. BABYLON.TargetedAnimation = TargetedAnimation;
  47507. /**
  47508. * Use this class to create coordinated animations on multiple targets
  47509. */
  47510. var AnimationGroup = /** @class */ (function () {
  47511. function AnimationGroup(name, scene) {
  47512. if (scene === void 0) { scene = null; }
  47513. this.name = name;
  47514. this._targetedAnimations = new Array();
  47515. this._animatables = new Array();
  47516. this._from = Number.MAX_VALUE;
  47517. this._to = -Number.MAX_VALUE;
  47518. this._speedRatio = 1;
  47519. this.onAnimationEndObservable = new BABYLON.Observable();
  47520. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  47521. this._scene.animationGroups.push(this);
  47522. }
  47523. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  47524. /**
  47525. * Define if the animations are started
  47526. */
  47527. get: function () {
  47528. return this._isStarted;
  47529. },
  47530. enumerable: true,
  47531. configurable: true
  47532. });
  47533. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  47534. /**
  47535. * Gets or sets the speed ratio to use for all animations
  47536. */
  47537. get: function () {
  47538. return this._speedRatio;
  47539. },
  47540. /**
  47541. * Gets or sets the speed ratio to use for all animations
  47542. */
  47543. set: function (value) {
  47544. if (this._speedRatio === value) {
  47545. return;
  47546. }
  47547. this._speedRatio = value;
  47548. for (var index = 0; index < this._animatables.length; index++) {
  47549. var animatable = this._animatables[index];
  47550. animatable.speedRatio = this._speedRatio;
  47551. }
  47552. },
  47553. enumerable: true,
  47554. configurable: true
  47555. });
  47556. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  47557. /**
  47558. * Gets the targeted animations for this animation group
  47559. */
  47560. get: function () {
  47561. return this._targetedAnimations;
  47562. },
  47563. enumerable: true,
  47564. configurable: true
  47565. });
  47566. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  47567. /**
  47568. * returning the list of animatables controlled by this animation group.
  47569. */
  47570. get: function () {
  47571. return this._animatables;
  47572. },
  47573. enumerable: true,
  47574. configurable: true
  47575. });
  47576. /**
  47577. * Add an animation (with its target) in the group
  47578. * @param animation defines the animation we want to add
  47579. * @param target defines the target of the animation
  47580. * @returns the {BABYLON.TargetedAnimation} object
  47581. */
  47582. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  47583. var targetedAnimation = {
  47584. animation: animation,
  47585. target: target
  47586. };
  47587. var keys = animation.getKeys();
  47588. if (this._from > keys[0].frame) {
  47589. this._from = keys[0].frame;
  47590. }
  47591. if (this._to < keys[keys.length - 1].frame) {
  47592. this._to = keys[keys.length - 1].frame;
  47593. }
  47594. this._targetedAnimations.push(targetedAnimation);
  47595. return targetedAnimation;
  47596. };
  47597. /**
  47598. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  47599. * It can add constant keys at begin or end
  47600. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smallest begin frame of all animations
  47601. * @param endFrame defines the new end frame for all animations. It can't be smaller than the largest end frame of all animations
  47602. */
  47603. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  47604. if (beginFrame === void 0) { beginFrame = -Number.MAX_VALUE; }
  47605. if (endFrame === void 0) { endFrame = Number.MAX_VALUE; }
  47606. beginFrame = Math.max(beginFrame, this._from);
  47607. endFrame = Math.min(endFrame, this._to);
  47608. for (var index = 0; index < this._targetedAnimations.length; index++) {
  47609. var targetedAnimation = this._targetedAnimations[index];
  47610. var keys = targetedAnimation.animation.getKeys();
  47611. var startKey = keys[0];
  47612. var endKey = keys[keys.length - 1];
  47613. if (startKey.frame > beginFrame) {
  47614. var newKey = {
  47615. frame: beginFrame,
  47616. value: startKey.value,
  47617. inTangent: startKey.inTangent,
  47618. outTangent: startKey.outTangent,
  47619. interpolation: startKey.interpolation
  47620. };
  47621. keys.splice(0, 0, newKey);
  47622. }
  47623. if (endKey.frame < endFrame) {
  47624. var newKey = {
  47625. frame: endFrame,
  47626. value: endKey.value,
  47627. inTangent: endKey.outTangent,
  47628. outTangent: endKey.outTangent,
  47629. interpolation: endKey.interpolation
  47630. };
  47631. keys.push(newKey);
  47632. }
  47633. }
  47634. return this;
  47635. };
  47636. /**
  47637. * Start all animations on given targets
  47638. * @param loop defines if animations must loop
  47639. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  47640. * @param from defines the from key (optional)
  47641. * @param to defines the to key (optional)
  47642. * @returns the current animation group
  47643. */
  47644. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  47645. var _this = this;
  47646. if (loop === void 0) { loop = false; }
  47647. if (speedRatio === void 0) { speedRatio = 1; }
  47648. if (this._isStarted || this._targetedAnimations.length === 0) {
  47649. return this;
  47650. }
  47651. var _loop_1 = function () {
  47652. var targetedAnimation = this_1._targetedAnimations[index];
  47653. if (!targetedAnimation.target.animations) {
  47654. targetedAnimation.target.animations = [];
  47655. }
  47656. if (targetedAnimation.target.animations.indexOf(targetedAnimation.animation) === -1) {
  47657. targetedAnimation.target.animations.push(targetedAnimation.animation);
  47658. }
  47659. 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 () {
  47660. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  47661. }));
  47662. };
  47663. var this_1 = this;
  47664. for (var index = 0; index < this._targetedAnimations.length; index++) {
  47665. _loop_1();
  47666. }
  47667. this._speedRatio = speedRatio;
  47668. this._isStarted = true;
  47669. return this;
  47670. };
  47671. /**
  47672. * Pause all animations
  47673. */
  47674. AnimationGroup.prototype.pause = function () {
  47675. if (!this._isStarted) {
  47676. return this;
  47677. }
  47678. for (var index = 0; index < this._animatables.length; index++) {
  47679. var animatable = this._animatables[index];
  47680. animatable.pause();
  47681. }
  47682. return this;
  47683. };
  47684. /**
  47685. * Play all animations to initial state
  47686. * This function will start() the animations if they were not started or will restart() them if they were paused
  47687. * @param loop defines if animations must loop
  47688. */
  47689. AnimationGroup.prototype.play = function (loop) {
  47690. if (this.isStarted) {
  47691. if (loop !== undefined) {
  47692. for (var index = 0; index < this._animatables.length; index++) {
  47693. var animatable = this._animatables[index];
  47694. animatable.loopAnimation = loop;
  47695. }
  47696. }
  47697. this.restart();
  47698. }
  47699. else {
  47700. this.start(loop, this._speedRatio);
  47701. }
  47702. return this;
  47703. };
  47704. /**
  47705. * Reset all animations to initial state
  47706. */
  47707. AnimationGroup.prototype.reset = function () {
  47708. if (!this._isStarted) {
  47709. return this;
  47710. }
  47711. for (var index = 0; index < this._animatables.length; index++) {
  47712. var animatable = this._animatables[index];
  47713. animatable.reset();
  47714. }
  47715. return this;
  47716. };
  47717. /**
  47718. * Restart animations from key 0
  47719. */
  47720. AnimationGroup.prototype.restart = function () {
  47721. if (!this._isStarted) {
  47722. return this;
  47723. }
  47724. for (var index = 0; index < this._animatables.length; index++) {
  47725. var animatable = this._animatables[index];
  47726. animatable.restart();
  47727. }
  47728. return this;
  47729. };
  47730. /**
  47731. * Stop all animations
  47732. */
  47733. AnimationGroup.prototype.stop = function () {
  47734. if (!this._isStarted) {
  47735. return this;
  47736. }
  47737. for (var index = 0; index < this._animatables.length; index++) {
  47738. var animatable = this._animatables[index];
  47739. animatable.stop();
  47740. }
  47741. this._isStarted = false;
  47742. return this;
  47743. };
  47744. /**
  47745. * Goes to a specific frame in this animation group
  47746. *
  47747. * @param frame the frame number to go to
  47748. * @return the animationGroup
  47749. */
  47750. AnimationGroup.prototype.goToFrame = function (frame) {
  47751. if (!this._isStarted) {
  47752. return this;
  47753. }
  47754. for (var index = 0; index < this._animatables.length; index++) {
  47755. var animatable = this._animatables[index];
  47756. animatable.goToFrame(frame);
  47757. }
  47758. return this;
  47759. };
  47760. /**
  47761. * Dispose all associated resources
  47762. */
  47763. AnimationGroup.prototype.dispose = function () {
  47764. this._targetedAnimations = [];
  47765. this._animatables = [];
  47766. var index = this._scene.animationGroups.indexOf(this);
  47767. if (index > -1) {
  47768. this._scene.animationGroups.splice(index, 1);
  47769. }
  47770. };
  47771. return AnimationGroup;
  47772. }());
  47773. BABYLON.AnimationGroup = AnimationGroup;
  47774. })(BABYLON || (BABYLON = {}));
  47775. //# sourceMappingURL=babylon.animationGroup.js.map
  47776. "use strict";
  47777. var BABYLON;
  47778. (function (BABYLON) {
  47779. var RuntimeAnimation = /** @class */ (function () {
  47780. /**
  47781. * Create a new RuntimeAnimation object
  47782. * @param target defines the target of the animation
  47783. * @param animation defines the source {BABYLON.Animation} object
  47784. * @param scene defines the hosting scene
  47785. * @param host defines the initiating Animatable
  47786. */
  47787. function RuntimeAnimation(target, animation, scene, host) {
  47788. this._currentFrame = 0;
  47789. this._offsetsCache = {};
  47790. this._highLimitsCache = {};
  47791. this._stopped = false;
  47792. this._blendingFactor = 0;
  47793. this._targetPath = "";
  47794. this._weight = 1.0;
  47795. this._ratioOffset = 0;
  47796. this._previousDelay = 0;
  47797. this._previousRatio = 0;
  47798. this._animation = animation;
  47799. this._target = target;
  47800. this._scene = scene;
  47801. this._host = host;
  47802. animation._runtimeAnimations.push(this);
  47803. }
  47804. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  47805. /**
  47806. * Gets the current frame
  47807. */
  47808. get: function () {
  47809. return this._currentFrame;
  47810. },
  47811. enumerable: true,
  47812. configurable: true
  47813. });
  47814. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  47815. /**
  47816. * Gets the weight of the runtime animation
  47817. */
  47818. get: function () {
  47819. return this._weight;
  47820. },
  47821. enumerable: true,
  47822. configurable: true
  47823. });
  47824. Object.defineProperty(RuntimeAnimation.prototype, "originalValue", {
  47825. /**
  47826. * Gets the original value of the runtime animation
  47827. */
  47828. get: function () {
  47829. return this._originalValue;
  47830. },
  47831. enumerable: true,
  47832. configurable: true
  47833. });
  47834. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  47835. /**
  47836. * Gets the current value of the runtime animation
  47837. */
  47838. get: function () {
  47839. return this._currentValue;
  47840. },
  47841. enumerable: true,
  47842. configurable: true
  47843. });
  47844. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  47845. /**
  47846. * Gets the path where to store the animated value in the target
  47847. */
  47848. get: function () {
  47849. return this._targetPath;
  47850. },
  47851. enumerable: true,
  47852. configurable: true
  47853. });
  47854. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  47855. /**
  47856. * Gets the actual target of the runtime animation
  47857. */
  47858. get: function () {
  47859. return this._activeTarget;
  47860. },
  47861. enumerable: true,
  47862. configurable: true
  47863. });
  47864. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  47865. get: function () {
  47866. return this._animation;
  47867. },
  47868. enumerable: true,
  47869. configurable: true
  47870. });
  47871. RuntimeAnimation.prototype.reset = function () {
  47872. this._offsetsCache = {};
  47873. this._highLimitsCache = {};
  47874. this._currentFrame = 0;
  47875. this._blendingFactor = 0;
  47876. this._originalValue = null;
  47877. };
  47878. RuntimeAnimation.prototype.isStopped = function () {
  47879. return this._stopped;
  47880. };
  47881. RuntimeAnimation.prototype.dispose = function () {
  47882. var index = this._animation.runtimeAnimations.indexOf(this);
  47883. if (index > -1) {
  47884. this._animation.runtimeAnimations.splice(index, 1);
  47885. }
  47886. };
  47887. RuntimeAnimation.prototype._getKeyValue = function (value) {
  47888. if (typeof value === "function") {
  47889. return value();
  47890. }
  47891. return value;
  47892. };
  47893. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  47894. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  47895. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  47896. }
  47897. this._currentFrame = currentFrame;
  47898. var keys = this._animation.getKeys();
  47899. // Try to get a hash to find the right key
  47900. 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));
  47901. if (keys[startKeyIndex].frame >= currentFrame) {
  47902. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  47903. startKeyIndex--;
  47904. }
  47905. }
  47906. for (var key = startKeyIndex; key < keys.length; key++) {
  47907. var endKey = keys[key + 1];
  47908. if (endKey.frame >= currentFrame) {
  47909. var startKey = keys[key];
  47910. var startValue = this._getKeyValue(startKey.value);
  47911. if (startKey.interpolation === BABYLON.AnimationKeyInterpolation.STEP) {
  47912. return startValue;
  47913. }
  47914. var endValue = this._getKeyValue(endKey.value);
  47915. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  47916. var frameDelta = endKey.frame - startKey.frame;
  47917. // gradient : percent of currentFrame between the frame inf and the frame sup
  47918. var gradient = (currentFrame - startKey.frame) / frameDelta;
  47919. // check for easingFunction and correction of gradient
  47920. var easingFunction = this._animation.getEasingFunction();
  47921. if (easingFunction != null) {
  47922. gradient = easingFunction.ease(gradient);
  47923. }
  47924. switch (this._animation.dataType) {
  47925. // Float
  47926. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  47927. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  47928. switch (loopMode) {
  47929. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47930. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47931. return floatValue;
  47932. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47933. return offsetValue * repeatCount + floatValue;
  47934. }
  47935. break;
  47936. // Quaternion
  47937. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  47938. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  47939. switch (loopMode) {
  47940. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47941. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47942. return quatValue;
  47943. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47944. return quatValue.add(offsetValue.scale(repeatCount));
  47945. }
  47946. return quatValue;
  47947. // Vector3
  47948. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  47949. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  47950. switch (loopMode) {
  47951. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47952. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47953. return vec3Value;
  47954. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47955. return vec3Value.add(offsetValue.scale(repeatCount));
  47956. }
  47957. // Vector2
  47958. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  47959. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  47960. switch (loopMode) {
  47961. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47962. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47963. return vec2Value;
  47964. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47965. return vec2Value.add(offsetValue.scale(repeatCount));
  47966. }
  47967. // Size
  47968. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  47969. switch (loopMode) {
  47970. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47971. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47972. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  47973. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47974. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  47975. }
  47976. // Color3
  47977. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  47978. switch (loopMode) {
  47979. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47980. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47981. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  47982. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47983. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  47984. }
  47985. // Matrix
  47986. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  47987. switch (loopMode) {
  47988. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47989. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47990. if (BABYLON.Animation.AllowMatricesInterpolation) {
  47991. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  47992. }
  47993. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47994. return startValue;
  47995. }
  47996. default:
  47997. break;
  47998. }
  47999. break;
  48000. }
  48001. }
  48002. return this._getKeyValue(keys[keys.length - 1].value);
  48003. };
  48004. /**
  48005. * Affect the interpolated value to the target
  48006. * @param currentValue defines the value computed by the animation
  48007. * @param weight defines the weight to apply to this value
  48008. */
  48009. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  48010. if (weight === void 0) { weight = 1.0; }
  48011. // Set value
  48012. var path;
  48013. var destination;
  48014. var targetPropertyPath = this._animation.targetPropertyPath;
  48015. if (targetPropertyPath.length > 1) {
  48016. var property = this._target[targetPropertyPath[0]];
  48017. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  48018. property = property[targetPropertyPath[index]];
  48019. }
  48020. path = targetPropertyPath[targetPropertyPath.length - 1];
  48021. destination = property;
  48022. }
  48023. else {
  48024. path = targetPropertyPath[0];
  48025. destination = this._target;
  48026. }
  48027. this._targetPath = path;
  48028. this._activeTarget = destination;
  48029. this._weight = weight;
  48030. // Blending
  48031. var enableBlending = this._target && this._target.animationPropertiesOverride ? this._target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  48032. var blendingSpeed = this._target && this._target.animationPropertiesOverride ? this._target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  48033. if (enableBlending && this._blendingFactor <= 1.0) {
  48034. if (!this._originalBlendValue) {
  48035. var originalValue = destination[path];
  48036. if (originalValue.clone) {
  48037. this._originalBlendValue = originalValue.clone();
  48038. }
  48039. else {
  48040. this._originalBlendValue = originalValue;
  48041. }
  48042. }
  48043. }
  48044. if (weight !== -1.0) {
  48045. if (!this._originalValue) {
  48046. var originalValue = void 0;
  48047. if (destination.getRestPose) {
  48048. originalValue = destination.getRestPose();
  48049. }
  48050. else {
  48051. originalValue = destination[path];
  48052. }
  48053. if (originalValue.clone) {
  48054. this._originalValue = originalValue.clone();
  48055. }
  48056. else {
  48057. this._originalValue = originalValue;
  48058. }
  48059. }
  48060. }
  48061. if (enableBlending && this._blendingFactor <= 1.0) {
  48062. if (this._originalBlendValue.prototype) {
  48063. if (this._originalBlendValue.prototype.Lerp) {
  48064. this._currentValue = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  48065. }
  48066. else {
  48067. this._currentValue = currentValue;
  48068. }
  48069. }
  48070. else if (this._originalBlendValue.m) {
  48071. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  48072. }
  48073. else {
  48074. this._currentValue = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  48075. }
  48076. this._blendingFactor += blendingSpeed;
  48077. }
  48078. else {
  48079. this._currentValue = currentValue;
  48080. }
  48081. if (weight !== -1.0) {
  48082. this._scene._registerTargetForLateAnimationBinding(this);
  48083. }
  48084. else {
  48085. destination[path] = this._currentValue;
  48086. }
  48087. if (this._target.markAsDirty) {
  48088. this._target.markAsDirty(this._animation.targetProperty);
  48089. }
  48090. };
  48091. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  48092. if (this._target && this._target.animationPropertiesOverride) {
  48093. return this._target.animationPropertiesOverride.loopMode;
  48094. }
  48095. return this._animation.loopMode;
  48096. };
  48097. /**
  48098. * Move the current animation to a given frame
  48099. * @param frame defines the frame to move to
  48100. */
  48101. RuntimeAnimation.prototype.goToFrame = function (frame) {
  48102. var keys = this._animation.getKeys();
  48103. if (frame < keys[0].frame) {
  48104. frame = keys[0].frame;
  48105. }
  48106. else if (frame > keys[keys.length - 1].frame) {
  48107. frame = keys[keys.length - 1].frame;
  48108. }
  48109. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  48110. this.setValue(currentValue, -1);
  48111. };
  48112. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  48113. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  48114. this._ratioOffset = this._previousRatio - newRatio;
  48115. };
  48116. /**
  48117. * Execute the current animation
  48118. * @param delay defines the delay to add to the current frame
  48119. * @param from defines the lower bound of the animation range
  48120. * @param to defines the upper bound of the animation range
  48121. * @param loop defines if the current animation must loop
  48122. * @param speedRatio defines the current speed ratio
  48123. * @param weight defines the weight of the animation (default is -1 so no weight)
  48124. * @returns a boolean indicating if the animation has ended
  48125. */
  48126. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  48127. if (weight === void 0) { weight = -1.0; }
  48128. var targetPropertyPath = this._animation.targetPropertyPath;
  48129. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  48130. this._stopped = true;
  48131. return false;
  48132. }
  48133. var returnValue = true;
  48134. var keys = this._animation.getKeys();
  48135. // Adding a start key at frame 0 if missing
  48136. if (keys[0].frame !== 0) {
  48137. var newKey = { frame: 0, value: keys[0].value };
  48138. keys.splice(0, 0, newKey);
  48139. }
  48140. // Check limits
  48141. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  48142. from = keys[0].frame;
  48143. }
  48144. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  48145. to = keys[keys.length - 1].frame;
  48146. }
  48147. //to and from cannot be the same key
  48148. if (from === to) {
  48149. if (from > keys[0].frame) {
  48150. from--;
  48151. }
  48152. else if (to < keys[keys.length - 1].frame) {
  48153. to++;
  48154. }
  48155. }
  48156. // Compute ratio
  48157. var range = to - from;
  48158. var offsetValue;
  48159. // ratio represents the frame delta between from and to
  48160. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  48161. var highLimitValue = 0;
  48162. this._previousDelay = delay;
  48163. this._previousRatio = ratio;
  48164. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  48165. returnValue = false;
  48166. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  48167. }
  48168. else {
  48169. // Get max value if required
  48170. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  48171. var keyOffset = to.toString() + from.toString();
  48172. if (!this._offsetsCache[keyOffset]) {
  48173. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  48174. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  48175. switch (this._animation.dataType) {
  48176. // Float
  48177. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  48178. this._offsetsCache[keyOffset] = toValue - fromValue;
  48179. break;
  48180. // Quaternion
  48181. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  48182. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  48183. break;
  48184. // Vector3
  48185. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  48186. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  48187. // Vector2
  48188. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  48189. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  48190. // Size
  48191. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  48192. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  48193. // Color3
  48194. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  48195. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  48196. default:
  48197. break;
  48198. }
  48199. this._highLimitsCache[keyOffset] = toValue;
  48200. }
  48201. highLimitValue = this._highLimitsCache[keyOffset];
  48202. offsetValue = this._offsetsCache[keyOffset];
  48203. }
  48204. }
  48205. if (offsetValue === undefined) {
  48206. switch (this._animation.dataType) {
  48207. // Float
  48208. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  48209. offsetValue = 0;
  48210. break;
  48211. // Quaternion
  48212. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  48213. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  48214. break;
  48215. // Vector3
  48216. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  48217. offsetValue = BABYLON.Vector3.Zero();
  48218. break;
  48219. // Vector2
  48220. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  48221. offsetValue = BABYLON.Vector2.Zero();
  48222. break;
  48223. // Size
  48224. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  48225. offsetValue = BABYLON.Size.Zero();
  48226. break;
  48227. // Color3
  48228. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  48229. offsetValue = BABYLON.Color3.Black();
  48230. }
  48231. }
  48232. // Compute value
  48233. var repeatCount = (ratio / range) >> 0;
  48234. var currentFrame = returnValue ? from + ratio % range : to;
  48235. // Need to normalize?
  48236. if (this._host && this._host.syncRoot) {
  48237. var syncRoot = this._host.syncRoot;
  48238. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  48239. currentFrame = from + (to - from) * hostNormalizedFrame;
  48240. }
  48241. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  48242. // Set value
  48243. this.setValue(currentValue, weight);
  48244. // Check events
  48245. var events = this._animation.getEvents();
  48246. for (var index = 0; index < events.length; index++) {
  48247. // Make sure current frame has passed event frame and that event frame is within the current range
  48248. // Also, handle both forward and reverse animations
  48249. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  48250. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  48251. var event = events[index];
  48252. if (!event.isDone) {
  48253. // If event should be done only once, remove it.
  48254. if (event.onlyOnce) {
  48255. events.splice(index, 1);
  48256. index--;
  48257. }
  48258. event.isDone = true;
  48259. event.action();
  48260. } // Don't do anything if the event has already be done.
  48261. }
  48262. else if (events[index].isDone && !events[index].onlyOnce) {
  48263. // reset event, the animation is looping
  48264. events[index].isDone = false;
  48265. }
  48266. }
  48267. if (!returnValue) {
  48268. this._stopped = true;
  48269. }
  48270. return returnValue;
  48271. };
  48272. return RuntimeAnimation;
  48273. }());
  48274. BABYLON.RuntimeAnimation = RuntimeAnimation;
  48275. })(BABYLON || (BABYLON = {}));
  48276. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  48277. "use strict";
  48278. var BABYLON;
  48279. (function (BABYLON) {
  48280. var Animatable = /** @class */ (function () {
  48281. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  48282. if (fromFrame === void 0) { fromFrame = 0; }
  48283. if (toFrame === void 0) { toFrame = 100; }
  48284. if (loopAnimation === void 0) { loopAnimation = false; }
  48285. if (speedRatio === void 0) { speedRatio = 1.0; }
  48286. this.target = target;
  48287. this.fromFrame = fromFrame;
  48288. this.toFrame = toFrame;
  48289. this.loopAnimation = loopAnimation;
  48290. this.onAnimationEnd = onAnimationEnd;
  48291. this._localDelayOffset = null;
  48292. this._pausedDelay = null;
  48293. this._runtimeAnimations = new Array();
  48294. this._paused = false;
  48295. this._speedRatio = 1;
  48296. this._weight = -1.0;
  48297. this.animationStarted = false;
  48298. if (animations) {
  48299. this.appendAnimations(target, animations);
  48300. }
  48301. this._speedRatio = speedRatio;
  48302. this._scene = scene;
  48303. scene._activeAnimatables.push(this);
  48304. }
  48305. Object.defineProperty(Animatable.prototype, "syncRoot", {
  48306. /**
  48307. * Gets the root Animatable used to synchronize and normalize animations
  48308. */
  48309. get: function () {
  48310. return this._syncRoot;
  48311. },
  48312. enumerable: true,
  48313. configurable: true
  48314. });
  48315. Object.defineProperty(Animatable.prototype, "masterFrame", {
  48316. /**
  48317. * Gets the current frame of the first RuntimeAnimation
  48318. * Used to synchronize Animatables
  48319. */
  48320. get: function () {
  48321. if (this._runtimeAnimations.length === 0) {
  48322. return 0;
  48323. }
  48324. return this._runtimeAnimations[0].currentFrame;
  48325. },
  48326. enumerable: true,
  48327. configurable: true
  48328. });
  48329. Object.defineProperty(Animatable.prototype, "weight", {
  48330. /**
  48331. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  48332. */
  48333. get: function () {
  48334. return this._weight;
  48335. },
  48336. set: function (value) {
  48337. if (value === -1) {
  48338. this._weight = -1;
  48339. return;
  48340. }
  48341. // Else weight must be in [0, 1] range
  48342. this._weight = Math.min(Math.max(value, 0), 1.0);
  48343. },
  48344. enumerable: true,
  48345. configurable: true
  48346. });
  48347. Object.defineProperty(Animatable.prototype, "speedRatio", {
  48348. /**
  48349. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  48350. */
  48351. get: function () {
  48352. return this._speedRatio;
  48353. },
  48354. set: function (value) {
  48355. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  48356. var animation = this._runtimeAnimations[index];
  48357. animation._prepareForSpeedRatioChange(value);
  48358. }
  48359. this._speedRatio = value;
  48360. },
  48361. enumerable: true,
  48362. configurable: true
  48363. });
  48364. // Methods
  48365. /**
  48366. * Synchronize and normalize current Animatable with a source Animatable.
  48367. * This is useful when using animation weights and when animations are not of the same length
  48368. * @param root defines the root Animatable to synchronize with
  48369. * @returns the current Animatable
  48370. */
  48371. Animatable.prototype.syncWith = function (root) {
  48372. this._syncRoot = root;
  48373. if (root) {
  48374. // Make sure this animatable will animate after the root
  48375. var index = this._scene._activeAnimatables.indexOf(this);
  48376. if (index > -1) {
  48377. this._scene._activeAnimatables.splice(index, 1);
  48378. this._scene._activeAnimatables.push(this);
  48379. }
  48380. }
  48381. return this;
  48382. };
  48383. Animatable.prototype.getAnimations = function () {
  48384. return this._runtimeAnimations;
  48385. };
  48386. Animatable.prototype.appendAnimations = function (target, animations) {
  48387. for (var index = 0; index < animations.length; index++) {
  48388. var animation = animations[index];
  48389. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  48390. }
  48391. };
  48392. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  48393. var runtimeAnimations = this._runtimeAnimations;
  48394. for (var index = 0; index < runtimeAnimations.length; index++) {
  48395. if (runtimeAnimations[index].animation.targetProperty === property) {
  48396. return runtimeAnimations[index].animation;
  48397. }
  48398. }
  48399. return null;
  48400. };
  48401. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  48402. var runtimeAnimations = this._runtimeAnimations;
  48403. for (var index = 0; index < runtimeAnimations.length; index++) {
  48404. if (runtimeAnimations[index].animation.targetProperty === property) {
  48405. return runtimeAnimations[index];
  48406. }
  48407. }
  48408. return null;
  48409. };
  48410. Animatable.prototype.reset = function () {
  48411. var runtimeAnimations = this._runtimeAnimations;
  48412. for (var index = 0; index < runtimeAnimations.length; index++) {
  48413. runtimeAnimations[index].reset();
  48414. }
  48415. // Reset to original value
  48416. for (index = 0; index < runtimeAnimations.length; index++) {
  48417. var animation = runtimeAnimations[index];
  48418. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  48419. }
  48420. this._localDelayOffset = null;
  48421. this._pausedDelay = null;
  48422. };
  48423. Animatable.prototype.enableBlending = function (blendingSpeed) {
  48424. var runtimeAnimations = this._runtimeAnimations;
  48425. for (var index = 0; index < runtimeAnimations.length; index++) {
  48426. runtimeAnimations[index].animation.enableBlending = true;
  48427. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  48428. }
  48429. };
  48430. Animatable.prototype.disableBlending = function () {
  48431. var runtimeAnimations = this._runtimeAnimations;
  48432. for (var index = 0; index < runtimeAnimations.length; index++) {
  48433. runtimeAnimations[index].animation.enableBlending = false;
  48434. }
  48435. };
  48436. Animatable.prototype.goToFrame = function (frame) {
  48437. var runtimeAnimations = this._runtimeAnimations;
  48438. if (runtimeAnimations[0]) {
  48439. var fps = runtimeAnimations[0].animation.framePerSecond;
  48440. var currentFrame = runtimeAnimations[0].currentFrame;
  48441. var adjustTime = frame - currentFrame;
  48442. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  48443. if (this._localDelayOffset === null) {
  48444. this._localDelayOffset = 0;
  48445. }
  48446. this._localDelayOffset -= delay;
  48447. }
  48448. for (var index = 0; index < runtimeAnimations.length; index++) {
  48449. runtimeAnimations[index].goToFrame(frame);
  48450. }
  48451. };
  48452. Animatable.prototype.pause = function () {
  48453. if (this._paused) {
  48454. return;
  48455. }
  48456. this._paused = true;
  48457. };
  48458. Animatable.prototype.restart = function () {
  48459. this._paused = false;
  48460. };
  48461. Animatable.prototype.stop = function (animationName) {
  48462. if (animationName) {
  48463. var idx = this._scene._activeAnimatables.indexOf(this);
  48464. if (idx > -1) {
  48465. var runtimeAnimations = this._runtimeAnimations;
  48466. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  48467. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  48468. continue;
  48469. }
  48470. runtimeAnimations[index].dispose();
  48471. runtimeAnimations.splice(index, 1);
  48472. }
  48473. if (runtimeAnimations.length == 0) {
  48474. this._scene._activeAnimatables.splice(idx, 1);
  48475. if (this.onAnimationEnd) {
  48476. this.onAnimationEnd();
  48477. }
  48478. }
  48479. }
  48480. }
  48481. else {
  48482. var index = this._scene._activeAnimatables.indexOf(this);
  48483. if (index > -1) {
  48484. this._scene._activeAnimatables.splice(index, 1);
  48485. var runtimeAnimations = this._runtimeAnimations;
  48486. for (var index = 0; index < runtimeAnimations.length; index++) {
  48487. runtimeAnimations[index].dispose();
  48488. }
  48489. if (this.onAnimationEnd) {
  48490. this.onAnimationEnd();
  48491. }
  48492. }
  48493. }
  48494. };
  48495. Animatable.prototype._animate = function (delay) {
  48496. if (this._paused) {
  48497. this.animationStarted = false;
  48498. if (this._pausedDelay === null) {
  48499. this._pausedDelay = delay;
  48500. }
  48501. return true;
  48502. }
  48503. if (this._localDelayOffset === null) {
  48504. this._localDelayOffset = delay;
  48505. this._pausedDelay = null;
  48506. }
  48507. else if (this._pausedDelay !== null) {
  48508. this._localDelayOffset += delay - this._pausedDelay;
  48509. this._pausedDelay = null;
  48510. }
  48511. if (this._weight === 0) {
  48512. return true;
  48513. }
  48514. // Animating
  48515. var running = false;
  48516. var runtimeAnimations = this._runtimeAnimations;
  48517. var index;
  48518. for (index = 0; index < runtimeAnimations.length; index++) {
  48519. var animation = runtimeAnimations[index];
  48520. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  48521. running = running || isRunning;
  48522. }
  48523. this.animationStarted = running;
  48524. if (!running) {
  48525. // Remove from active animatables
  48526. index = this._scene._activeAnimatables.indexOf(this);
  48527. this._scene._activeAnimatables.splice(index, 1);
  48528. // Dispose all runtime animations
  48529. for (index = 0; index < runtimeAnimations.length; index++) {
  48530. runtimeAnimations[index].dispose();
  48531. }
  48532. }
  48533. if (!running && this.onAnimationEnd) {
  48534. this.onAnimationEnd();
  48535. this.onAnimationEnd = null;
  48536. }
  48537. return running;
  48538. };
  48539. return Animatable;
  48540. }());
  48541. BABYLON.Animatable = Animatable;
  48542. })(BABYLON || (BABYLON = {}));
  48543. //# sourceMappingURL=babylon.animatable.js.map
  48544. "use strict";
  48545. var BABYLON;
  48546. (function (BABYLON) {
  48547. var EasingFunction = /** @class */ (function () {
  48548. function EasingFunction() {
  48549. // Properties
  48550. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  48551. }
  48552. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  48553. get: function () {
  48554. return EasingFunction._EASINGMODE_EASEIN;
  48555. },
  48556. enumerable: true,
  48557. configurable: true
  48558. });
  48559. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  48560. get: function () {
  48561. return EasingFunction._EASINGMODE_EASEOUT;
  48562. },
  48563. enumerable: true,
  48564. configurable: true
  48565. });
  48566. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  48567. get: function () {
  48568. return EasingFunction._EASINGMODE_EASEINOUT;
  48569. },
  48570. enumerable: true,
  48571. configurable: true
  48572. });
  48573. EasingFunction.prototype.setEasingMode = function (easingMode) {
  48574. var n = Math.min(Math.max(easingMode, 0), 2);
  48575. this._easingMode = n;
  48576. };
  48577. EasingFunction.prototype.getEasingMode = function () {
  48578. return this._easingMode;
  48579. };
  48580. EasingFunction.prototype.easeInCore = function (gradient) {
  48581. throw new Error('You must implement this method');
  48582. };
  48583. EasingFunction.prototype.ease = function (gradient) {
  48584. switch (this._easingMode) {
  48585. case EasingFunction.EASINGMODE_EASEIN:
  48586. return this.easeInCore(gradient);
  48587. case EasingFunction.EASINGMODE_EASEOUT:
  48588. return (1 - this.easeInCore(1 - gradient));
  48589. }
  48590. if (gradient >= 0.5) {
  48591. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  48592. }
  48593. return (this.easeInCore(gradient * 2) * 0.5);
  48594. };
  48595. //Statics
  48596. EasingFunction._EASINGMODE_EASEIN = 0;
  48597. EasingFunction._EASINGMODE_EASEOUT = 1;
  48598. EasingFunction._EASINGMODE_EASEINOUT = 2;
  48599. return EasingFunction;
  48600. }());
  48601. BABYLON.EasingFunction = EasingFunction;
  48602. var CircleEase = /** @class */ (function (_super) {
  48603. __extends(CircleEase, _super);
  48604. function CircleEase() {
  48605. return _super !== null && _super.apply(this, arguments) || this;
  48606. }
  48607. CircleEase.prototype.easeInCore = function (gradient) {
  48608. gradient = Math.max(0, Math.min(1, gradient));
  48609. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  48610. };
  48611. return CircleEase;
  48612. }(EasingFunction));
  48613. BABYLON.CircleEase = CircleEase;
  48614. var BackEase = /** @class */ (function (_super) {
  48615. __extends(BackEase, _super);
  48616. function BackEase(amplitude) {
  48617. if (amplitude === void 0) { amplitude = 1; }
  48618. var _this = _super.call(this) || this;
  48619. _this.amplitude = amplitude;
  48620. return _this;
  48621. }
  48622. BackEase.prototype.easeInCore = function (gradient) {
  48623. var num = Math.max(0, this.amplitude);
  48624. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  48625. };
  48626. return BackEase;
  48627. }(EasingFunction));
  48628. BABYLON.BackEase = BackEase;
  48629. var BounceEase = /** @class */ (function (_super) {
  48630. __extends(BounceEase, _super);
  48631. function BounceEase(bounces, bounciness) {
  48632. if (bounces === void 0) { bounces = 3; }
  48633. if (bounciness === void 0) { bounciness = 2; }
  48634. var _this = _super.call(this) || this;
  48635. _this.bounces = bounces;
  48636. _this.bounciness = bounciness;
  48637. return _this;
  48638. }
  48639. BounceEase.prototype.easeInCore = function (gradient) {
  48640. var y = Math.max(0.0, this.bounces);
  48641. var bounciness = this.bounciness;
  48642. if (bounciness <= 1.0) {
  48643. bounciness = 1.001;
  48644. }
  48645. var num9 = Math.pow(bounciness, y);
  48646. var num5 = 1.0 - bounciness;
  48647. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  48648. var num15 = gradient * num4;
  48649. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  48650. var num3 = Math.floor(num65);
  48651. var num13 = num3 + 1.0;
  48652. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  48653. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  48654. var num7 = (num8 + num12) * 0.5;
  48655. var num6 = gradient - num7;
  48656. var num2 = num7 - num8;
  48657. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  48658. };
  48659. return BounceEase;
  48660. }(EasingFunction));
  48661. BABYLON.BounceEase = BounceEase;
  48662. var CubicEase = /** @class */ (function (_super) {
  48663. __extends(CubicEase, _super);
  48664. function CubicEase() {
  48665. return _super !== null && _super.apply(this, arguments) || this;
  48666. }
  48667. CubicEase.prototype.easeInCore = function (gradient) {
  48668. return (gradient * gradient * gradient);
  48669. };
  48670. return CubicEase;
  48671. }(EasingFunction));
  48672. BABYLON.CubicEase = CubicEase;
  48673. var ElasticEase = /** @class */ (function (_super) {
  48674. __extends(ElasticEase, _super);
  48675. function ElasticEase(oscillations, springiness) {
  48676. if (oscillations === void 0) { oscillations = 3; }
  48677. if (springiness === void 0) { springiness = 3; }
  48678. var _this = _super.call(this) || this;
  48679. _this.oscillations = oscillations;
  48680. _this.springiness = springiness;
  48681. return _this;
  48682. }
  48683. ElasticEase.prototype.easeInCore = function (gradient) {
  48684. var num2;
  48685. var num3 = Math.max(0.0, this.oscillations);
  48686. var num = Math.max(0.0, this.springiness);
  48687. if (num == 0) {
  48688. num2 = gradient;
  48689. }
  48690. else {
  48691. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  48692. }
  48693. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  48694. };
  48695. return ElasticEase;
  48696. }(EasingFunction));
  48697. BABYLON.ElasticEase = ElasticEase;
  48698. var ExponentialEase = /** @class */ (function (_super) {
  48699. __extends(ExponentialEase, _super);
  48700. function ExponentialEase(exponent) {
  48701. if (exponent === void 0) { exponent = 2; }
  48702. var _this = _super.call(this) || this;
  48703. _this.exponent = exponent;
  48704. return _this;
  48705. }
  48706. ExponentialEase.prototype.easeInCore = function (gradient) {
  48707. if (this.exponent <= 0) {
  48708. return gradient;
  48709. }
  48710. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  48711. };
  48712. return ExponentialEase;
  48713. }(EasingFunction));
  48714. BABYLON.ExponentialEase = ExponentialEase;
  48715. var PowerEase = /** @class */ (function (_super) {
  48716. __extends(PowerEase, _super);
  48717. function PowerEase(power) {
  48718. if (power === void 0) { power = 2; }
  48719. var _this = _super.call(this) || this;
  48720. _this.power = power;
  48721. return _this;
  48722. }
  48723. PowerEase.prototype.easeInCore = function (gradient) {
  48724. var y = Math.max(0.0, this.power);
  48725. return Math.pow(gradient, y);
  48726. };
  48727. return PowerEase;
  48728. }(EasingFunction));
  48729. BABYLON.PowerEase = PowerEase;
  48730. var QuadraticEase = /** @class */ (function (_super) {
  48731. __extends(QuadraticEase, _super);
  48732. function QuadraticEase() {
  48733. return _super !== null && _super.apply(this, arguments) || this;
  48734. }
  48735. QuadraticEase.prototype.easeInCore = function (gradient) {
  48736. return (gradient * gradient);
  48737. };
  48738. return QuadraticEase;
  48739. }(EasingFunction));
  48740. BABYLON.QuadraticEase = QuadraticEase;
  48741. var QuarticEase = /** @class */ (function (_super) {
  48742. __extends(QuarticEase, _super);
  48743. function QuarticEase() {
  48744. return _super !== null && _super.apply(this, arguments) || this;
  48745. }
  48746. QuarticEase.prototype.easeInCore = function (gradient) {
  48747. return (gradient * gradient * gradient * gradient);
  48748. };
  48749. return QuarticEase;
  48750. }(EasingFunction));
  48751. BABYLON.QuarticEase = QuarticEase;
  48752. var QuinticEase = /** @class */ (function (_super) {
  48753. __extends(QuinticEase, _super);
  48754. function QuinticEase() {
  48755. return _super !== null && _super.apply(this, arguments) || this;
  48756. }
  48757. QuinticEase.prototype.easeInCore = function (gradient) {
  48758. return (gradient * gradient * gradient * gradient * gradient);
  48759. };
  48760. return QuinticEase;
  48761. }(EasingFunction));
  48762. BABYLON.QuinticEase = QuinticEase;
  48763. var SineEase = /** @class */ (function (_super) {
  48764. __extends(SineEase, _super);
  48765. function SineEase() {
  48766. return _super !== null && _super.apply(this, arguments) || this;
  48767. }
  48768. SineEase.prototype.easeInCore = function (gradient) {
  48769. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  48770. };
  48771. return SineEase;
  48772. }(EasingFunction));
  48773. BABYLON.SineEase = SineEase;
  48774. var BezierCurveEase = /** @class */ (function (_super) {
  48775. __extends(BezierCurveEase, _super);
  48776. function BezierCurveEase(x1, y1, x2, y2) {
  48777. if (x1 === void 0) { x1 = 0; }
  48778. if (y1 === void 0) { y1 = 0; }
  48779. if (x2 === void 0) { x2 = 1; }
  48780. if (y2 === void 0) { y2 = 1; }
  48781. var _this = _super.call(this) || this;
  48782. _this.x1 = x1;
  48783. _this.y1 = y1;
  48784. _this.x2 = x2;
  48785. _this.y2 = y2;
  48786. return _this;
  48787. }
  48788. BezierCurveEase.prototype.easeInCore = function (gradient) {
  48789. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  48790. };
  48791. return BezierCurveEase;
  48792. }(EasingFunction));
  48793. BABYLON.BezierCurveEase = BezierCurveEase;
  48794. })(BABYLON || (BABYLON = {}));
  48795. //# sourceMappingURL=babylon.easing.js.map
  48796. "use strict";
  48797. var BABYLON;
  48798. (function (BABYLON) {
  48799. var Condition = /** @class */ (function () {
  48800. function Condition(actionManager) {
  48801. this._actionManager = actionManager;
  48802. }
  48803. Condition.prototype.isValid = function () {
  48804. return true;
  48805. };
  48806. Condition.prototype._getProperty = function (propertyPath) {
  48807. return this._actionManager._getProperty(propertyPath);
  48808. };
  48809. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  48810. return this._actionManager._getEffectiveTarget(target, propertyPath);
  48811. };
  48812. Condition.prototype.serialize = function () {
  48813. };
  48814. Condition.prototype._serialize = function (serializedCondition) {
  48815. return {
  48816. type: 2,
  48817. children: [],
  48818. name: serializedCondition.name,
  48819. properties: serializedCondition.properties
  48820. };
  48821. };
  48822. return Condition;
  48823. }());
  48824. BABYLON.Condition = Condition;
  48825. var ValueCondition = /** @class */ (function (_super) {
  48826. __extends(ValueCondition, _super);
  48827. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  48828. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  48829. var _this = _super.call(this, actionManager) || this;
  48830. _this.propertyPath = propertyPath;
  48831. _this.value = value;
  48832. _this.operator = operator;
  48833. _this._target = target;
  48834. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  48835. _this._property = _this._getProperty(_this.propertyPath);
  48836. return _this;
  48837. }
  48838. Object.defineProperty(ValueCondition, "IsEqual", {
  48839. get: function () {
  48840. return ValueCondition._IsEqual;
  48841. },
  48842. enumerable: true,
  48843. configurable: true
  48844. });
  48845. Object.defineProperty(ValueCondition, "IsDifferent", {
  48846. get: function () {
  48847. return ValueCondition._IsDifferent;
  48848. },
  48849. enumerable: true,
  48850. configurable: true
  48851. });
  48852. Object.defineProperty(ValueCondition, "IsGreater", {
  48853. get: function () {
  48854. return ValueCondition._IsGreater;
  48855. },
  48856. enumerable: true,
  48857. configurable: true
  48858. });
  48859. Object.defineProperty(ValueCondition, "IsLesser", {
  48860. get: function () {
  48861. return ValueCondition._IsLesser;
  48862. },
  48863. enumerable: true,
  48864. configurable: true
  48865. });
  48866. // Methods
  48867. ValueCondition.prototype.isValid = function () {
  48868. switch (this.operator) {
  48869. case ValueCondition.IsGreater:
  48870. return this._effectiveTarget[this._property] > this.value;
  48871. case ValueCondition.IsLesser:
  48872. return this._effectiveTarget[this._property] < this.value;
  48873. case ValueCondition.IsEqual:
  48874. case ValueCondition.IsDifferent:
  48875. var check;
  48876. if (this.value.equals) {
  48877. check = this.value.equals(this._effectiveTarget[this._property]);
  48878. }
  48879. else {
  48880. check = this.value === this._effectiveTarget[this._property];
  48881. }
  48882. return this.operator === ValueCondition.IsEqual ? check : !check;
  48883. }
  48884. return false;
  48885. };
  48886. ValueCondition.prototype.serialize = function () {
  48887. return this._serialize({
  48888. name: "ValueCondition",
  48889. properties: [
  48890. BABYLON.Action._GetTargetProperty(this._target),
  48891. { name: "propertyPath", value: this.propertyPath },
  48892. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  48893. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  48894. ]
  48895. });
  48896. };
  48897. ValueCondition.GetOperatorName = function (operator) {
  48898. switch (operator) {
  48899. case ValueCondition._IsEqual: return "IsEqual";
  48900. case ValueCondition._IsDifferent: return "IsDifferent";
  48901. case ValueCondition._IsGreater: return "IsGreater";
  48902. case ValueCondition._IsLesser: return "IsLesser";
  48903. default: return "";
  48904. }
  48905. };
  48906. // Statics
  48907. ValueCondition._IsEqual = 0;
  48908. ValueCondition._IsDifferent = 1;
  48909. ValueCondition._IsGreater = 2;
  48910. ValueCondition._IsLesser = 3;
  48911. return ValueCondition;
  48912. }(Condition));
  48913. BABYLON.ValueCondition = ValueCondition;
  48914. var PredicateCondition = /** @class */ (function (_super) {
  48915. __extends(PredicateCondition, _super);
  48916. function PredicateCondition(actionManager, predicate) {
  48917. var _this = _super.call(this, actionManager) || this;
  48918. _this.predicate = predicate;
  48919. return _this;
  48920. }
  48921. PredicateCondition.prototype.isValid = function () {
  48922. return this.predicate();
  48923. };
  48924. return PredicateCondition;
  48925. }(Condition));
  48926. BABYLON.PredicateCondition = PredicateCondition;
  48927. var StateCondition = /** @class */ (function (_super) {
  48928. __extends(StateCondition, _super);
  48929. function StateCondition(actionManager, target, value) {
  48930. var _this = _super.call(this, actionManager) || this;
  48931. _this.value = value;
  48932. _this._target = target;
  48933. return _this;
  48934. }
  48935. // Methods
  48936. StateCondition.prototype.isValid = function () {
  48937. return this._target.state === this.value;
  48938. };
  48939. StateCondition.prototype.serialize = function () {
  48940. return this._serialize({
  48941. name: "StateCondition",
  48942. properties: [
  48943. BABYLON.Action._GetTargetProperty(this._target),
  48944. { name: "value", value: this.value }
  48945. ]
  48946. });
  48947. };
  48948. return StateCondition;
  48949. }(Condition));
  48950. BABYLON.StateCondition = StateCondition;
  48951. })(BABYLON || (BABYLON = {}));
  48952. //# sourceMappingURL=babylon.condition.js.map
  48953. "use strict";
  48954. var BABYLON;
  48955. (function (BABYLON) {
  48956. var Action = /** @class */ (function () {
  48957. function Action(triggerOptions, condition) {
  48958. this.triggerOptions = triggerOptions;
  48959. this.onBeforeExecuteObservable = new BABYLON.Observable();
  48960. if (triggerOptions.parameter) {
  48961. this.trigger = triggerOptions.trigger;
  48962. this._triggerParameter = triggerOptions.parameter;
  48963. }
  48964. else {
  48965. this.trigger = triggerOptions;
  48966. }
  48967. this._nextActiveAction = this;
  48968. this._condition = condition;
  48969. }
  48970. // Methods
  48971. Action.prototype._prepare = function () {
  48972. };
  48973. Action.prototype.getTriggerParameter = function () {
  48974. return this._triggerParameter;
  48975. };
  48976. Action.prototype._executeCurrent = function (evt) {
  48977. if (this._nextActiveAction._condition) {
  48978. var condition = this._nextActiveAction._condition;
  48979. var currentRenderId = this._actionManager.getScene().getRenderId();
  48980. // We cache the current evaluation for the current frame
  48981. if (condition._evaluationId === currentRenderId) {
  48982. if (!condition._currentResult) {
  48983. return;
  48984. }
  48985. }
  48986. else {
  48987. condition._evaluationId = currentRenderId;
  48988. if (!condition.isValid()) {
  48989. condition._currentResult = false;
  48990. return;
  48991. }
  48992. condition._currentResult = true;
  48993. }
  48994. }
  48995. this.onBeforeExecuteObservable.notifyObservers(this);
  48996. this._nextActiveAction.execute(evt);
  48997. this.skipToNextActiveAction();
  48998. };
  48999. Action.prototype.execute = function (evt) {
  49000. };
  49001. Action.prototype.skipToNextActiveAction = function () {
  49002. if (this._nextActiveAction._child) {
  49003. if (!this._nextActiveAction._child._actionManager) {
  49004. this._nextActiveAction._child._actionManager = this._actionManager;
  49005. }
  49006. this._nextActiveAction = this._nextActiveAction._child;
  49007. }
  49008. else {
  49009. this._nextActiveAction = this;
  49010. }
  49011. };
  49012. Action.prototype.then = function (action) {
  49013. this._child = action;
  49014. action._actionManager = this._actionManager;
  49015. action._prepare();
  49016. return action;
  49017. };
  49018. Action.prototype._getProperty = function (propertyPath) {
  49019. return this._actionManager._getProperty(propertyPath);
  49020. };
  49021. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  49022. return this._actionManager._getEffectiveTarget(target, propertyPath);
  49023. };
  49024. Action.prototype.serialize = function (parent) {
  49025. };
  49026. // Called by BABYLON.Action objects in serialize(...). Internal use
  49027. Action.prototype._serialize = function (serializedAction, parent) {
  49028. var serializationObject = {
  49029. type: 1,
  49030. children: [],
  49031. name: serializedAction.name,
  49032. properties: serializedAction.properties || []
  49033. };
  49034. // Serialize child
  49035. if (this._child) {
  49036. this._child.serialize(serializationObject);
  49037. }
  49038. // Check if "this" has a condition
  49039. if (this._condition) {
  49040. var serializedCondition = this._condition.serialize();
  49041. serializedCondition.children.push(serializationObject);
  49042. if (parent) {
  49043. parent.children.push(serializedCondition);
  49044. }
  49045. return serializedCondition;
  49046. }
  49047. if (parent) {
  49048. parent.children.push(serializationObject);
  49049. }
  49050. return serializationObject;
  49051. };
  49052. Action._SerializeValueAsString = function (value) {
  49053. if (typeof value === "number") {
  49054. return value.toString();
  49055. }
  49056. if (typeof value === "boolean") {
  49057. return value ? "true" : "false";
  49058. }
  49059. if (value instanceof BABYLON.Vector2) {
  49060. return value.x + ", " + value.y;
  49061. }
  49062. if (value instanceof BABYLON.Vector3) {
  49063. return value.x + ", " + value.y + ", " + value.z;
  49064. }
  49065. if (value instanceof BABYLON.Color3) {
  49066. return value.r + ", " + value.g + ", " + value.b;
  49067. }
  49068. if (value instanceof BABYLON.Color4) {
  49069. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  49070. }
  49071. return value; // string
  49072. };
  49073. Action._GetTargetProperty = function (target) {
  49074. return {
  49075. name: "target",
  49076. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  49077. : target instanceof BABYLON.Light ? "LightProperties"
  49078. : target instanceof BABYLON.Camera ? "CameraProperties"
  49079. : "SceneProperties",
  49080. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  49081. };
  49082. };
  49083. return Action;
  49084. }());
  49085. BABYLON.Action = Action;
  49086. })(BABYLON || (BABYLON = {}));
  49087. //# sourceMappingURL=babylon.action.js.map
  49088. "use strict";
  49089. var BABYLON;
  49090. (function (BABYLON) {
  49091. /**
  49092. * ActionEvent is the event beint sent when an action is triggered.
  49093. */
  49094. var ActionEvent = /** @class */ (function () {
  49095. /**
  49096. * @param source The mesh or sprite that triggered the action.
  49097. * @param pointerX The X mouse cursor position at the time of the event
  49098. * @param pointerY The Y mouse cursor position at the time of the event
  49099. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  49100. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  49101. */
  49102. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  49103. this.source = source;
  49104. this.pointerX = pointerX;
  49105. this.pointerY = pointerY;
  49106. this.meshUnderPointer = meshUnderPointer;
  49107. this.sourceEvent = sourceEvent;
  49108. this.additionalData = additionalData;
  49109. }
  49110. /**
  49111. * Helper function to auto-create an ActionEvent from a source mesh.
  49112. * @param source The source mesh that triggered the event
  49113. * @param evt {Event} The original (browser) event
  49114. */
  49115. ActionEvent.CreateNew = function (source, evt, additionalData) {
  49116. var scene = source.getScene();
  49117. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  49118. };
  49119. /**
  49120. * Helper function to auto-create an ActionEvent from a source mesh.
  49121. * @param source The source sprite that triggered the event
  49122. * @param scene Scene associated with the sprite
  49123. * @param evt {Event} The original (browser) event
  49124. */
  49125. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  49126. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  49127. };
  49128. /**
  49129. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  49130. * @param scene the scene where the event occurred
  49131. * @param evt {Event} The original (browser) event
  49132. */
  49133. ActionEvent.CreateNewFromScene = function (scene, evt) {
  49134. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  49135. };
  49136. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  49137. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  49138. };
  49139. return ActionEvent;
  49140. }());
  49141. BABYLON.ActionEvent = ActionEvent;
  49142. /**
  49143. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  49144. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  49145. */
  49146. var ActionManager = /** @class */ (function () {
  49147. function ActionManager(scene) {
  49148. // Members
  49149. this.actions = new Array();
  49150. this.hoverCursor = '';
  49151. this._scene = scene;
  49152. scene._actionManagers.push(this);
  49153. }
  49154. Object.defineProperty(ActionManager, "NothingTrigger", {
  49155. get: function () {
  49156. return ActionManager._NothingTrigger;
  49157. },
  49158. enumerable: true,
  49159. configurable: true
  49160. });
  49161. Object.defineProperty(ActionManager, "OnPickTrigger", {
  49162. get: function () {
  49163. return ActionManager._OnPickTrigger;
  49164. },
  49165. enumerable: true,
  49166. configurable: true
  49167. });
  49168. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  49169. get: function () {
  49170. return ActionManager._OnLeftPickTrigger;
  49171. },
  49172. enumerable: true,
  49173. configurable: true
  49174. });
  49175. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  49176. get: function () {
  49177. return ActionManager._OnRightPickTrigger;
  49178. },
  49179. enumerable: true,
  49180. configurable: true
  49181. });
  49182. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  49183. get: function () {
  49184. return ActionManager._OnCenterPickTrigger;
  49185. },
  49186. enumerable: true,
  49187. configurable: true
  49188. });
  49189. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  49190. get: function () {
  49191. return ActionManager._OnPickDownTrigger;
  49192. },
  49193. enumerable: true,
  49194. configurable: true
  49195. });
  49196. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  49197. get: function () {
  49198. return ActionManager._OnDoublePickTrigger;
  49199. },
  49200. enumerable: true,
  49201. configurable: true
  49202. });
  49203. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  49204. get: function () {
  49205. return ActionManager._OnPickUpTrigger;
  49206. },
  49207. enumerable: true,
  49208. configurable: true
  49209. });
  49210. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  49211. /// This trigger will only be raised if you also declared a OnPickDown
  49212. get: function () {
  49213. return ActionManager._OnPickOutTrigger;
  49214. },
  49215. enumerable: true,
  49216. configurable: true
  49217. });
  49218. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  49219. get: function () {
  49220. return ActionManager._OnLongPressTrigger;
  49221. },
  49222. enumerable: true,
  49223. configurable: true
  49224. });
  49225. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  49226. get: function () {
  49227. return ActionManager._OnPointerOverTrigger;
  49228. },
  49229. enumerable: true,
  49230. configurable: true
  49231. });
  49232. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  49233. get: function () {
  49234. return ActionManager._OnPointerOutTrigger;
  49235. },
  49236. enumerable: true,
  49237. configurable: true
  49238. });
  49239. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  49240. get: function () {
  49241. return ActionManager._OnEveryFrameTrigger;
  49242. },
  49243. enumerable: true,
  49244. configurable: true
  49245. });
  49246. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  49247. get: function () {
  49248. return ActionManager._OnIntersectionEnterTrigger;
  49249. },
  49250. enumerable: true,
  49251. configurable: true
  49252. });
  49253. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  49254. get: function () {
  49255. return ActionManager._OnIntersectionExitTrigger;
  49256. },
  49257. enumerable: true,
  49258. configurable: true
  49259. });
  49260. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  49261. get: function () {
  49262. return ActionManager._OnKeyDownTrigger;
  49263. },
  49264. enumerable: true,
  49265. configurable: true
  49266. });
  49267. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  49268. get: function () {
  49269. return ActionManager._OnKeyUpTrigger;
  49270. },
  49271. enumerable: true,
  49272. configurable: true
  49273. });
  49274. // Methods
  49275. ActionManager.prototype.dispose = function () {
  49276. var index = this._scene._actionManagers.indexOf(this);
  49277. for (var i = 0; i < this.actions.length; i++) {
  49278. var action = this.actions[i];
  49279. ActionManager.Triggers[action.trigger]--;
  49280. if (ActionManager.Triggers[action.trigger] === 0) {
  49281. delete ActionManager.Triggers[action.trigger];
  49282. }
  49283. }
  49284. if (index > -1) {
  49285. this._scene._actionManagers.splice(index, 1);
  49286. }
  49287. };
  49288. ActionManager.prototype.getScene = function () {
  49289. return this._scene;
  49290. };
  49291. /**
  49292. * Does this action manager handles actions of any of the given triggers
  49293. * @param {number[]} triggers - the triggers to be tested
  49294. * @return {boolean} whether one (or more) of the triggers is handeled
  49295. */
  49296. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  49297. for (var index = 0; index < this.actions.length; index++) {
  49298. var action = this.actions[index];
  49299. if (triggers.indexOf(action.trigger) > -1) {
  49300. return true;
  49301. }
  49302. }
  49303. return false;
  49304. };
  49305. /**
  49306. * Does this action manager handles actions of a given trigger
  49307. * @param {number} trigger - the trigger to be tested
  49308. * @return {boolean} whether the trigger is handeled
  49309. */
  49310. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  49311. for (var index = 0; index < this.actions.length; index++) {
  49312. var action = this.actions[index];
  49313. if (action.trigger === trigger) {
  49314. return true;
  49315. }
  49316. }
  49317. return false;
  49318. };
  49319. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  49320. /**
  49321. * Does this action manager has pointer triggers
  49322. * @return {boolean} whether or not it has pointer triggers
  49323. */
  49324. get: function () {
  49325. for (var index = 0; index < this.actions.length; index++) {
  49326. var action = this.actions[index];
  49327. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  49328. return true;
  49329. }
  49330. }
  49331. return false;
  49332. },
  49333. enumerable: true,
  49334. configurable: true
  49335. });
  49336. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  49337. /**
  49338. * Does this action manager has pick triggers
  49339. * @return {boolean} whether or not it has pick triggers
  49340. */
  49341. get: function () {
  49342. for (var index = 0; index < this.actions.length; index++) {
  49343. var action = this.actions[index];
  49344. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  49345. return true;
  49346. }
  49347. }
  49348. return false;
  49349. },
  49350. enumerable: true,
  49351. configurable: true
  49352. });
  49353. Object.defineProperty(ActionManager, "HasTriggers", {
  49354. /**
  49355. * Does exist one action manager with at least one trigger
  49356. * @return {boolean} whether or not it exists one action manager with one trigger
  49357. **/
  49358. get: function () {
  49359. for (var t in ActionManager.Triggers) {
  49360. if (ActionManager.Triggers.hasOwnProperty(t)) {
  49361. return true;
  49362. }
  49363. }
  49364. return false;
  49365. },
  49366. enumerable: true,
  49367. configurable: true
  49368. });
  49369. Object.defineProperty(ActionManager, "HasPickTriggers", {
  49370. /**
  49371. * Does exist one action manager with at least one pick trigger
  49372. * @return {boolean} whether or not it exists one action manager with one pick trigger
  49373. **/
  49374. get: function () {
  49375. for (var t in ActionManager.Triggers) {
  49376. if (ActionManager.Triggers.hasOwnProperty(t)) {
  49377. var t_int = parseInt(t);
  49378. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  49379. return true;
  49380. }
  49381. }
  49382. }
  49383. return false;
  49384. },
  49385. enumerable: true,
  49386. configurable: true
  49387. });
  49388. /**
  49389. * Does exist one action manager that handles actions of a given trigger
  49390. * @param {number} trigger - the trigger to be tested
  49391. * @return {boolean} whether the trigger is handeled by at least one action manager
  49392. **/
  49393. ActionManager.HasSpecificTrigger = function (trigger) {
  49394. for (var t in ActionManager.Triggers) {
  49395. if (ActionManager.Triggers.hasOwnProperty(t)) {
  49396. var t_int = parseInt(t);
  49397. if (t_int === trigger) {
  49398. return true;
  49399. }
  49400. }
  49401. }
  49402. return false;
  49403. };
  49404. /**
  49405. * Registers an action to this action manager
  49406. * @param {BABYLON.Action} action - the action to be registered
  49407. * @return {BABYLON.Action} the action amended (prepared) after registration
  49408. */
  49409. ActionManager.prototype.registerAction = function (action) {
  49410. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  49411. if (this.getScene().actionManager !== this) {
  49412. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  49413. return null;
  49414. }
  49415. }
  49416. this.actions.push(action);
  49417. if (ActionManager.Triggers[action.trigger]) {
  49418. ActionManager.Triggers[action.trigger]++;
  49419. }
  49420. else {
  49421. ActionManager.Triggers[action.trigger] = 1;
  49422. }
  49423. action._actionManager = this;
  49424. action._prepare();
  49425. return action;
  49426. };
  49427. /**
  49428. * Unregisters an action to this action manager
  49429. * @param action The action to be unregistered
  49430. * @return whether the action has been unregistered
  49431. */
  49432. ActionManager.prototype.unregisterAction = function (action) {
  49433. var index = this.actions.indexOf(action);
  49434. if (index !== -1) {
  49435. this.actions.splice(index, 1);
  49436. ActionManager.Triggers[action.trigger] -= 1;
  49437. if (ActionManager.Triggers[action.trigger] === 0) {
  49438. delete ActionManager.Triggers[action.trigger];
  49439. }
  49440. delete action._actionManager;
  49441. return true;
  49442. }
  49443. return false;
  49444. };
  49445. /**
  49446. * Process a specific trigger
  49447. * @param {number} trigger - the trigger to process
  49448. * @param evt {BABYLON.ActionEvent} the event details to be processed
  49449. */
  49450. ActionManager.prototype.processTrigger = function (trigger, evt) {
  49451. for (var index = 0; index < this.actions.length; index++) {
  49452. var action = this.actions[index];
  49453. if (action.trigger === trigger) {
  49454. if (evt) {
  49455. if (trigger === ActionManager.OnKeyUpTrigger
  49456. || trigger === ActionManager.OnKeyDownTrigger) {
  49457. var parameter = action.getTriggerParameter();
  49458. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  49459. if (!parameter.toLowerCase) {
  49460. continue;
  49461. }
  49462. var lowerCase = parameter.toLowerCase();
  49463. if (lowerCase !== evt.sourceEvent.key) {
  49464. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  49465. var actualkey = String.fromCharCode(unicode).toLowerCase();
  49466. if (actualkey !== lowerCase) {
  49467. continue;
  49468. }
  49469. }
  49470. }
  49471. }
  49472. }
  49473. action._executeCurrent(evt);
  49474. }
  49475. }
  49476. };
  49477. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  49478. var properties = propertyPath.split(".");
  49479. for (var index = 0; index < properties.length - 1; index++) {
  49480. target = target[properties[index]];
  49481. }
  49482. return target;
  49483. };
  49484. ActionManager.prototype._getProperty = function (propertyPath) {
  49485. var properties = propertyPath.split(".");
  49486. return properties[properties.length - 1];
  49487. };
  49488. ActionManager.prototype.serialize = function (name) {
  49489. var root = {
  49490. children: new Array(),
  49491. name: name,
  49492. type: 3,
  49493. properties: new Array() // Empty for root but required
  49494. };
  49495. for (var i = 0; i < this.actions.length; i++) {
  49496. var triggerObject = {
  49497. type: 0,
  49498. children: new Array(),
  49499. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  49500. properties: new Array()
  49501. };
  49502. var triggerOptions = this.actions[i].triggerOptions;
  49503. if (triggerOptions && typeof triggerOptions !== "number") {
  49504. if (triggerOptions.parameter instanceof BABYLON.Node) {
  49505. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  49506. }
  49507. else {
  49508. var parameter = {};
  49509. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  49510. if (triggerOptions.parameter.mesh) {
  49511. parameter._meshId = triggerOptions.parameter.mesh.id;
  49512. }
  49513. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  49514. }
  49515. }
  49516. // Serialize child action, recursively
  49517. this.actions[i].serialize(triggerObject);
  49518. // Add serialized trigger
  49519. root.children.push(triggerObject);
  49520. }
  49521. return root;
  49522. };
  49523. ActionManager.Parse = function (parsedActions, object, scene) {
  49524. var actionManager = new ActionManager(scene);
  49525. if (object === null)
  49526. scene.actionManager = actionManager;
  49527. else
  49528. object.actionManager = actionManager;
  49529. // instanciate a new object
  49530. var instanciate = function (name, params) {
  49531. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  49532. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  49533. newInstance.constructor.apply(newInstance, params);
  49534. return newInstance;
  49535. };
  49536. var parseParameter = function (name, value, target, propertyPath) {
  49537. if (propertyPath === null) {
  49538. // String, boolean or float
  49539. var floatValue = parseFloat(value);
  49540. if (value === "true" || value === "false")
  49541. return value === "true";
  49542. else
  49543. return isNaN(floatValue) ? value : floatValue;
  49544. }
  49545. var effectiveTarget = propertyPath.split(".");
  49546. var values = value.split(",");
  49547. // Get effective Target
  49548. for (var i = 0; i < effectiveTarget.length; i++) {
  49549. target = target[effectiveTarget[i]];
  49550. }
  49551. // Return appropriate value with its type
  49552. if (typeof (target) === "boolean")
  49553. return values[0] === "true";
  49554. if (typeof (target) === "string")
  49555. return values[0];
  49556. // Parameters with multiple values such as Vector3 etc.
  49557. var split = new Array();
  49558. for (var i = 0; i < values.length; i++)
  49559. split.push(parseFloat(values[i]));
  49560. if (target instanceof BABYLON.Vector3)
  49561. return BABYLON.Vector3.FromArray(split);
  49562. if (target instanceof BABYLON.Vector4)
  49563. return BABYLON.Vector4.FromArray(split);
  49564. if (target instanceof BABYLON.Color3)
  49565. return BABYLON.Color3.FromArray(split);
  49566. if (target instanceof BABYLON.Color4)
  49567. return BABYLON.Color4.FromArray(split);
  49568. return parseFloat(values[0]);
  49569. };
  49570. // traverse graph per trigger
  49571. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  49572. if (combineArray === void 0) { combineArray = null; }
  49573. if (parsedAction.detached)
  49574. return;
  49575. var parameters = new Array();
  49576. var target = null;
  49577. var propertyPath = null;
  49578. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  49579. // Parameters
  49580. if (parsedAction.type === 2)
  49581. parameters.push(actionManager);
  49582. else
  49583. parameters.push(trigger);
  49584. if (combine) {
  49585. var actions = new Array();
  49586. for (var j = 0; j < parsedAction.combine.length; j++) {
  49587. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  49588. }
  49589. parameters.push(actions);
  49590. }
  49591. else {
  49592. for (var i = 0; i < parsedAction.properties.length; i++) {
  49593. var value = parsedAction.properties[i].value;
  49594. var name = parsedAction.properties[i].name;
  49595. var targetType = parsedAction.properties[i].targetType;
  49596. if (name === "target")
  49597. if (targetType !== null && targetType === "SceneProperties")
  49598. value = target = scene;
  49599. else
  49600. value = target = scene.getNodeByName(value);
  49601. else if (name === "parent")
  49602. value = scene.getNodeByName(value);
  49603. else if (name === "sound")
  49604. value = scene.getSoundByName(value);
  49605. else if (name !== "propertyPath") {
  49606. if (parsedAction.type === 2 && name === "operator")
  49607. value = BABYLON.ValueCondition[value];
  49608. else
  49609. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  49610. }
  49611. else {
  49612. propertyPath = value;
  49613. }
  49614. parameters.push(value);
  49615. }
  49616. }
  49617. if (combineArray === null) {
  49618. parameters.push(condition);
  49619. }
  49620. else {
  49621. parameters.push(null);
  49622. }
  49623. // If interpolate value action
  49624. if (parsedAction.name === "InterpolateValueAction") {
  49625. var param = parameters[parameters.length - 2];
  49626. parameters[parameters.length - 1] = param;
  49627. parameters[parameters.length - 2] = condition;
  49628. }
  49629. // Action or condition(s) and not CombineAction
  49630. var newAction = instanciate(parsedAction.name, parameters);
  49631. if (newAction instanceof BABYLON.Condition && condition !== null) {
  49632. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  49633. if (action)
  49634. action.then(nothing);
  49635. else
  49636. actionManager.registerAction(nothing);
  49637. action = nothing;
  49638. }
  49639. if (combineArray === null) {
  49640. if (newAction instanceof BABYLON.Condition) {
  49641. condition = newAction;
  49642. newAction = action;
  49643. }
  49644. else {
  49645. condition = null;
  49646. if (action)
  49647. action.then(newAction);
  49648. else
  49649. actionManager.registerAction(newAction);
  49650. }
  49651. }
  49652. else {
  49653. combineArray.push(newAction);
  49654. }
  49655. for (var i = 0; i < parsedAction.children.length; i++)
  49656. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  49657. };
  49658. // triggers
  49659. for (var i = 0; i < parsedActions.children.length; i++) {
  49660. var triggerParams;
  49661. var trigger = parsedActions.children[i];
  49662. if (trigger.properties.length > 0) {
  49663. var param = trigger.properties[0].value;
  49664. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  49665. if (value._meshId) {
  49666. value.mesh = scene.getMeshByID(value._meshId);
  49667. }
  49668. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  49669. }
  49670. else
  49671. triggerParams = ActionManager[trigger.name];
  49672. for (var j = 0; j < trigger.children.length; j++) {
  49673. if (!trigger.detached)
  49674. traverse(trigger.children[j], triggerParams, null, null);
  49675. }
  49676. }
  49677. };
  49678. ActionManager.GetTriggerName = function (trigger) {
  49679. switch (trigger) {
  49680. case 0: return "NothingTrigger";
  49681. case 1: return "OnPickTrigger";
  49682. case 2: return "OnLeftPickTrigger";
  49683. case 3: return "OnRightPickTrigger";
  49684. case 4: return "OnCenterPickTrigger";
  49685. case 5: return "OnPickDownTrigger";
  49686. case 6: return "OnPickUpTrigger";
  49687. case 7: return "OnLongPressTrigger";
  49688. case 8: return "OnPointerOverTrigger";
  49689. case 9: return "OnPointerOutTrigger";
  49690. case 10: return "OnEveryFrameTrigger";
  49691. case 11: return "OnIntersectionEnterTrigger";
  49692. case 12: return "OnIntersectionExitTrigger";
  49693. case 13: return "OnKeyDownTrigger";
  49694. case 14: return "OnKeyUpTrigger";
  49695. case 15: return "OnPickOutTrigger";
  49696. default: return "";
  49697. }
  49698. };
  49699. // Statics
  49700. ActionManager._NothingTrigger = 0;
  49701. ActionManager._OnPickTrigger = 1;
  49702. ActionManager._OnLeftPickTrigger = 2;
  49703. ActionManager._OnRightPickTrigger = 3;
  49704. ActionManager._OnCenterPickTrigger = 4;
  49705. ActionManager._OnPickDownTrigger = 5;
  49706. ActionManager._OnDoublePickTrigger = 6;
  49707. ActionManager._OnPickUpTrigger = 7;
  49708. ActionManager._OnLongPressTrigger = 8;
  49709. ActionManager._OnPointerOverTrigger = 9;
  49710. ActionManager._OnPointerOutTrigger = 10;
  49711. ActionManager._OnEveryFrameTrigger = 11;
  49712. ActionManager._OnIntersectionEnterTrigger = 12;
  49713. ActionManager._OnIntersectionExitTrigger = 13;
  49714. ActionManager._OnKeyDownTrigger = 14;
  49715. ActionManager._OnKeyUpTrigger = 15;
  49716. ActionManager._OnPickOutTrigger = 16;
  49717. ActionManager.Triggers = {};
  49718. return ActionManager;
  49719. }());
  49720. BABYLON.ActionManager = ActionManager;
  49721. })(BABYLON || (BABYLON = {}));
  49722. //# sourceMappingURL=babylon.actionManager.js.map
  49723. "use strict";
  49724. var BABYLON;
  49725. (function (BABYLON) {
  49726. var InterpolateValueAction = /** @class */ (function (_super) {
  49727. __extends(InterpolateValueAction, _super);
  49728. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  49729. if (duration === void 0) { duration = 1000; }
  49730. var _this = _super.call(this, triggerOptions, condition) || this;
  49731. _this.propertyPath = propertyPath;
  49732. _this.value = value;
  49733. _this.duration = duration;
  49734. _this.stopOtherAnimations = stopOtherAnimations;
  49735. _this.onInterpolationDone = onInterpolationDone;
  49736. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  49737. _this._target = _this._effectiveTarget = target;
  49738. return _this;
  49739. }
  49740. InterpolateValueAction.prototype._prepare = function () {
  49741. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49742. this._property = this._getProperty(this.propertyPath);
  49743. };
  49744. InterpolateValueAction.prototype.execute = function () {
  49745. var _this = this;
  49746. var scene = this._actionManager.getScene();
  49747. var keys = [
  49748. {
  49749. frame: 0,
  49750. value: this._effectiveTarget[this._property]
  49751. }, {
  49752. frame: 100,
  49753. value: this.value
  49754. }
  49755. ];
  49756. var dataType;
  49757. if (typeof this.value === "number") {
  49758. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  49759. }
  49760. else if (this.value instanceof BABYLON.Color3) {
  49761. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  49762. }
  49763. else if (this.value instanceof BABYLON.Vector3) {
  49764. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  49765. }
  49766. else if (this.value instanceof BABYLON.Matrix) {
  49767. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  49768. }
  49769. else if (this.value instanceof BABYLON.Quaternion) {
  49770. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  49771. }
  49772. else {
  49773. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  49774. return;
  49775. }
  49776. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  49777. animation.setKeys(keys);
  49778. if (this.stopOtherAnimations) {
  49779. scene.stopAnimation(this._effectiveTarget);
  49780. }
  49781. var wrapper = function () {
  49782. _this.onInterpolationDoneObservable.notifyObservers(_this);
  49783. if (_this.onInterpolationDone) {
  49784. _this.onInterpolationDone();
  49785. }
  49786. };
  49787. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  49788. };
  49789. InterpolateValueAction.prototype.serialize = function (parent) {
  49790. return _super.prototype._serialize.call(this, {
  49791. name: "InterpolateValueAction",
  49792. properties: [
  49793. BABYLON.Action._GetTargetProperty(this._target),
  49794. { name: "propertyPath", value: this.propertyPath },
  49795. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  49796. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  49797. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  49798. ]
  49799. }, parent);
  49800. };
  49801. return InterpolateValueAction;
  49802. }(BABYLON.Action));
  49803. BABYLON.InterpolateValueAction = InterpolateValueAction;
  49804. })(BABYLON || (BABYLON = {}));
  49805. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  49806. "use strict";
  49807. var BABYLON;
  49808. (function (BABYLON) {
  49809. var SwitchBooleanAction = /** @class */ (function (_super) {
  49810. __extends(SwitchBooleanAction, _super);
  49811. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  49812. var _this = _super.call(this, triggerOptions, condition) || this;
  49813. _this.propertyPath = propertyPath;
  49814. _this._target = _this._effectiveTarget = target;
  49815. return _this;
  49816. }
  49817. SwitchBooleanAction.prototype._prepare = function () {
  49818. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49819. this._property = this._getProperty(this.propertyPath);
  49820. };
  49821. SwitchBooleanAction.prototype.execute = function () {
  49822. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  49823. };
  49824. SwitchBooleanAction.prototype.serialize = function (parent) {
  49825. return _super.prototype._serialize.call(this, {
  49826. name: "SwitchBooleanAction",
  49827. properties: [
  49828. BABYLON.Action._GetTargetProperty(this._target),
  49829. { name: "propertyPath", value: this.propertyPath }
  49830. ]
  49831. }, parent);
  49832. };
  49833. return SwitchBooleanAction;
  49834. }(BABYLON.Action));
  49835. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  49836. var SetStateAction = /** @class */ (function (_super) {
  49837. __extends(SetStateAction, _super);
  49838. function SetStateAction(triggerOptions, target, value, condition) {
  49839. var _this = _super.call(this, triggerOptions, condition) || this;
  49840. _this.value = value;
  49841. _this._target = target;
  49842. return _this;
  49843. }
  49844. SetStateAction.prototype.execute = function () {
  49845. this._target.state = this.value;
  49846. };
  49847. SetStateAction.prototype.serialize = function (parent) {
  49848. return _super.prototype._serialize.call(this, {
  49849. name: "SetStateAction",
  49850. properties: [
  49851. BABYLON.Action._GetTargetProperty(this._target),
  49852. { name: "value", value: this.value }
  49853. ]
  49854. }, parent);
  49855. };
  49856. return SetStateAction;
  49857. }(BABYLON.Action));
  49858. BABYLON.SetStateAction = SetStateAction;
  49859. var SetValueAction = /** @class */ (function (_super) {
  49860. __extends(SetValueAction, _super);
  49861. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  49862. var _this = _super.call(this, triggerOptions, condition) || this;
  49863. _this.propertyPath = propertyPath;
  49864. _this.value = value;
  49865. _this._target = _this._effectiveTarget = target;
  49866. return _this;
  49867. }
  49868. SetValueAction.prototype._prepare = function () {
  49869. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49870. this._property = this._getProperty(this.propertyPath);
  49871. };
  49872. SetValueAction.prototype.execute = function () {
  49873. this._effectiveTarget[this._property] = this.value;
  49874. if (this._target.markAsDirty) {
  49875. this._target.markAsDirty(this._property);
  49876. }
  49877. };
  49878. SetValueAction.prototype.serialize = function (parent) {
  49879. return _super.prototype._serialize.call(this, {
  49880. name: "SetValueAction",
  49881. properties: [
  49882. BABYLON.Action._GetTargetProperty(this._target),
  49883. { name: "propertyPath", value: this.propertyPath },
  49884. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  49885. ]
  49886. }, parent);
  49887. };
  49888. return SetValueAction;
  49889. }(BABYLON.Action));
  49890. BABYLON.SetValueAction = SetValueAction;
  49891. var IncrementValueAction = /** @class */ (function (_super) {
  49892. __extends(IncrementValueAction, _super);
  49893. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  49894. var _this = _super.call(this, triggerOptions, condition) || this;
  49895. _this.propertyPath = propertyPath;
  49896. _this.value = value;
  49897. _this._target = _this._effectiveTarget = target;
  49898. return _this;
  49899. }
  49900. IncrementValueAction.prototype._prepare = function () {
  49901. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49902. this._property = this._getProperty(this.propertyPath);
  49903. if (typeof this._effectiveTarget[this._property] !== "number") {
  49904. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  49905. }
  49906. };
  49907. IncrementValueAction.prototype.execute = function () {
  49908. this._effectiveTarget[this._property] += this.value;
  49909. if (this._target.markAsDirty) {
  49910. this._target.markAsDirty(this._property);
  49911. }
  49912. };
  49913. IncrementValueAction.prototype.serialize = function (parent) {
  49914. return _super.prototype._serialize.call(this, {
  49915. name: "IncrementValueAction",
  49916. properties: [
  49917. BABYLON.Action._GetTargetProperty(this._target),
  49918. { name: "propertyPath", value: this.propertyPath },
  49919. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  49920. ]
  49921. }, parent);
  49922. };
  49923. return IncrementValueAction;
  49924. }(BABYLON.Action));
  49925. BABYLON.IncrementValueAction = IncrementValueAction;
  49926. var PlayAnimationAction = /** @class */ (function (_super) {
  49927. __extends(PlayAnimationAction, _super);
  49928. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  49929. var _this = _super.call(this, triggerOptions, condition) || this;
  49930. _this.from = from;
  49931. _this.to = to;
  49932. _this.loop = loop;
  49933. _this._target = target;
  49934. return _this;
  49935. }
  49936. PlayAnimationAction.prototype._prepare = function () {
  49937. };
  49938. PlayAnimationAction.prototype.execute = function () {
  49939. var scene = this._actionManager.getScene();
  49940. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  49941. };
  49942. PlayAnimationAction.prototype.serialize = function (parent) {
  49943. return _super.prototype._serialize.call(this, {
  49944. name: "PlayAnimationAction",
  49945. properties: [
  49946. BABYLON.Action._GetTargetProperty(this._target),
  49947. { name: "from", value: String(this.from) },
  49948. { name: "to", value: String(this.to) },
  49949. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  49950. ]
  49951. }, parent);
  49952. };
  49953. return PlayAnimationAction;
  49954. }(BABYLON.Action));
  49955. BABYLON.PlayAnimationAction = PlayAnimationAction;
  49956. var StopAnimationAction = /** @class */ (function (_super) {
  49957. __extends(StopAnimationAction, _super);
  49958. function StopAnimationAction(triggerOptions, target, condition) {
  49959. var _this = _super.call(this, triggerOptions, condition) || this;
  49960. _this._target = target;
  49961. return _this;
  49962. }
  49963. StopAnimationAction.prototype._prepare = function () {
  49964. };
  49965. StopAnimationAction.prototype.execute = function () {
  49966. var scene = this._actionManager.getScene();
  49967. scene.stopAnimation(this._target);
  49968. };
  49969. StopAnimationAction.prototype.serialize = function (parent) {
  49970. return _super.prototype._serialize.call(this, {
  49971. name: "StopAnimationAction",
  49972. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  49973. }, parent);
  49974. };
  49975. return StopAnimationAction;
  49976. }(BABYLON.Action));
  49977. BABYLON.StopAnimationAction = StopAnimationAction;
  49978. var DoNothingAction = /** @class */ (function (_super) {
  49979. __extends(DoNothingAction, _super);
  49980. function DoNothingAction(triggerOptions, condition) {
  49981. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  49982. return _super.call(this, triggerOptions, condition) || this;
  49983. }
  49984. DoNothingAction.prototype.execute = function () {
  49985. };
  49986. DoNothingAction.prototype.serialize = function (parent) {
  49987. return _super.prototype._serialize.call(this, {
  49988. name: "DoNothingAction",
  49989. properties: []
  49990. }, parent);
  49991. };
  49992. return DoNothingAction;
  49993. }(BABYLON.Action));
  49994. BABYLON.DoNothingAction = DoNothingAction;
  49995. var CombineAction = /** @class */ (function (_super) {
  49996. __extends(CombineAction, _super);
  49997. function CombineAction(triggerOptions, children, condition) {
  49998. var _this = _super.call(this, triggerOptions, condition) || this;
  49999. _this.children = children;
  50000. return _this;
  50001. }
  50002. CombineAction.prototype._prepare = function () {
  50003. for (var index = 0; index < this.children.length; index++) {
  50004. this.children[index]._actionManager = this._actionManager;
  50005. this.children[index]._prepare();
  50006. }
  50007. };
  50008. CombineAction.prototype.execute = function (evt) {
  50009. for (var index = 0; index < this.children.length; index++) {
  50010. this.children[index].execute(evt);
  50011. }
  50012. };
  50013. CombineAction.prototype.serialize = function (parent) {
  50014. var serializationObject = _super.prototype._serialize.call(this, {
  50015. name: "CombineAction",
  50016. properties: [],
  50017. combine: []
  50018. }, parent);
  50019. for (var i = 0; i < this.children.length; i++) {
  50020. serializationObject.combine.push(this.children[i].serialize(null));
  50021. }
  50022. return serializationObject;
  50023. };
  50024. return CombineAction;
  50025. }(BABYLON.Action));
  50026. BABYLON.CombineAction = CombineAction;
  50027. var ExecuteCodeAction = /** @class */ (function (_super) {
  50028. __extends(ExecuteCodeAction, _super);
  50029. function ExecuteCodeAction(triggerOptions, func, condition) {
  50030. var _this = _super.call(this, triggerOptions, condition) || this;
  50031. _this.func = func;
  50032. return _this;
  50033. }
  50034. ExecuteCodeAction.prototype.execute = function (evt) {
  50035. this.func(evt);
  50036. };
  50037. return ExecuteCodeAction;
  50038. }(BABYLON.Action));
  50039. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  50040. var SetParentAction = /** @class */ (function (_super) {
  50041. __extends(SetParentAction, _super);
  50042. function SetParentAction(triggerOptions, target, parent, condition) {
  50043. var _this = _super.call(this, triggerOptions, condition) || this;
  50044. _this._target = target;
  50045. _this._parent = parent;
  50046. return _this;
  50047. }
  50048. SetParentAction.prototype._prepare = function () {
  50049. };
  50050. SetParentAction.prototype.execute = function () {
  50051. if (this._target.parent === this._parent) {
  50052. return;
  50053. }
  50054. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  50055. invertParentWorldMatrix.invert();
  50056. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  50057. this._target.parent = this._parent;
  50058. };
  50059. SetParentAction.prototype.serialize = function (parent) {
  50060. return _super.prototype._serialize.call(this, {
  50061. name: "SetParentAction",
  50062. properties: [
  50063. BABYLON.Action._GetTargetProperty(this._target),
  50064. BABYLON.Action._GetTargetProperty(this._parent),
  50065. ]
  50066. }, parent);
  50067. };
  50068. return SetParentAction;
  50069. }(BABYLON.Action));
  50070. BABYLON.SetParentAction = SetParentAction;
  50071. var PlaySoundAction = /** @class */ (function (_super) {
  50072. __extends(PlaySoundAction, _super);
  50073. function PlaySoundAction(triggerOptions, sound, condition) {
  50074. var _this = _super.call(this, triggerOptions, condition) || this;
  50075. _this._sound = sound;
  50076. return _this;
  50077. }
  50078. PlaySoundAction.prototype._prepare = function () {
  50079. };
  50080. PlaySoundAction.prototype.execute = function () {
  50081. if (this._sound !== undefined)
  50082. this._sound.play();
  50083. };
  50084. PlaySoundAction.prototype.serialize = function (parent) {
  50085. return _super.prototype._serialize.call(this, {
  50086. name: "PlaySoundAction",
  50087. properties: [{ name: "sound", value: this._sound.name }]
  50088. }, parent);
  50089. };
  50090. return PlaySoundAction;
  50091. }(BABYLON.Action));
  50092. BABYLON.PlaySoundAction = PlaySoundAction;
  50093. var StopSoundAction = /** @class */ (function (_super) {
  50094. __extends(StopSoundAction, _super);
  50095. function StopSoundAction(triggerOptions, sound, condition) {
  50096. var _this = _super.call(this, triggerOptions, condition) || this;
  50097. _this._sound = sound;
  50098. return _this;
  50099. }
  50100. StopSoundAction.prototype._prepare = function () {
  50101. };
  50102. StopSoundAction.prototype.execute = function () {
  50103. if (this._sound !== undefined)
  50104. this._sound.stop();
  50105. };
  50106. StopSoundAction.prototype.serialize = function (parent) {
  50107. return _super.prototype._serialize.call(this, {
  50108. name: "StopSoundAction",
  50109. properties: [{ name: "sound", value: this._sound.name }]
  50110. }, parent);
  50111. };
  50112. return StopSoundAction;
  50113. }(BABYLON.Action));
  50114. BABYLON.StopSoundAction = StopSoundAction;
  50115. })(BABYLON || (BABYLON = {}));
  50116. //# sourceMappingURL=babylon.directActions.js.map
  50117. "use strict";
  50118. var BABYLON;
  50119. (function (BABYLON) {
  50120. var SpriteManager = /** @class */ (function () {
  50121. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  50122. if (epsilon === void 0) { epsilon = 0.01; }
  50123. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50124. this.name = name;
  50125. this.sprites = new Array();
  50126. this.renderingGroupId = 0;
  50127. this.layerMask = 0x0FFFFFFF;
  50128. this.fogEnabled = true;
  50129. this.isPickable = false;
  50130. /**
  50131. * An event triggered when the manager is disposed.
  50132. * @type {BABYLON.Observable}
  50133. */
  50134. this.onDisposeObservable = new BABYLON.Observable();
  50135. this._vertexBuffers = {};
  50136. this._capacity = capacity;
  50137. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  50138. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50139. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50140. if (cellSize.width && cellSize.height) {
  50141. this.cellWidth = cellSize.width;
  50142. this.cellHeight = cellSize.height;
  50143. }
  50144. else if (cellSize !== undefined) {
  50145. this.cellWidth = cellSize;
  50146. this.cellHeight = cellSize;
  50147. }
  50148. else {
  50149. return;
  50150. }
  50151. this._epsilon = epsilon;
  50152. this._scene = scene;
  50153. this._scene.spriteManagers.push(this);
  50154. var indices = [];
  50155. var index = 0;
  50156. for (var count = 0; count < capacity; count++) {
  50157. indices.push(index);
  50158. indices.push(index + 1);
  50159. indices.push(index + 2);
  50160. indices.push(index);
  50161. indices.push(index + 2);
  50162. indices.push(index + 3);
  50163. index += 4;
  50164. }
  50165. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  50166. // VBO
  50167. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  50168. this._vertexData = new Float32Array(capacity * 16 * 4);
  50169. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  50170. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  50171. var options = this._buffer.createVertexBuffer("options", 4, 4);
  50172. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  50173. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  50174. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  50175. this._vertexBuffers["options"] = options;
  50176. this._vertexBuffers["cellInfo"] = cellInfo;
  50177. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  50178. // Effects
  50179. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  50180. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  50181. }
  50182. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  50183. set: function (callback) {
  50184. if (this._onDisposeObserver) {
  50185. this.onDisposeObservable.remove(this._onDisposeObserver);
  50186. }
  50187. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  50188. },
  50189. enumerable: true,
  50190. configurable: true
  50191. });
  50192. Object.defineProperty(SpriteManager.prototype, "texture", {
  50193. get: function () {
  50194. return this._spriteTexture;
  50195. },
  50196. set: function (value) {
  50197. this._spriteTexture = value;
  50198. },
  50199. enumerable: true,
  50200. configurable: true
  50201. });
  50202. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  50203. var arrayOffset = index * 16;
  50204. if (offsetX === 0)
  50205. offsetX = this._epsilon;
  50206. else if (offsetX === 1)
  50207. offsetX = 1 - this._epsilon;
  50208. if (offsetY === 0)
  50209. offsetY = this._epsilon;
  50210. else if (offsetY === 1)
  50211. offsetY = 1 - this._epsilon;
  50212. this._vertexData[arrayOffset] = sprite.position.x;
  50213. this._vertexData[arrayOffset + 1] = sprite.position.y;
  50214. this._vertexData[arrayOffset + 2] = sprite.position.z;
  50215. this._vertexData[arrayOffset + 3] = sprite.angle;
  50216. this._vertexData[arrayOffset + 4] = sprite.width;
  50217. this._vertexData[arrayOffset + 5] = sprite.height;
  50218. this._vertexData[arrayOffset + 6] = offsetX;
  50219. this._vertexData[arrayOffset + 7] = offsetY;
  50220. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  50221. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  50222. var offset = (sprite.cellIndex / rowSize) >> 0;
  50223. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  50224. this._vertexData[arrayOffset + 11] = offset;
  50225. // Color
  50226. this._vertexData[arrayOffset + 12] = sprite.color.r;
  50227. this._vertexData[arrayOffset + 13] = sprite.color.g;
  50228. this._vertexData[arrayOffset + 14] = sprite.color.b;
  50229. this._vertexData[arrayOffset + 15] = sprite.color.a;
  50230. };
  50231. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  50232. var count = Math.min(this._capacity, this.sprites.length);
  50233. var min = BABYLON.Vector3.Zero();
  50234. var max = BABYLON.Vector3.Zero();
  50235. var distance = Number.MAX_VALUE;
  50236. var currentSprite = null;
  50237. var cameraSpacePosition = BABYLON.Vector3.Zero();
  50238. var cameraView = camera.getViewMatrix();
  50239. for (var index = 0; index < count; index++) {
  50240. var sprite = this.sprites[index];
  50241. if (!sprite) {
  50242. continue;
  50243. }
  50244. if (predicate) {
  50245. if (!predicate(sprite)) {
  50246. continue;
  50247. }
  50248. }
  50249. else if (!sprite.isPickable) {
  50250. continue;
  50251. }
  50252. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  50253. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  50254. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  50255. if (ray.intersectsBoxMinMax(min, max)) {
  50256. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  50257. if (distance > currentDistance) {
  50258. distance = currentDistance;
  50259. currentSprite = sprite;
  50260. if (fastCheck) {
  50261. break;
  50262. }
  50263. }
  50264. }
  50265. }
  50266. if (currentSprite) {
  50267. var result = new BABYLON.PickingInfo();
  50268. result.hit = true;
  50269. result.pickedSprite = currentSprite;
  50270. result.distance = distance;
  50271. return result;
  50272. }
  50273. return null;
  50274. };
  50275. SpriteManager.prototype.render = function () {
  50276. // Check
  50277. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  50278. return;
  50279. var engine = this._scene.getEngine();
  50280. var baseSize = this._spriteTexture.getBaseSize();
  50281. // Sprites
  50282. var deltaTime = engine.getDeltaTime();
  50283. var max = Math.min(this._capacity, this.sprites.length);
  50284. var rowSize = baseSize.width / this.cellWidth;
  50285. var offset = 0;
  50286. for (var index = 0; index < max; index++) {
  50287. var sprite = this.sprites[index];
  50288. if (!sprite) {
  50289. continue;
  50290. }
  50291. sprite._animate(deltaTime);
  50292. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  50293. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  50294. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  50295. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  50296. }
  50297. this._buffer.update(this._vertexData);
  50298. // Render
  50299. var effect = this._effectBase;
  50300. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  50301. effect = this._effectFog;
  50302. }
  50303. engine.enableEffect(effect);
  50304. var viewMatrix = this._scene.getViewMatrix();
  50305. effect.setTexture("diffuseSampler", this._spriteTexture);
  50306. effect.setMatrix("view", viewMatrix);
  50307. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  50308. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  50309. // Fog
  50310. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  50311. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  50312. effect.setColor3("vFogColor", this._scene.fogColor);
  50313. }
  50314. // VBOs
  50315. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  50316. // Draw order
  50317. engine.setDepthFunctionToLessOrEqual();
  50318. effect.setBool("alphaTest", true);
  50319. engine.setColorWrite(false);
  50320. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  50321. engine.setColorWrite(true);
  50322. effect.setBool("alphaTest", false);
  50323. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  50324. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  50325. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  50326. };
  50327. SpriteManager.prototype.dispose = function () {
  50328. if (this._buffer) {
  50329. this._buffer.dispose();
  50330. this._buffer = null;
  50331. }
  50332. if (this._indexBuffer) {
  50333. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  50334. this._indexBuffer = null;
  50335. }
  50336. if (this._spriteTexture) {
  50337. this._spriteTexture.dispose();
  50338. this._spriteTexture = null;
  50339. }
  50340. // Remove from scene
  50341. var index = this._scene.spriteManagers.indexOf(this);
  50342. this._scene.spriteManagers.splice(index, 1);
  50343. // Callback
  50344. this.onDisposeObservable.notifyObservers(this);
  50345. this.onDisposeObservable.clear();
  50346. };
  50347. return SpriteManager;
  50348. }());
  50349. BABYLON.SpriteManager = SpriteManager;
  50350. })(BABYLON || (BABYLON = {}));
  50351. //# sourceMappingURL=babylon.spriteManager.js.map
  50352. "use strict";
  50353. var BABYLON;
  50354. (function (BABYLON) {
  50355. var Sprite = /** @class */ (function () {
  50356. function Sprite(name, manager) {
  50357. this.name = name;
  50358. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50359. this.width = 1.0;
  50360. this.height = 1.0;
  50361. this.angle = 0;
  50362. this.cellIndex = 0;
  50363. this.invertU = 0;
  50364. this.invertV = 0;
  50365. this.animations = new Array();
  50366. this.isPickable = false;
  50367. this._animationStarted = false;
  50368. this._loopAnimation = false;
  50369. this._fromIndex = 0;
  50370. this._toIndex = 0;
  50371. this._delay = 0;
  50372. this._direction = 1;
  50373. this._time = 0;
  50374. this._manager = manager;
  50375. this._manager.sprites.push(this);
  50376. this.position = BABYLON.Vector3.Zero();
  50377. }
  50378. Object.defineProperty(Sprite.prototype, "size", {
  50379. get: function () {
  50380. return this.width;
  50381. },
  50382. set: function (value) {
  50383. this.width = value;
  50384. this.height = value;
  50385. },
  50386. enumerable: true,
  50387. configurable: true
  50388. });
  50389. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  50390. this._fromIndex = from;
  50391. this._toIndex = to;
  50392. this._loopAnimation = loop;
  50393. this._delay = delay;
  50394. this._animationStarted = true;
  50395. this._direction = from < to ? 1 : -1;
  50396. this.cellIndex = from;
  50397. this._time = 0;
  50398. this._onAnimationEnd = onAnimationEnd;
  50399. };
  50400. Sprite.prototype.stopAnimation = function () {
  50401. this._animationStarted = false;
  50402. };
  50403. Sprite.prototype._animate = function (deltaTime) {
  50404. if (!this._animationStarted)
  50405. return;
  50406. this._time += deltaTime;
  50407. if (this._time > this._delay) {
  50408. this._time = this._time % this._delay;
  50409. this.cellIndex += this._direction;
  50410. if (this.cellIndex > this._toIndex) {
  50411. if (this._loopAnimation) {
  50412. this.cellIndex = this._fromIndex;
  50413. }
  50414. else {
  50415. this.cellIndex = this._toIndex;
  50416. this._animationStarted = false;
  50417. if (this._onAnimationEnd) {
  50418. this._onAnimationEnd();
  50419. }
  50420. if (this.disposeWhenFinishedAnimating) {
  50421. this.dispose();
  50422. }
  50423. }
  50424. }
  50425. }
  50426. };
  50427. Sprite.prototype.dispose = function () {
  50428. for (var i = 0; i < this._manager.sprites.length; i++) {
  50429. if (this._manager.sprites[i] == this) {
  50430. this._manager.sprites.splice(i, 1);
  50431. }
  50432. }
  50433. };
  50434. return Sprite;
  50435. }());
  50436. BABYLON.Sprite = Sprite;
  50437. })(BABYLON || (BABYLON = {}));
  50438. //# sourceMappingURL=babylon.sprite.js.map
  50439. "use strict";
  50440. var BABYLON;
  50441. (function (BABYLON) {
  50442. var IntersectionInfo = /** @class */ (function () {
  50443. function IntersectionInfo(bu, bv, distance) {
  50444. this.bu = bu;
  50445. this.bv = bv;
  50446. this.distance = distance;
  50447. this.faceId = 0;
  50448. this.subMeshId = 0;
  50449. }
  50450. return IntersectionInfo;
  50451. }());
  50452. BABYLON.IntersectionInfo = IntersectionInfo;
  50453. var PickingInfo = /** @class */ (function () {
  50454. function PickingInfo() {
  50455. this.hit = false;
  50456. this.distance = 0;
  50457. this.pickedPoint = null;
  50458. this.pickedMesh = null;
  50459. this.bu = 0;
  50460. this.bv = 0;
  50461. this.faceId = -1;
  50462. this.subMeshId = 0;
  50463. this.pickedSprite = null;
  50464. }
  50465. // Methods
  50466. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  50467. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  50468. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  50469. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  50470. return null;
  50471. }
  50472. var indices = this.pickedMesh.getIndices();
  50473. if (!indices) {
  50474. return null;
  50475. }
  50476. var result;
  50477. if (useVerticesNormals) {
  50478. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  50479. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  50480. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  50481. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  50482. normal0 = normal0.scale(this.bu);
  50483. normal1 = normal1.scale(this.bv);
  50484. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  50485. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  50486. }
  50487. else {
  50488. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  50489. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  50490. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  50491. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  50492. var p1p2 = vertex1.subtract(vertex2);
  50493. var p3p2 = vertex3.subtract(vertex2);
  50494. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  50495. }
  50496. if (useWorldCoordinates) {
  50497. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  50498. }
  50499. return BABYLON.Vector3.Normalize(result);
  50500. };
  50501. PickingInfo.prototype.getTextureCoordinates = function () {
  50502. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  50503. return null;
  50504. }
  50505. var indices = this.pickedMesh.getIndices();
  50506. if (!indices) {
  50507. return null;
  50508. }
  50509. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  50510. if (!uvs) {
  50511. return null;
  50512. }
  50513. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  50514. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  50515. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  50516. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  50517. uv1 = uv1.scale(this.bu);
  50518. uv2 = uv2.scale(this.bv);
  50519. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  50520. };
  50521. return PickingInfo;
  50522. }());
  50523. BABYLON.PickingInfo = PickingInfo;
  50524. })(BABYLON || (BABYLON = {}));
  50525. //# sourceMappingURL=babylon.pickingInfo.js.map
  50526. "use strict";
  50527. var BABYLON;
  50528. (function (BABYLON) {
  50529. var Ray = /** @class */ (function () {
  50530. function Ray(origin, direction, length) {
  50531. if (length === void 0) { length = Number.MAX_VALUE; }
  50532. this.origin = origin;
  50533. this.direction = direction;
  50534. this.length = length;
  50535. }
  50536. // Methods
  50537. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  50538. var d = 0.0;
  50539. var maxValue = Number.MAX_VALUE;
  50540. var inv;
  50541. var min;
  50542. var max;
  50543. var temp;
  50544. if (Math.abs(this.direction.x) < 0.0000001) {
  50545. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  50546. return false;
  50547. }
  50548. }
  50549. else {
  50550. inv = 1.0 / this.direction.x;
  50551. min = (minimum.x - this.origin.x) * inv;
  50552. max = (maximum.x - this.origin.x) * inv;
  50553. if (max === -Infinity) {
  50554. max = Infinity;
  50555. }
  50556. if (min > max) {
  50557. temp = min;
  50558. min = max;
  50559. max = temp;
  50560. }
  50561. d = Math.max(min, d);
  50562. maxValue = Math.min(max, maxValue);
  50563. if (d > maxValue) {
  50564. return false;
  50565. }
  50566. }
  50567. if (Math.abs(this.direction.y) < 0.0000001) {
  50568. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  50569. return false;
  50570. }
  50571. }
  50572. else {
  50573. inv = 1.0 / this.direction.y;
  50574. min = (minimum.y - this.origin.y) * inv;
  50575. max = (maximum.y - this.origin.y) * inv;
  50576. if (max === -Infinity) {
  50577. max = Infinity;
  50578. }
  50579. if (min > max) {
  50580. temp = min;
  50581. min = max;
  50582. max = temp;
  50583. }
  50584. d = Math.max(min, d);
  50585. maxValue = Math.min(max, maxValue);
  50586. if (d > maxValue) {
  50587. return false;
  50588. }
  50589. }
  50590. if (Math.abs(this.direction.z) < 0.0000001) {
  50591. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  50592. return false;
  50593. }
  50594. }
  50595. else {
  50596. inv = 1.0 / this.direction.z;
  50597. min = (minimum.z - this.origin.z) * inv;
  50598. max = (maximum.z - this.origin.z) * inv;
  50599. if (max === -Infinity) {
  50600. max = Infinity;
  50601. }
  50602. if (min > max) {
  50603. temp = min;
  50604. min = max;
  50605. max = temp;
  50606. }
  50607. d = Math.max(min, d);
  50608. maxValue = Math.min(max, maxValue);
  50609. if (d > maxValue) {
  50610. return false;
  50611. }
  50612. }
  50613. return true;
  50614. };
  50615. Ray.prototype.intersectsBox = function (box) {
  50616. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  50617. };
  50618. Ray.prototype.intersectsSphere = function (sphere) {
  50619. var x = sphere.center.x - this.origin.x;
  50620. var y = sphere.center.y - this.origin.y;
  50621. var z = sphere.center.z - this.origin.z;
  50622. var pyth = (x * x) + (y * y) + (z * z);
  50623. var rr = sphere.radius * sphere.radius;
  50624. if (pyth <= rr) {
  50625. return true;
  50626. }
  50627. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  50628. if (dot < 0.0) {
  50629. return false;
  50630. }
  50631. var temp = pyth - (dot * dot);
  50632. return temp <= rr;
  50633. };
  50634. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  50635. if (!this._edge1) {
  50636. this._edge1 = BABYLON.Vector3.Zero();
  50637. this._edge2 = BABYLON.Vector3.Zero();
  50638. this._pvec = BABYLON.Vector3.Zero();
  50639. this._tvec = BABYLON.Vector3.Zero();
  50640. this._qvec = BABYLON.Vector3.Zero();
  50641. }
  50642. vertex1.subtractToRef(vertex0, this._edge1);
  50643. vertex2.subtractToRef(vertex0, this._edge2);
  50644. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  50645. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  50646. if (det === 0) {
  50647. return null;
  50648. }
  50649. var invdet = 1 / det;
  50650. this.origin.subtractToRef(vertex0, this._tvec);
  50651. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  50652. if (bu < 0 || bu > 1.0) {
  50653. return null;
  50654. }
  50655. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  50656. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  50657. if (bv < 0 || bu + bv > 1.0) {
  50658. return null;
  50659. }
  50660. //check if the distance is longer than the predefined length.
  50661. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  50662. if (distance > this.length) {
  50663. return null;
  50664. }
  50665. return new BABYLON.IntersectionInfo(bu, bv, distance);
  50666. };
  50667. Ray.prototype.intersectsPlane = function (plane) {
  50668. var distance;
  50669. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  50670. if (Math.abs(result1) < 9.99999997475243E-07) {
  50671. return null;
  50672. }
  50673. else {
  50674. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  50675. distance = (-plane.d - result2) / result1;
  50676. if (distance < 0.0) {
  50677. if (distance < -9.99999997475243E-07) {
  50678. return null;
  50679. }
  50680. else {
  50681. return 0;
  50682. }
  50683. }
  50684. return distance;
  50685. }
  50686. };
  50687. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  50688. var tm = BABYLON.Tmp.Matrix[0];
  50689. mesh.getWorldMatrix().invertToRef(tm);
  50690. if (this._tmpRay) {
  50691. Ray.TransformToRef(this, tm, this._tmpRay);
  50692. }
  50693. else {
  50694. this._tmpRay = Ray.Transform(this, tm);
  50695. }
  50696. return mesh.intersects(this._tmpRay, fastCheck);
  50697. };
  50698. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  50699. if (results) {
  50700. results.length = 0;
  50701. }
  50702. else {
  50703. results = [];
  50704. }
  50705. for (var i = 0; i < meshes.length; i++) {
  50706. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  50707. if (pickInfo.hit) {
  50708. results.push(pickInfo);
  50709. }
  50710. }
  50711. results.sort(this._comparePickingInfo);
  50712. return results;
  50713. };
  50714. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  50715. if (pickingInfoA.distance < pickingInfoB.distance) {
  50716. return -1;
  50717. }
  50718. else if (pickingInfoA.distance > pickingInfoB.distance) {
  50719. return 1;
  50720. }
  50721. else {
  50722. return 0;
  50723. }
  50724. };
  50725. /**
  50726. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  50727. * @param sega the first point of the segment to test the intersection against
  50728. * @param segb the second point of the segment to test the intersection against
  50729. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  50730. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  50731. */
  50732. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  50733. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  50734. var u = segb.subtract(sega);
  50735. var v = rsegb.subtract(this.origin);
  50736. var w = sega.subtract(this.origin);
  50737. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  50738. var b = BABYLON.Vector3.Dot(u, v);
  50739. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  50740. var d = BABYLON.Vector3.Dot(u, w);
  50741. var e = BABYLON.Vector3.Dot(v, w);
  50742. var D = a * c - b * b; // always >= 0
  50743. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  50744. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  50745. // compute the line parameters of the two closest points
  50746. if (D < Ray.smallnum) {
  50747. sN = 0.0; // force using point P0 on segment S1
  50748. sD = 1.0; // to prevent possible division by 0.0 later
  50749. tN = e;
  50750. tD = c;
  50751. }
  50752. else {
  50753. sN = (b * e - c * d);
  50754. tN = (a * e - b * d);
  50755. if (sN < 0.0) {
  50756. sN = 0.0;
  50757. tN = e;
  50758. tD = c;
  50759. }
  50760. else if (sN > sD) {
  50761. sN = sD;
  50762. tN = e + b;
  50763. tD = c;
  50764. }
  50765. }
  50766. if (tN < 0.0) {
  50767. tN = 0.0;
  50768. // recompute sc for this edge
  50769. if (-d < 0.0) {
  50770. sN = 0.0;
  50771. }
  50772. else if (-d > a)
  50773. sN = sD;
  50774. else {
  50775. sN = -d;
  50776. sD = a;
  50777. }
  50778. }
  50779. else if (tN > tD) {
  50780. tN = tD;
  50781. // recompute sc for this edge
  50782. if ((-d + b) < 0.0) {
  50783. sN = 0;
  50784. }
  50785. else if ((-d + b) > a) {
  50786. sN = sD;
  50787. }
  50788. else {
  50789. sN = (-d + b);
  50790. sD = a;
  50791. }
  50792. }
  50793. // finally do the division to get sc and tc
  50794. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  50795. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  50796. // get the difference of the two closest points
  50797. var qtc = v.multiplyByFloats(tc, tc, tc);
  50798. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  50799. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  50800. if (isIntersected) {
  50801. return qtc.length();
  50802. }
  50803. return -1;
  50804. };
  50805. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  50806. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  50807. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  50808. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  50809. this.direction.normalize();
  50810. return this;
  50811. };
  50812. // Statics
  50813. Ray.Zero = function () {
  50814. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  50815. };
  50816. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  50817. var result = Ray.Zero();
  50818. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  50819. };
  50820. /**
  50821. * 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
  50822. * transformed to the given world matrix.
  50823. * @param origin The origin point
  50824. * @param end The end point
  50825. * @param world a matrix to transform the ray to. Default is the identity matrix.
  50826. */
  50827. Ray.CreateNewFromTo = function (origin, end, world) {
  50828. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  50829. var direction = end.subtract(origin);
  50830. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  50831. direction.normalize();
  50832. return Ray.Transform(new Ray(origin, direction, length), world);
  50833. };
  50834. Ray.Transform = function (ray, matrix) {
  50835. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  50836. Ray.TransformToRef(ray, matrix, result);
  50837. return result;
  50838. };
  50839. Ray.TransformToRef = function (ray, matrix, result) {
  50840. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  50841. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  50842. result.length = ray.length;
  50843. var dir = result.direction;
  50844. var len = dir.length();
  50845. if (!(len === 0 || len === 1)) {
  50846. var num = 1.0 / len;
  50847. dir.x *= num;
  50848. dir.y *= num;
  50849. dir.z *= num;
  50850. result.length *= len;
  50851. }
  50852. };
  50853. Ray.smallnum = 0.00000001;
  50854. Ray.rayl = 10e8;
  50855. return Ray;
  50856. }());
  50857. BABYLON.Ray = Ray;
  50858. })(BABYLON || (BABYLON = {}));
  50859. //# sourceMappingURL=babylon.ray.js.map
  50860. "use strict";
  50861. var BABYLON;
  50862. (function (BABYLON) {
  50863. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  50864. if (boxMin.x > sphereCenter.x + sphereRadius)
  50865. return false;
  50866. if (sphereCenter.x - sphereRadius > boxMax.x)
  50867. return false;
  50868. if (boxMin.y > sphereCenter.y + sphereRadius)
  50869. return false;
  50870. if (sphereCenter.y - sphereRadius > boxMax.y)
  50871. return false;
  50872. if (boxMin.z > sphereCenter.z + sphereRadius)
  50873. return false;
  50874. if (sphereCenter.z - sphereRadius > boxMax.z)
  50875. return false;
  50876. return true;
  50877. };
  50878. var getLowestRoot = (function () {
  50879. var result = { root: 0, found: false };
  50880. return function (a, b, c, maxR) {
  50881. result.root = 0;
  50882. result.found = false;
  50883. var determinant = b * b - 4.0 * a * c;
  50884. if (determinant < 0)
  50885. return result;
  50886. var sqrtD = Math.sqrt(determinant);
  50887. var r1 = (-b - sqrtD) / (2.0 * a);
  50888. var r2 = (-b + sqrtD) / (2.0 * a);
  50889. if (r1 > r2) {
  50890. var temp = r2;
  50891. r2 = r1;
  50892. r1 = temp;
  50893. }
  50894. if (r1 > 0 && r1 < maxR) {
  50895. result.root = r1;
  50896. result.found = true;
  50897. return result;
  50898. }
  50899. if (r2 > 0 && r2 < maxR) {
  50900. result.root = r2;
  50901. result.found = true;
  50902. return result;
  50903. }
  50904. return result;
  50905. };
  50906. })();
  50907. var Collider = /** @class */ (function () {
  50908. function Collider() {
  50909. this._collisionPoint = BABYLON.Vector3.Zero();
  50910. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  50911. this._tempVector = BABYLON.Vector3.Zero();
  50912. this._tempVector2 = BABYLON.Vector3.Zero();
  50913. this._tempVector3 = BABYLON.Vector3.Zero();
  50914. this._tempVector4 = BABYLON.Vector3.Zero();
  50915. this._edge = BABYLON.Vector3.Zero();
  50916. this._baseToVertex = BABYLON.Vector3.Zero();
  50917. this._destinationPoint = BABYLON.Vector3.Zero();
  50918. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  50919. this._displacementVector = BABYLON.Vector3.Zero();
  50920. this._radius = BABYLON.Vector3.One();
  50921. this._retry = 0;
  50922. this._basePointWorld = BABYLON.Vector3.Zero();
  50923. this._velocityWorld = BABYLON.Vector3.Zero();
  50924. this._normalizedVelocity = BABYLON.Vector3.Zero();
  50925. this._collisionMask = -1;
  50926. }
  50927. Object.defineProperty(Collider.prototype, "collisionMask", {
  50928. get: function () {
  50929. return this._collisionMask;
  50930. },
  50931. set: function (mask) {
  50932. this._collisionMask = !isNaN(mask) ? mask : -1;
  50933. },
  50934. enumerable: true,
  50935. configurable: true
  50936. });
  50937. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  50938. /**
  50939. * Gets the plane normal used to compute the sliding response (in local space)
  50940. */
  50941. get: function () {
  50942. return this._slidePlaneNormal;
  50943. },
  50944. enumerable: true,
  50945. configurable: true
  50946. });
  50947. // Methods
  50948. Collider.prototype._initialize = function (source, dir, e) {
  50949. this._velocity = dir;
  50950. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  50951. this._basePoint = source;
  50952. source.multiplyToRef(this._radius, this._basePointWorld);
  50953. dir.multiplyToRef(this._radius, this._velocityWorld);
  50954. this._velocityWorldLength = this._velocityWorld.length();
  50955. this._epsilon = e;
  50956. this.collisionFound = false;
  50957. };
  50958. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  50959. pa.subtractToRef(point, this._tempVector);
  50960. pb.subtractToRef(point, this._tempVector2);
  50961. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  50962. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  50963. if (d < 0)
  50964. return false;
  50965. pc.subtractToRef(point, this._tempVector3);
  50966. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  50967. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  50968. if (d < 0)
  50969. return false;
  50970. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  50971. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  50972. return d >= 0;
  50973. };
  50974. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  50975. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  50976. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  50977. if (distance > this._velocityWorldLength + max + sphereRadius) {
  50978. return false;
  50979. }
  50980. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  50981. return false;
  50982. return true;
  50983. };
  50984. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  50985. var t0;
  50986. var embeddedInPlane = false;
  50987. //defensive programming, actually not needed.
  50988. if (!trianglePlaneArray) {
  50989. trianglePlaneArray = [];
  50990. }
  50991. if (!trianglePlaneArray[faceIndex]) {
  50992. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  50993. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  50994. }
  50995. var trianglePlane = trianglePlaneArray[faceIndex];
  50996. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  50997. return;
  50998. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  50999. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  51000. if (normalDotVelocity == 0) {
  51001. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  51002. return;
  51003. embeddedInPlane = true;
  51004. t0 = 0;
  51005. }
  51006. else {
  51007. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  51008. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  51009. if (t0 > t1) {
  51010. var temp = t1;
  51011. t1 = t0;
  51012. t0 = temp;
  51013. }
  51014. if (t0 > 1.0 || t1 < 0.0)
  51015. return;
  51016. if (t0 < 0)
  51017. t0 = 0;
  51018. if (t0 > 1.0)
  51019. t0 = 1.0;
  51020. }
  51021. this._collisionPoint.copyFromFloats(0, 0, 0);
  51022. var found = false;
  51023. var t = 1.0;
  51024. if (!embeddedInPlane) {
  51025. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  51026. this._velocity.scaleToRef(t0, this._tempVector);
  51027. this._planeIntersectionPoint.addInPlace(this._tempVector);
  51028. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  51029. found = true;
  51030. t = t0;
  51031. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  51032. }
  51033. }
  51034. if (!found) {
  51035. var velocitySquaredLength = this._velocity.lengthSquared();
  51036. var a = velocitySquaredLength;
  51037. this._basePoint.subtractToRef(p1, this._tempVector);
  51038. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  51039. var c = this._tempVector.lengthSquared() - 1.0;
  51040. var lowestRoot = getLowestRoot(a, b, c, t);
  51041. if (lowestRoot.found) {
  51042. t = lowestRoot.root;
  51043. found = true;
  51044. this._collisionPoint.copyFrom(p1);
  51045. }
  51046. this._basePoint.subtractToRef(p2, this._tempVector);
  51047. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  51048. c = this._tempVector.lengthSquared() - 1.0;
  51049. lowestRoot = getLowestRoot(a, b, c, t);
  51050. if (lowestRoot.found) {
  51051. t = lowestRoot.root;
  51052. found = true;
  51053. this._collisionPoint.copyFrom(p2);
  51054. }
  51055. this._basePoint.subtractToRef(p3, this._tempVector);
  51056. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  51057. c = this._tempVector.lengthSquared() - 1.0;
  51058. lowestRoot = getLowestRoot(a, b, c, t);
  51059. if (lowestRoot.found) {
  51060. t = lowestRoot.root;
  51061. found = true;
  51062. this._collisionPoint.copyFrom(p3);
  51063. }
  51064. p2.subtractToRef(p1, this._edge);
  51065. p1.subtractToRef(this._basePoint, this._baseToVertex);
  51066. var edgeSquaredLength = this._edge.lengthSquared();
  51067. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  51068. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  51069. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  51070. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  51071. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  51072. lowestRoot = getLowestRoot(a, b, c, t);
  51073. if (lowestRoot.found) {
  51074. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  51075. if (f >= 0.0 && f <= 1.0) {
  51076. t = lowestRoot.root;
  51077. found = true;
  51078. this._edge.scaleInPlace(f);
  51079. p1.addToRef(this._edge, this._collisionPoint);
  51080. }
  51081. }
  51082. p3.subtractToRef(p2, this._edge);
  51083. p2.subtractToRef(this._basePoint, this._baseToVertex);
  51084. edgeSquaredLength = this._edge.lengthSquared();
  51085. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  51086. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  51087. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  51088. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  51089. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  51090. lowestRoot = getLowestRoot(a, b, c, t);
  51091. if (lowestRoot.found) {
  51092. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  51093. if (f >= 0.0 && f <= 1.0) {
  51094. t = lowestRoot.root;
  51095. found = true;
  51096. this._edge.scaleInPlace(f);
  51097. p2.addToRef(this._edge, this._collisionPoint);
  51098. }
  51099. }
  51100. p1.subtractToRef(p3, this._edge);
  51101. p3.subtractToRef(this._basePoint, this._baseToVertex);
  51102. edgeSquaredLength = this._edge.lengthSquared();
  51103. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  51104. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  51105. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  51106. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  51107. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  51108. lowestRoot = getLowestRoot(a, b, c, t);
  51109. if (lowestRoot.found) {
  51110. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  51111. if (f >= 0.0 && f <= 1.0) {
  51112. t = lowestRoot.root;
  51113. found = true;
  51114. this._edge.scaleInPlace(f);
  51115. p3.addToRef(this._edge, this._collisionPoint);
  51116. }
  51117. }
  51118. }
  51119. if (found) {
  51120. var distToCollision = t * this._velocity.length();
  51121. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  51122. if (!this.intersectionPoint) {
  51123. this.intersectionPoint = this._collisionPoint.clone();
  51124. }
  51125. else {
  51126. this.intersectionPoint.copyFrom(this._collisionPoint);
  51127. }
  51128. this._nearestDistance = distToCollision;
  51129. this.collisionFound = true;
  51130. }
  51131. }
  51132. };
  51133. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  51134. for (var i = indexStart; i < indexEnd; i += 3) {
  51135. var p1 = pts[indices[i] - decal];
  51136. var p2 = pts[indices[i + 1] - decal];
  51137. var p3 = pts[indices[i + 2] - decal];
  51138. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  51139. }
  51140. };
  51141. Collider.prototype._getResponse = function (pos, vel) {
  51142. pos.addToRef(vel, this._destinationPoint);
  51143. vel.scaleInPlace((this._nearestDistance / vel.length()));
  51144. this._basePoint.addToRef(vel, pos);
  51145. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  51146. this._slidePlaneNormal.normalize();
  51147. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  51148. pos.addInPlace(this._displacementVector);
  51149. this.intersectionPoint.addInPlace(this._displacementVector);
  51150. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  51151. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  51152. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  51153. };
  51154. return Collider;
  51155. }());
  51156. BABYLON.Collider = Collider;
  51157. })(BABYLON || (BABYLON = {}));
  51158. //# sourceMappingURL=babylon.collider.js.map
  51159. "use strict";
  51160. var BABYLON;
  51161. (function (BABYLON) {
  51162. //WebWorker code will be inserted to this variable.
  51163. BABYLON.CollisionWorker = "";
  51164. var WorkerTaskType;
  51165. (function (WorkerTaskType) {
  51166. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  51167. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  51168. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  51169. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  51170. var WorkerReplyType;
  51171. (function (WorkerReplyType) {
  51172. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  51173. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  51174. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  51175. var CollisionCoordinatorWorker = /** @class */ (function () {
  51176. function CollisionCoordinatorWorker() {
  51177. var _this = this;
  51178. this._scaledPosition = BABYLON.Vector3.Zero();
  51179. this._scaledVelocity = BABYLON.Vector3.Zero();
  51180. this.onMeshUpdated = function (transformNode) {
  51181. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  51182. };
  51183. this.onGeometryUpdated = function (geometry) {
  51184. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  51185. };
  51186. this._afterRender = function () {
  51187. if (!_this._init)
  51188. return;
  51189. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  51190. return;
  51191. }
  51192. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  51193. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  51194. if (_this._runningUpdated > 4) {
  51195. return;
  51196. }
  51197. ++_this._runningUpdated;
  51198. var payload = {
  51199. updatedMeshes: _this._addUpdateMeshesList,
  51200. updatedGeometries: _this._addUpdateGeometriesList,
  51201. removedGeometries: _this._toRemoveGeometryArray,
  51202. removedMeshes: _this._toRemoveMeshesArray
  51203. };
  51204. var message = {
  51205. payload: payload,
  51206. taskType: WorkerTaskType.UPDATE
  51207. };
  51208. var serializable = [];
  51209. for (var id in payload.updatedGeometries) {
  51210. if (payload.updatedGeometries.hasOwnProperty(id)) {
  51211. //prepare transferables
  51212. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  51213. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  51214. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  51215. }
  51216. }
  51217. _this._worker.postMessage(message, serializable);
  51218. _this._addUpdateMeshesList = {};
  51219. _this._addUpdateGeometriesList = {};
  51220. _this._toRemoveGeometryArray = [];
  51221. _this._toRemoveMeshesArray = [];
  51222. };
  51223. this._onMessageFromWorker = function (e) {
  51224. var returnData = e.data;
  51225. if (returnData.error != WorkerReplyType.SUCCESS) {
  51226. //TODO what errors can be returned from the worker?
  51227. BABYLON.Tools.Warn("error returned from worker!");
  51228. return;
  51229. }
  51230. switch (returnData.taskType) {
  51231. case WorkerTaskType.INIT:
  51232. _this._init = true;
  51233. //Update the worked with ALL of the scene's current state
  51234. _this._scene.meshes.forEach(function (mesh) {
  51235. _this.onMeshAdded(mesh);
  51236. });
  51237. _this._scene.getGeometries().forEach(function (geometry) {
  51238. _this.onGeometryAdded(geometry);
  51239. });
  51240. break;
  51241. case WorkerTaskType.UPDATE:
  51242. _this._runningUpdated--;
  51243. break;
  51244. case WorkerTaskType.COLLIDE:
  51245. var returnPayload = returnData.payload;
  51246. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  51247. return;
  51248. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  51249. if (callback) {
  51250. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  51251. if (mesh) {
  51252. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  51253. }
  51254. }
  51255. //cleanup
  51256. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  51257. break;
  51258. }
  51259. };
  51260. this._collisionsCallbackArray = [];
  51261. this._init = false;
  51262. this._runningUpdated = 0;
  51263. this._addUpdateMeshesList = {};
  51264. this._addUpdateGeometriesList = {};
  51265. this._toRemoveGeometryArray = [];
  51266. this._toRemoveMeshesArray = [];
  51267. }
  51268. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  51269. if (!this._init)
  51270. return;
  51271. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  51272. return;
  51273. position.divideToRef(collider._radius, this._scaledPosition);
  51274. displacement.divideToRef(collider._radius, this._scaledVelocity);
  51275. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  51276. var payload = {
  51277. collider: {
  51278. position: this._scaledPosition.asArray(),
  51279. velocity: this._scaledVelocity.asArray(),
  51280. radius: collider._radius.asArray()
  51281. },
  51282. collisionId: collisionIndex,
  51283. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  51284. maximumRetry: maximumRetry
  51285. };
  51286. var message = {
  51287. payload: payload,
  51288. taskType: WorkerTaskType.COLLIDE
  51289. };
  51290. this._worker.postMessage(message);
  51291. };
  51292. CollisionCoordinatorWorker.prototype.init = function (scene) {
  51293. this._scene = scene;
  51294. this._scene.registerAfterRender(this._afterRender);
  51295. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  51296. this._worker = new Worker(workerUrl);
  51297. this._worker.onmessage = this._onMessageFromWorker;
  51298. var message = {
  51299. payload: {},
  51300. taskType: WorkerTaskType.INIT
  51301. };
  51302. this._worker.postMessage(message);
  51303. };
  51304. CollisionCoordinatorWorker.prototype.destroy = function () {
  51305. this._scene.unregisterAfterRender(this._afterRender);
  51306. this._worker.terminate();
  51307. };
  51308. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  51309. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  51310. this.onMeshUpdated(mesh);
  51311. };
  51312. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  51313. this._toRemoveMeshesArray.push(mesh.uniqueId);
  51314. };
  51315. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  51316. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  51317. geometry.onGeometryUpdated = this.onGeometryUpdated;
  51318. this.onGeometryUpdated(geometry);
  51319. };
  51320. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  51321. this._toRemoveGeometryArray.push(geometry.id);
  51322. };
  51323. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  51324. var submeshes = [];
  51325. if (mesh.subMeshes) {
  51326. submeshes = mesh.subMeshes.map(function (sm, idx) {
  51327. var boundingInfo = sm.getBoundingInfo();
  51328. return {
  51329. position: idx,
  51330. verticesStart: sm.verticesStart,
  51331. verticesCount: sm.verticesCount,
  51332. indexStart: sm.indexStart,
  51333. indexCount: sm.indexCount,
  51334. hasMaterial: !!sm.getMaterial(),
  51335. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  51336. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  51337. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  51338. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  51339. };
  51340. });
  51341. }
  51342. var geometryId = null;
  51343. if (mesh instanceof BABYLON.Mesh) {
  51344. var geometry = mesh.geometry;
  51345. geometryId = geometry ? geometry.id : null;
  51346. }
  51347. else if (mesh instanceof BABYLON.InstancedMesh) {
  51348. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  51349. geometryId = geometry ? geometry.id : null;
  51350. }
  51351. var boundingInfo = mesh.getBoundingInfo();
  51352. return {
  51353. uniqueId: mesh.uniqueId,
  51354. id: mesh.id,
  51355. name: mesh.name,
  51356. geometryId: geometryId,
  51357. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  51358. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  51359. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  51360. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  51361. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  51362. subMeshes: submeshes,
  51363. checkCollisions: mesh.checkCollisions
  51364. };
  51365. };
  51366. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  51367. return {
  51368. id: geometry.id,
  51369. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  51370. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  51371. indices: new Uint32Array(geometry.getIndices() || []),
  51372. };
  51373. };
  51374. return CollisionCoordinatorWorker;
  51375. }());
  51376. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  51377. var CollisionCoordinatorLegacy = /** @class */ (function () {
  51378. function CollisionCoordinatorLegacy() {
  51379. this._scaledPosition = BABYLON.Vector3.Zero();
  51380. this._scaledVelocity = BABYLON.Vector3.Zero();
  51381. this._finalPosition = BABYLON.Vector3.Zero();
  51382. }
  51383. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  51384. position.divideToRef(collider._radius, this._scaledPosition);
  51385. displacement.divideToRef(collider._radius, this._scaledVelocity);
  51386. collider.collidedMesh = null;
  51387. collider._retry = 0;
  51388. collider._initialVelocity = this._scaledVelocity;
  51389. collider._initialPosition = this._scaledPosition;
  51390. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  51391. this._finalPosition.multiplyInPlace(collider._radius);
  51392. //run the callback
  51393. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  51394. };
  51395. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  51396. this._scene = scene;
  51397. };
  51398. CollisionCoordinatorLegacy.prototype.destroy = function () {
  51399. //Legacy need no destruction method.
  51400. };
  51401. //No update in legacy mode
  51402. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  51403. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  51404. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  51405. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  51406. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  51407. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  51408. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  51409. if (excludedMesh === void 0) { excludedMesh = null; }
  51410. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  51411. if (collider._retry >= maximumRetry) {
  51412. finalPosition.copyFrom(position);
  51413. return;
  51414. }
  51415. // Check if this is a mesh else camera or -1
  51416. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  51417. collider._initialize(position, velocity, closeDistance);
  51418. // Check all meshes
  51419. for (var index = 0; index < this._scene.meshes.length; index++) {
  51420. var mesh = this._scene.meshes[index];
  51421. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  51422. mesh._checkCollision(collider);
  51423. }
  51424. }
  51425. if (!collider.collisionFound) {
  51426. position.addToRef(velocity, finalPosition);
  51427. return;
  51428. }
  51429. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  51430. collider._getResponse(position, velocity);
  51431. }
  51432. if (velocity.length() <= closeDistance) {
  51433. finalPosition.copyFrom(position);
  51434. return;
  51435. }
  51436. collider._retry++;
  51437. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  51438. };
  51439. return CollisionCoordinatorLegacy;
  51440. }());
  51441. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  51442. })(BABYLON || (BABYLON = {}));
  51443. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  51444. "use strict";
  51445. var BABYLON;
  51446. (function (BABYLON) {
  51447. /**
  51448. * A particle represents one of the element emitted by a particle system.
  51449. * This is mainly define by its coordinates, direction, velocity and age.
  51450. */
  51451. var Particle = /** @class */ (function () {
  51452. /**
  51453. * Creates a new instance of @see Particle
  51454. * @param particleSystem the particle system the particle belongs to
  51455. */
  51456. function Particle(
  51457. /**
  51458. * particleSystem the particle system the particle belongs to.
  51459. */
  51460. particleSystem) {
  51461. this.particleSystem = particleSystem;
  51462. /**
  51463. * The world position of the particle in the scene.
  51464. */
  51465. this.position = BABYLON.Vector3.Zero();
  51466. /**
  51467. * The world direction of the particle in the scene.
  51468. */
  51469. this.direction = BABYLON.Vector3.Zero();
  51470. /**
  51471. * The color of the particle.
  51472. */
  51473. this.color = new BABYLON.Color4(0, 0, 0, 0);
  51474. /**
  51475. * The color change of the particle per step.
  51476. */
  51477. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  51478. /**
  51479. * Defines how long will the life of the particle be.
  51480. */
  51481. this.lifeTime = 1.0;
  51482. /**
  51483. * The current age of the particle.
  51484. */
  51485. this.age = 0;
  51486. /**
  51487. * The current size of the particle.
  51488. */
  51489. this.size = 0;
  51490. /**
  51491. * The current angle of the particle.
  51492. */
  51493. this.angle = 0;
  51494. /**
  51495. * Defines how fast is the angle changing.
  51496. */
  51497. this.angularSpeed = 0;
  51498. /**
  51499. * Defines the cell index used by the particle to be rendered from a sprite.
  51500. */
  51501. this.cellIndex = 0;
  51502. this._currentFrameCounter = 0;
  51503. if (!this.particleSystem.isAnimationSheetEnabled) {
  51504. return;
  51505. }
  51506. this.updateCellInfoFromSystem();
  51507. }
  51508. Particle.prototype.updateCellInfoFromSystem = function () {
  51509. this.cellIndex = this.particleSystem.startSpriteCellID;
  51510. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  51511. this.updateCellIndex = this._updateCellIndexWithSpeedCalculated;
  51512. }
  51513. else {
  51514. this.updateCellIndex = this._updateCellIndexWithCustomSpeed;
  51515. }
  51516. };
  51517. Particle.prototype._updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  51518. // (ageOffset / scaledUpdateSpeed) / available cells
  51519. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  51520. this._currentFrameCounter += scaledUpdateSpeed;
  51521. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  51522. this._currentFrameCounter = 0;
  51523. this.cellIndex++;
  51524. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  51525. this.cellIndex = this.particleSystem.endSpriteCellID;
  51526. }
  51527. }
  51528. };
  51529. Particle.prototype._updateCellIndexWithCustomSpeed = function () {
  51530. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  51531. this.cellIndex++;
  51532. this._currentFrameCounter = 0;
  51533. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  51534. if (this.particleSystem.spriteCellLoop) {
  51535. this.cellIndex = this.particleSystem.startSpriteCellID;
  51536. }
  51537. else {
  51538. this.cellIndex = this.particleSystem.endSpriteCellID;
  51539. }
  51540. }
  51541. }
  51542. else {
  51543. this._currentFrameCounter++;
  51544. }
  51545. };
  51546. /**
  51547. * Copy the properties of particle to another one.
  51548. * @param other the particle to copy the information to.
  51549. */
  51550. Particle.prototype.copyTo = function (other) {
  51551. other.position.copyFrom(this.position);
  51552. other.direction.copyFrom(this.direction);
  51553. other.color.copyFrom(this.color);
  51554. other.colorStep.copyFrom(this.colorStep);
  51555. other.lifeTime = this.lifeTime;
  51556. other.age = this.age;
  51557. other.size = this.size;
  51558. other.angle = this.angle;
  51559. other.angularSpeed = this.angularSpeed;
  51560. other.particleSystem = this.particleSystem;
  51561. other.cellIndex = this.cellIndex;
  51562. };
  51563. return Particle;
  51564. }());
  51565. BABYLON.Particle = Particle;
  51566. })(BABYLON || (BABYLON = {}));
  51567. //# sourceMappingURL=babylon.particle.js.map
  51568. "use strict";
  51569. var BABYLON;
  51570. (function (BABYLON) {
  51571. /**
  51572. * This represents a particle system in Babylon.
  51573. * 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.
  51574. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  51575. * @example https://doc.babylonjs.com/babylon101/particles
  51576. */
  51577. var ParticleSystem = /** @class */ (function () {
  51578. /**
  51579. * Instantiates a particle system.
  51580. * 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.
  51581. * @param name The name of the particle system
  51582. * @param capacity The max number of particles alive at the same time
  51583. * @param scene The scene the particle system belongs to
  51584. * @param customEffect a custom effect used to change the way particles are rendered by default
  51585. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  51586. * @param epsilon Offset used to render the particles
  51587. */
  51588. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  51589. if (customEffect === void 0) { customEffect = null; }
  51590. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  51591. if (epsilon === void 0) { epsilon = 0.01; }
  51592. var _this = this;
  51593. /**
  51594. * List of animations used by the particle system.
  51595. */
  51596. this.animations = [];
  51597. /**
  51598. * The rendering group used by the Particle system to chose when to render.
  51599. */
  51600. this.renderingGroupId = 0;
  51601. /**
  51602. * The emitter represents the Mesh or position we are attaching the particle system to.
  51603. */
  51604. this.emitter = null;
  51605. /**
  51606. * The maximum number of particles to emit per frame
  51607. */
  51608. this.emitRate = 10;
  51609. /**
  51610. * If you want to launch only a few particles at once, that can be done, as well.
  51611. */
  51612. this.manualEmitCount = -1;
  51613. /**
  51614. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  51615. */
  51616. this.updateSpeed = 0.01;
  51617. /**
  51618. * The amount of time the particle system is running (depends of the overall update speed).
  51619. */
  51620. this.targetStopDuration = 0;
  51621. /**
  51622. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  51623. */
  51624. this.disposeOnStop = false;
  51625. /**
  51626. * Minimum power of emitting particles.
  51627. */
  51628. this.minEmitPower = 1;
  51629. /**
  51630. * Maximum power of emitting particles.
  51631. */
  51632. this.maxEmitPower = 1;
  51633. /**
  51634. * Minimum life time of emitting particles.
  51635. */
  51636. this.minLifeTime = 1;
  51637. /**
  51638. * Maximum life time of emitting particles.
  51639. */
  51640. this.maxLifeTime = 1;
  51641. /**
  51642. * Minimum Size of emitting particles.
  51643. */
  51644. this.minSize = 1;
  51645. /**
  51646. * Maximum Size of emitting particles.
  51647. */
  51648. this.maxSize = 1;
  51649. /**
  51650. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  51651. */
  51652. this.minAngularSpeed = 0;
  51653. /**
  51654. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  51655. */
  51656. this.maxAngularSpeed = 0;
  51657. /**
  51658. * The layer mask we are rendering the particles through.
  51659. */
  51660. this.layerMask = 0x0FFFFFFF;
  51661. /**
  51662. * This can help using your own shader to render the particle system.
  51663. * The according effect will be created
  51664. */
  51665. this.customShader = null;
  51666. /**
  51667. * By default particle system starts as soon as they are created. This prevents the
  51668. * automatic start to happen and let you decide when to start emitting particles.
  51669. */
  51670. this.preventAutoStart = false;
  51671. /**
  51672. * Callback triggered when the particle animation is ending.
  51673. */
  51674. this.onAnimationEnd = null;
  51675. /**
  51676. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  51677. */
  51678. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  51679. /**
  51680. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  51681. * to override the particles.
  51682. */
  51683. this.forceDepthWrite = false;
  51684. /**
  51685. * You can use gravity if you want to give an orientation to your particles.
  51686. */
  51687. this.gravity = BABYLON.Vector3.Zero();
  51688. /**
  51689. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  51690. */
  51691. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  51692. /**
  51693. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  51694. */
  51695. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  51696. /**
  51697. * Color the particle will have at the end of its lifetime.
  51698. */
  51699. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  51700. /**
  51701. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  51702. */
  51703. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  51704. /**
  51705. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  51706. */
  51707. this.spriteCellLoop = true;
  51708. /**
  51709. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  51710. */
  51711. this.spriteCellChangeSpeed = 0;
  51712. /**
  51713. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  51714. */
  51715. this.startSpriteCellID = 0;
  51716. /**
  51717. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  51718. */
  51719. this.endSpriteCellID = 0;
  51720. /**
  51721. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  51722. */
  51723. this.spriteCellWidth = 0;
  51724. /**
  51725. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  51726. */
  51727. this.spriteCellHeight = 0;
  51728. /**
  51729. * An event triggered when the system is disposed.
  51730. */
  51731. this.onDisposeObservable = new BABYLON.Observable();
  51732. this._particles = new Array();
  51733. this._stockParticles = new Array();
  51734. this._newPartsExcess = 0;
  51735. this._vertexBuffers = {};
  51736. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  51737. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  51738. this._scaledDirection = BABYLON.Vector3.Zero();
  51739. this._scaledGravity = BABYLON.Vector3.Zero();
  51740. this._currentRenderId = -1;
  51741. this._started = false;
  51742. this._stopped = false;
  51743. this._actualFrame = 0;
  51744. this._vertexBufferSize = 11;
  51745. // start of sub system methods
  51746. /**
  51747. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  51748. * Its lifetime will start back at 0.
  51749. */
  51750. this.recycleParticle = function (particle) {
  51751. var lastParticle = _this._particles.pop();
  51752. if (lastParticle !== particle) {
  51753. lastParticle.copyTo(particle);
  51754. }
  51755. _this._stockParticles.push(lastParticle);
  51756. };
  51757. this._createParticle = function () {
  51758. var particle;
  51759. if (_this._stockParticles.length !== 0) {
  51760. particle = _this._stockParticles.pop();
  51761. particle.age = 0;
  51762. particle.cellIndex = _this.startSpriteCellID;
  51763. }
  51764. else {
  51765. particle = new BABYLON.Particle(_this);
  51766. }
  51767. return particle;
  51768. };
  51769. this._emitFromParticle = function (particle) {
  51770. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  51771. return;
  51772. }
  51773. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  51774. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  51775. subSystem._rootParticleSystem = _this;
  51776. _this.activeSubSystems.push(subSystem);
  51777. subSystem.start();
  51778. };
  51779. this._appendParticleVertexes = null;
  51780. this.id = name;
  51781. this.name = name;
  51782. this._capacity = capacity;
  51783. this._epsilon = epsilon;
  51784. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  51785. if (isAnimationSheetEnabled) {
  51786. this._vertexBufferSize = 12;
  51787. }
  51788. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  51789. this._customEffect = customEffect;
  51790. scene.particleSystems.push(this);
  51791. this._createIndexBuffer();
  51792. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  51793. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  51794. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  51795. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  51796. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  51797. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  51798. if (this._isAnimationSheetEnabled) {
  51799. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  51800. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  51801. }
  51802. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  51803. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  51804. this._vertexBuffers["options"] = options;
  51805. // Default emitter type
  51806. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  51807. this.updateFunction = function (particles) {
  51808. for (var index = 0; index < particles.length; index++) {
  51809. var particle = particles[index];
  51810. particle.age += _this._scaledUpdateSpeed;
  51811. if (particle.age >= particle.lifeTime) {
  51812. _this._emitFromParticle(particle);
  51813. _this.recycleParticle(particle);
  51814. index--;
  51815. continue;
  51816. }
  51817. else {
  51818. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  51819. particle.color.addInPlace(_this._scaledColorStep);
  51820. if (particle.color.a < 0)
  51821. particle.color.a = 0;
  51822. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  51823. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  51824. particle.position.addInPlace(_this._scaledDirection);
  51825. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  51826. particle.direction.addInPlace(_this._scaledGravity);
  51827. if (_this._isAnimationSheetEnabled) {
  51828. particle.updateCellIndex(_this._scaledUpdateSpeed);
  51829. }
  51830. }
  51831. }
  51832. };
  51833. }
  51834. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  51835. /**
  51836. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51837. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51838. */
  51839. get: function () {
  51840. if (this.particleEmitterType.direction1) {
  51841. return this.particleEmitterType.direction1;
  51842. }
  51843. return BABYLON.Vector3.Zero();
  51844. },
  51845. set: function (value) {
  51846. if (this.particleEmitterType.direction1) {
  51847. this.particleEmitterType.direction1 = value;
  51848. }
  51849. },
  51850. enumerable: true,
  51851. configurable: true
  51852. });
  51853. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  51854. /**
  51855. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51856. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51857. */
  51858. get: function () {
  51859. if (this.particleEmitterType.direction2) {
  51860. return this.particleEmitterType.direction2;
  51861. }
  51862. return BABYLON.Vector3.Zero();
  51863. },
  51864. set: function (value) {
  51865. if (this.particleEmitterType.direction2) {
  51866. this.particleEmitterType.direction2 = value;
  51867. }
  51868. },
  51869. enumerable: true,
  51870. configurable: true
  51871. });
  51872. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  51873. /**
  51874. * 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.
  51875. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51876. */
  51877. get: function () {
  51878. if (this.particleEmitterType.minEmitBox) {
  51879. return this.particleEmitterType.minEmitBox;
  51880. }
  51881. return BABYLON.Vector3.Zero();
  51882. },
  51883. set: function (value) {
  51884. if (this.particleEmitterType.minEmitBox) {
  51885. this.particleEmitterType.minEmitBox = value;
  51886. }
  51887. },
  51888. enumerable: true,
  51889. configurable: true
  51890. });
  51891. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  51892. /**
  51893. * 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.
  51894. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51895. */
  51896. get: function () {
  51897. if (this.particleEmitterType.maxEmitBox) {
  51898. return this.particleEmitterType.maxEmitBox;
  51899. }
  51900. return BABYLON.Vector3.Zero();
  51901. },
  51902. set: function (value) {
  51903. if (this.particleEmitterType.maxEmitBox) {
  51904. this.particleEmitterType.maxEmitBox = value;
  51905. }
  51906. },
  51907. enumerable: true,
  51908. configurable: true
  51909. });
  51910. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  51911. /**
  51912. * Sets a callback that will be triggered when the system is disposed.
  51913. */
  51914. set: function (callback) {
  51915. if (this._onDisposeObserver) {
  51916. this.onDisposeObservable.remove(this._onDisposeObserver);
  51917. }
  51918. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  51919. },
  51920. enumerable: true,
  51921. configurable: true
  51922. });
  51923. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  51924. /**
  51925. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  51926. */
  51927. get: function () {
  51928. return this._isAnimationSheetEnabled;
  51929. },
  51930. enumerable: true,
  51931. configurable: true
  51932. });
  51933. Object.defineProperty(ParticleSystem.prototype, "particles", {
  51934. //end of Sub-emitter
  51935. /**
  51936. * Gets the current list of active particles
  51937. */
  51938. get: function () {
  51939. return this._particles;
  51940. },
  51941. enumerable: true,
  51942. configurable: true
  51943. });
  51944. /**
  51945. * Returns the string "ParticleSystem"
  51946. * @returns a string containing the class name
  51947. */
  51948. ParticleSystem.prototype.getClassName = function () {
  51949. return "ParticleSystem";
  51950. };
  51951. ParticleSystem.prototype._createIndexBuffer = function () {
  51952. var indices = [];
  51953. var index = 0;
  51954. for (var count = 0; count < this._capacity; count++) {
  51955. indices.push(index);
  51956. indices.push(index + 1);
  51957. indices.push(index + 2);
  51958. indices.push(index);
  51959. indices.push(index + 2);
  51960. indices.push(index + 3);
  51961. index += 4;
  51962. }
  51963. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  51964. };
  51965. /**
  51966. * Gets the maximum number of particles active at the same time.
  51967. * @returns The max number of active particles.
  51968. */
  51969. ParticleSystem.prototype.getCapacity = function () {
  51970. return this._capacity;
  51971. };
  51972. /**
  51973. * Gets Wether there are still active particles in the system.
  51974. * @returns True if it is alive, otherwise false.
  51975. */
  51976. ParticleSystem.prototype.isAlive = function () {
  51977. return this._alive;
  51978. };
  51979. /**
  51980. * Gets Wether the system has been started.
  51981. * @returns True if it has been started, otherwise false.
  51982. */
  51983. ParticleSystem.prototype.isStarted = function () {
  51984. return this._started;
  51985. };
  51986. /**
  51987. * Starts the particle system and begins to emit.
  51988. */
  51989. ParticleSystem.prototype.start = function () {
  51990. this._started = true;
  51991. this._stopped = false;
  51992. this._actualFrame = 0;
  51993. if (this.subEmitters && this.subEmitters.length != 0) {
  51994. this.activeSubSystems = new Array();
  51995. }
  51996. };
  51997. /**
  51998. * Stops the particle system.
  51999. * @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.
  52000. */
  52001. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  52002. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  52003. this._stopped = true;
  52004. if (stopSubEmitters) {
  52005. this._stopSubEmitters();
  52006. }
  52007. };
  52008. // animation sheet
  52009. /**
  52010. * Remove all active particles
  52011. */
  52012. ParticleSystem.prototype.reset = function () {
  52013. this._stockParticles = [];
  52014. this._particles = [];
  52015. };
  52016. /**
  52017. * @ignore (for internal use only)
  52018. */
  52019. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  52020. var offset = index * this._vertexBufferSize;
  52021. this._vertexData[offset] = particle.position.x;
  52022. this._vertexData[offset + 1] = particle.position.y;
  52023. this._vertexData[offset + 2] = particle.position.z;
  52024. this._vertexData[offset + 3] = particle.color.r;
  52025. this._vertexData[offset + 4] = particle.color.g;
  52026. this._vertexData[offset + 5] = particle.color.b;
  52027. this._vertexData[offset + 6] = particle.color.a;
  52028. this._vertexData[offset + 7] = particle.angle;
  52029. this._vertexData[offset + 8] = particle.size;
  52030. this._vertexData[offset + 9] = offsetX;
  52031. this._vertexData[offset + 10] = offsetY;
  52032. };
  52033. /**
  52034. * @ignore (for internal use only)
  52035. */
  52036. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  52037. if (offsetX === 0)
  52038. offsetX = this._epsilon;
  52039. else if (offsetX === 1)
  52040. offsetX = 1 - this._epsilon;
  52041. if (offsetY === 0)
  52042. offsetY = this._epsilon;
  52043. else if (offsetY === 1)
  52044. offsetY = 1 - this._epsilon;
  52045. var offset = index * this._vertexBufferSize;
  52046. this._vertexData[offset] = particle.position.x;
  52047. this._vertexData[offset + 1] = particle.position.y;
  52048. this._vertexData[offset + 2] = particle.position.z;
  52049. this._vertexData[offset + 3] = particle.color.r;
  52050. this._vertexData[offset + 4] = particle.color.g;
  52051. this._vertexData[offset + 5] = particle.color.b;
  52052. this._vertexData[offset + 6] = particle.color.a;
  52053. this._vertexData[offset + 7] = particle.angle;
  52054. this._vertexData[offset + 8] = particle.size;
  52055. this._vertexData[offset + 9] = offsetX;
  52056. this._vertexData[offset + 10] = offsetY;
  52057. this._vertexData[offset + 11] = particle.cellIndex;
  52058. };
  52059. ParticleSystem.prototype._stopSubEmitters = function () {
  52060. if (!this.activeSubSystems) {
  52061. return;
  52062. }
  52063. this.activeSubSystems.forEach(function (subSystem) {
  52064. subSystem.stop(true);
  52065. });
  52066. this.activeSubSystems = new Array();
  52067. };
  52068. ParticleSystem.prototype._removeFromRoot = function () {
  52069. if (!this._rootParticleSystem) {
  52070. return;
  52071. }
  52072. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  52073. if (index !== -1) {
  52074. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  52075. }
  52076. };
  52077. // end of sub system methods
  52078. ParticleSystem.prototype._update = function (newParticles) {
  52079. // Update current
  52080. this._alive = this._particles.length > 0;
  52081. this.updateFunction(this._particles);
  52082. // Add new ones
  52083. var worldMatrix;
  52084. if (this.emitter.position) {
  52085. var emitterMesh = this.emitter;
  52086. worldMatrix = emitterMesh.getWorldMatrix();
  52087. }
  52088. else {
  52089. var emitterPosition = this.emitter;
  52090. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  52091. }
  52092. var particle;
  52093. for (var index = 0; index < newParticles; index++) {
  52094. if (this._particles.length === this._capacity) {
  52095. break;
  52096. }
  52097. particle = this._createParticle();
  52098. this._particles.push(particle);
  52099. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  52100. if (this.startPositionFunction) {
  52101. this.startPositionFunction(worldMatrix, particle.position, particle);
  52102. }
  52103. else {
  52104. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  52105. }
  52106. if (this.startDirectionFunction) {
  52107. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  52108. }
  52109. else {
  52110. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  52111. }
  52112. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  52113. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  52114. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  52115. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  52116. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  52117. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  52118. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  52119. }
  52120. };
  52121. ParticleSystem.prototype._getEffect = function () {
  52122. if (this._customEffect) {
  52123. return this._customEffect;
  52124. }
  52125. ;
  52126. var defines = [];
  52127. if (this._scene.clipPlane) {
  52128. defines.push("#define CLIPPLANE");
  52129. }
  52130. if (this._isAnimationSheetEnabled) {
  52131. defines.push("#define ANIMATESHEET");
  52132. }
  52133. // Effect
  52134. var join = defines.join("\n");
  52135. if (this._cachedDefines !== join) {
  52136. this._cachedDefines = join;
  52137. var attributesNamesOrOptions;
  52138. var effectCreationOption;
  52139. if (this._isAnimationSheetEnabled) {
  52140. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  52141. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  52142. }
  52143. else {
  52144. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  52145. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  52146. }
  52147. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  52148. }
  52149. return this._effect;
  52150. };
  52151. /**
  52152. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  52153. */
  52154. ParticleSystem.prototype.animate = function () {
  52155. if (!this._started)
  52156. return;
  52157. var effect = this._getEffect();
  52158. // Check
  52159. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  52160. return;
  52161. if (this._currentRenderId === this._scene.getRenderId()) {
  52162. return;
  52163. }
  52164. this._currentRenderId = this._scene.getRenderId();
  52165. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  52166. // determine the number of particles we need to create
  52167. var newParticles;
  52168. if (this.manualEmitCount > -1) {
  52169. newParticles = this.manualEmitCount;
  52170. this._newPartsExcess = 0;
  52171. this.manualEmitCount = 0;
  52172. }
  52173. else {
  52174. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  52175. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  52176. }
  52177. if (this._newPartsExcess > 1.0) {
  52178. newParticles += this._newPartsExcess >> 0;
  52179. this._newPartsExcess -= this._newPartsExcess >> 0;
  52180. }
  52181. this._alive = false;
  52182. if (!this._stopped) {
  52183. this._actualFrame += this._scaledUpdateSpeed;
  52184. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  52185. this.stop();
  52186. }
  52187. else {
  52188. newParticles = 0;
  52189. }
  52190. this._update(newParticles);
  52191. // Stopped?
  52192. if (this._stopped) {
  52193. if (!this._alive) {
  52194. this._started = false;
  52195. if (this.onAnimationEnd) {
  52196. this.onAnimationEnd();
  52197. }
  52198. if (this.disposeOnStop) {
  52199. this._scene._toBeDisposed.push(this);
  52200. }
  52201. }
  52202. }
  52203. // Animation sheet
  52204. if (this._isAnimationSheetEnabled) {
  52205. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  52206. }
  52207. else {
  52208. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  52209. }
  52210. // Update VBO
  52211. var offset = 0;
  52212. for (var index = 0; index < this._particles.length; index++) {
  52213. var particle = this._particles[index];
  52214. this._appendParticleVertexes(offset, particle);
  52215. offset += 4;
  52216. }
  52217. if (this._vertexBuffer) {
  52218. this._vertexBuffer.update(this._vertexData);
  52219. }
  52220. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  52221. this.stop();
  52222. }
  52223. };
  52224. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  52225. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  52226. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  52227. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  52228. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  52229. };
  52230. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  52231. this._appendParticleVertex(offset++, particle, 0, 0);
  52232. this._appendParticleVertex(offset++, particle, 1, 0);
  52233. this._appendParticleVertex(offset++, particle, 1, 1);
  52234. this._appendParticleVertex(offset++, particle, 0, 1);
  52235. };
  52236. /**
  52237. * Rebuilds the particle system.
  52238. */
  52239. ParticleSystem.prototype.rebuild = function () {
  52240. this._createIndexBuffer();
  52241. if (this._vertexBuffer) {
  52242. this._vertexBuffer._rebuild();
  52243. }
  52244. };
  52245. /**
  52246. * Is this system ready to be used/rendered
  52247. * @return true if the system is ready
  52248. */
  52249. ParticleSystem.prototype.isReady = function () {
  52250. var effect = this._getEffect();
  52251. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  52252. return false;
  52253. }
  52254. return true;
  52255. };
  52256. /**
  52257. * Renders the particle system in its current state.
  52258. * @returns the current number of particles
  52259. */
  52260. ParticleSystem.prototype.render = function () {
  52261. var effect = this._getEffect();
  52262. // Check
  52263. if (!this.isReady() || !this._particles.length) {
  52264. return 0;
  52265. }
  52266. var engine = this._scene.getEngine();
  52267. // Render
  52268. engine.enableEffect(effect);
  52269. engine.setState(false);
  52270. var viewMatrix = this._scene.getViewMatrix();
  52271. effect.setTexture("diffuseSampler", this.particleTexture);
  52272. effect.setMatrix("view", viewMatrix);
  52273. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  52274. if (this._isAnimationSheetEnabled && this.particleTexture) {
  52275. var baseSize = this.particleTexture.getBaseSize();
  52276. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  52277. }
  52278. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  52279. if (this._scene.clipPlane) {
  52280. var clipPlane = this._scene.clipPlane;
  52281. var invView = viewMatrix.clone();
  52282. invView.invert();
  52283. effect.setMatrix("invView", invView);
  52284. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  52285. }
  52286. // VBOs
  52287. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  52288. // Draw order
  52289. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  52290. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  52291. }
  52292. else {
  52293. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  52294. }
  52295. if (this.forceDepthWrite) {
  52296. engine.setDepthWrite(true);
  52297. }
  52298. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  52299. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  52300. return this._particles.length;
  52301. };
  52302. /**
  52303. * Disposes the particle system and free the associated resources
  52304. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  52305. */
  52306. ParticleSystem.prototype.dispose = function (disposeTexture) {
  52307. if (disposeTexture === void 0) { disposeTexture = true; }
  52308. if (this._vertexBuffer) {
  52309. this._vertexBuffer.dispose();
  52310. this._vertexBuffer = null;
  52311. }
  52312. if (this._indexBuffer) {
  52313. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  52314. this._indexBuffer = null;
  52315. }
  52316. if (disposeTexture && this.particleTexture) {
  52317. this.particleTexture.dispose();
  52318. this.particleTexture = null;
  52319. }
  52320. this._removeFromRoot();
  52321. // Remove from scene
  52322. var index = this._scene.particleSystems.indexOf(this);
  52323. if (index > -1) {
  52324. this._scene.particleSystems.splice(index, 1);
  52325. }
  52326. // Callback
  52327. this.onDisposeObservable.notifyObservers(this);
  52328. this.onDisposeObservable.clear();
  52329. };
  52330. /**
  52331. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  52332. * @param radius The radius of the sphere to emit from
  52333. * @returns the emitter
  52334. */
  52335. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  52336. if (radius === void 0) { radius = 1; }
  52337. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  52338. this.particleEmitterType = particleEmitter;
  52339. return particleEmitter;
  52340. };
  52341. /**
  52342. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  52343. * @param radius The radius of the sphere to emit from
  52344. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  52345. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  52346. * @returns the emitter
  52347. */
  52348. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  52349. if (radius === void 0) { radius = 1; }
  52350. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  52351. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  52352. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  52353. this.particleEmitterType = particleEmitter;
  52354. return particleEmitter;
  52355. };
  52356. /**
  52357. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  52358. * @param radius The radius of the cone to emit from
  52359. * @param angle The base angle of the cone
  52360. * @returns the emitter
  52361. */
  52362. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  52363. if (radius === void 0) { radius = 1; }
  52364. if (angle === void 0) { angle = Math.PI / 4; }
  52365. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  52366. this.particleEmitterType = particleEmitter;
  52367. return particleEmitter;
  52368. };
  52369. // 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.
  52370. /**
  52371. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  52372. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  52373. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  52374. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  52375. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  52376. * @returns the emitter
  52377. */
  52378. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  52379. var particleEmitter = new BABYLON.BoxParticleEmitter();
  52380. this.particleEmitterType = particleEmitter;
  52381. this.direction1 = direction1;
  52382. this.direction2 = direction2;
  52383. this.minEmitBox = minEmitBox;
  52384. this.maxEmitBox = maxEmitBox;
  52385. return particleEmitter;
  52386. };
  52387. // Clone
  52388. /**
  52389. * Clones the particle system.
  52390. * @param name The name of the cloned object
  52391. * @param newEmitter The new emitter to use
  52392. * @returns the cloned particle system
  52393. */
  52394. ParticleSystem.prototype.clone = function (name, newEmitter) {
  52395. var custom = null;
  52396. var program = null;
  52397. if (this.customShader != null) {
  52398. program = this.customShader;
  52399. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  52400. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  52401. }
  52402. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  52403. result.customShader = program;
  52404. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  52405. if (newEmitter === undefined) {
  52406. newEmitter = this.emitter;
  52407. }
  52408. result.emitter = newEmitter;
  52409. if (this.particleTexture) {
  52410. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  52411. }
  52412. if (!this.preventAutoStart) {
  52413. result.start();
  52414. }
  52415. return result;
  52416. };
  52417. /**
  52418. * Serializes the particle system to a JSON object.
  52419. * @returns the JSON object
  52420. */
  52421. ParticleSystem.prototype.serialize = function () {
  52422. var serializationObject = {};
  52423. serializationObject.name = this.name;
  52424. serializationObject.id = this.id;
  52425. // Emitter
  52426. if (this.emitter.position) {
  52427. var emitterMesh = this.emitter;
  52428. serializationObject.emitterId = emitterMesh.id;
  52429. }
  52430. else {
  52431. var emitterPosition = this.emitter;
  52432. serializationObject.emitter = emitterPosition.asArray();
  52433. }
  52434. serializationObject.capacity = this.getCapacity();
  52435. if (this.particleTexture) {
  52436. serializationObject.textureName = this.particleTexture.name;
  52437. }
  52438. // Animations
  52439. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  52440. // Particle system
  52441. serializationObject.minAngularSpeed = this.minAngularSpeed;
  52442. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  52443. serializationObject.minSize = this.minSize;
  52444. serializationObject.maxSize = this.maxSize;
  52445. serializationObject.minEmitPower = this.minEmitPower;
  52446. serializationObject.maxEmitPower = this.maxEmitPower;
  52447. serializationObject.minLifeTime = this.minLifeTime;
  52448. serializationObject.maxLifeTime = this.maxLifeTime;
  52449. serializationObject.emitRate = this.emitRate;
  52450. serializationObject.minEmitBox = this.minEmitBox.asArray();
  52451. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  52452. serializationObject.gravity = this.gravity.asArray();
  52453. serializationObject.direction1 = this.direction1.asArray();
  52454. serializationObject.direction2 = this.direction2.asArray();
  52455. serializationObject.color1 = this.color1.asArray();
  52456. serializationObject.color2 = this.color2.asArray();
  52457. serializationObject.colorDead = this.colorDead.asArray();
  52458. serializationObject.updateSpeed = this.updateSpeed;
  52459. serializationObject.targetStopDuration = this.targetStopDuration;
  52460. serializationObject.textureMask = this.textureMask.asArray();
  52461. serializationObject.blendMode = this.blendMode;
  52462. serializationObject.customShader = this.customShader;
  52463. serializationObject.preventAutoStart = this.preventAutoStart;
  52464. serializationObject.startSpriteCellID = this.startSpriteCellID;
  52465. serializationObject.endSpriteCellID = this.endSpriteCellID;
  52466. serializationObject.spriteCellLoop = this.spriteCellLoop;
  52467. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  52468. serializationObject.spriteCellWidth = this.spriteCellWidth;
  52469. serializationObject.spriteCellHeight = this.spriteCellHeight;
  52470. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  52471. // Emitter
  52472. if (this.particleEmitterType) {
  52473. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  52474. }
  52475. return serializationObject;
  52476. };
  52477. /**
  52478. * Parses a JSON object to create a particle system.
  52479. * @param parsedParticleSystem The JSON object to parse
  52480. * @param scene The scene to create the particle system in
  52481. * @param rootUrl The root url to use to load external dependencies like texture
  52482. * @returns the Parsed particle system
  52483. */
  52484. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  52485. var name = parsedParticleSystem.name;
  52486. var custom = null;
  52487. var program = null;
  52488. if (parsedParticleSystem.customShader) {
  52489. program = parsedParticleSystem.customShader;
  52490. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  52491. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  52492. }
  52493. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  52494. particleSystem.customShader = program;
  52495. if (parsedParticleSystem.id) {
  52496. particleSystem.id = parsedParticleSystem.id;
  52497. }
  52498. // Auto start
  52499. if (parsedParticleSystem.preventAutoStart) {
  52500. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  52501. }
  52502. // Texture
  52503. if (parsedParticleSystem.textureName) {
  52504. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  52505. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  52506. }
  52507. // Emitter
  52508. if (parsedParticleSystem.emitterId) {
  52509. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  52510. }
  52511. else {
  52512. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  52513. }
  52514. // Animations
  52515. if (parsedParticleSystem.animations) {
  52516. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  52517. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  52518. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  52519. }
  52520. }
  52521. if (parsedParticleSystem.autoAnimate) {
  52522. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  52523. }
  52524. // Particle system
  52525. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  52526. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  52527. particleSystem.minSize = parsedParticleSystem.minSize;
  52528. particleSystem.maxSize = parsedParticleSystem.maxSize;
  52529. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  52530. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  52531. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  52532. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  52533. particleSystem.emitRate = parsedParticleSystem.emitRate;
  52534. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  52535. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  52536. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  52537. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  52538. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  52539. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  52540. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  52541. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  52542. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  52543. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  52544. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  52545. particleSystem.blendMode = parsedParticleSystem.blendMode;
  52546. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  52547. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  52548. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  52549. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  52550. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  52551. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  52552. if (!particleSystem.preventAutoStart) {
  52553. particleSystem.start();
  52554. }
  52555. return particleSystem;
  52556. };
  52557. /**
  52558. * Source color is added to the destination color without alpha affecting the result.
  52559. */
  52560. ParticleSystem.BLENDMODE_ONEONE = 0;
  52561. /**
  52562. * Blend current color and particle color using particle’s alpha.
  52563. */
  52564. ParticleSystem.BLENDMODE_STANDARD = 1;
  52565. return ParticleSystem;
  52566. }());
  52567. BABYLON.ParticleSystem = ParticleSystem;
  52568. })(BABYLON || (BABYLON = {}));
  52569. //# sourceMappingURL=babylon.particleSystem.js.map
  52570. "use strict";
  52571. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  52572. "use strict";
  52573. var BABYLON;
  52574. (function (BABYLON) {
  52575. /**
  52576. * Particle emitter emitting particles from the inside of a box.
  52577. * It emits the particles randomly between 2 given directions.
  52578. */
  52579. var BoxParticleEmitter = /** @class */ (function () {
  52580. /**
  52581. * Creates a new instance of @see BoxParticleEmitter
  52582. */
  52583. function BoxParticleEmitter() {
  52584. /**
  52585. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  52586. */
  52587. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  52588. /**
  52589. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  52590. */
  52591. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  52592. /**
  52593. * 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.
  52594. */
  52595. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  52596. /**
  52597. * 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.
  52598. */
  52599. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  52600. }
  52601. /**
  52602. * Called by the particle System when the direction is computed for the created particle.
  52603. * @param emitPower is the power of the particle (speed)
  52604. * @param worldMatrix is the world matrix of the particle system
  52605. * @param directionToUpdate is the direction vector to update with the result
  52606. * @param particle is the particle we are computed the direction for
  52607. */
  52608. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  52609. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  52610. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  52611. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  52612. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  52613. };
  52614. /**
  52615. * Called by the particle System when the position is computed for the created particle.
  52616. * @param worldMatrix is the world matrix of the particle system
  52617. * @param positionToUpdate is the position vector to update with the result
  52618. * @param particle is the particle we are computed the position for
  52619. */
  52620. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  52621. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  52622. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  52623. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  52624. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  52625. };
  52626. /**
  52627. * Clones the current emitter and returns a copy of it
  52628. * @returns the new emitter
  52629. */
  52630. BoxParticleEmitter.prototype.clone = function () {
  52631. var newOne = new BoxParticleEmitter();
  52632. BABYLON.Tools.DeepCopy(this, newOne);
  52633. return newOne;
  52634. };
  52635. /**
  52636. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  52637. * @param effect defines the update shader
  52638. */
  52639. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  52640. effect.setVector3("direction1", this.direction1);
  52641. effect.setVector3("direction2", this.direction2);
  52642. effect.setVector3("minEmitBox", this.minEmitBox);
  52643. effect.setVector3("maxEmitBox", this.maxEmitBox);
  52644. };
  52645. /**
  52646. * Returns a string to use to update the GPU particles update shader
  52647. * @returns a string containng the defines string
  52648. */
  52649. BoxParticleEmitter.prototype.getEffectDefines = function () {
  52650. return "#define BOXEMITTER";
  52651. };
  52652. /**
  52653. * Returns the string "BoxEmitter"
  52654. * @returns a string containing the class name
  52655. */
  52656. BoxParticleEmitter.prototype.getClassName = function () {
  52657. return "BoxEmitter";
  52658. };
  52659. /**
  52660. * Serializes the particle system to a JSON object.
  52661. * @returns the JSON object
  52662. */
  52663. BoxParticleEmitter.prototype.serialize = function () {
  52664. var serializationObject = {};
  52665. serializationObject.type = this.getClassName();
  52666. serializationObject.direction1 = this.direction1.asArray();
  52667. ;
  52668. serializationObject.direction2 = this.direction2.asArray();
  52669. ;
  52670. serializationObject.minEmitBox = this.minEmitBox.asArray();
  52671. ;
  52672. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  52673. ;
  52674. return serializationObject;
  52675. };
  52676. /**
  52677. * Parse properties from a JSON object
  52678. * @param serializationObject defines the JSON object
  52679. */
  52680. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  52681. this.direction1.copyFrom(serializationObject.direction1);
  52682. this.direction2.copyFrom(serializationObject.direction2);
  52683. this.minEmitBox.copyFrom(serializationObject.minEmitBox);
  52684. this.maxEmitBox.copyFrom(serializationObject.maxEmitBox);
  52685. };
  52686. return BoxParticleEmitter;
  52687. }());
  52688. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  52689. })(BABYLON || (BABYLON = {}));
  52690. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  52691. "use strict";
  52692. var BABYLON;
  52693. (function (BABYLON) {
  52694. /**
  52695. * Particle emitter emitting particles from the inside of a cone.
  52696. * It emits the particles alongside the cone volume from the base to the particle.
  52697. * The emission direction might be randomized.
  52698. */
  52699. var ConeParticleEmitter = /** @class */ (function () {
  52700. /**
  52701. * Creates a new instance of @see ConeParticleEmitter
  52702. * @param radius the radius of the emission cone (1 by default)
  52703. * @param angles the cone base angle (PI by default)
  52704. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  52705. */
  52706. function ConeParticleEmitter(radius,
  52707. /**
  52708. * The radius of the emission cone.
  52709. */
  52710. angle,
  52711. /**
  52712. * The cone base angle.
  52713. */
  52714. directionRandomizer) {
  52715. if (radius === void 0) { radius = 1; }
  52716. if (angle === void 0) { angle = Math.PI; }
  52717. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  52718. this.angle = angle;
  52719. this.directionRandomizer = directionRandomizer;
  52720. this.radius = radius;
  52721. }
  52722. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  52723. /**
  52724. * Gets the radius of the emission cone.
  52725. */
  52726. get: function () {
  52727. return this._radius;
  52728. },
  52729. /**
  52730. * Sets the radius of the emission cone.
  52731. */
  52732. set: function (value) {
  52733. this._radius = value;
  52734. if (this.angle !== 0) {
  52735. this._height = value / Math.tan(this.angle / 2);
  52736. }
  52737. else {
  52738. this._height = 1;
  52739. }
  52740. },
  52741. enumerable: true,
  52742. configurable: true
  52743. });
  52744. /**
  52745. * Called by the particle System when the direction is computed for the created particle.
  52746. * @param emitPower is the power of the particle (speed)
  52747. * @param worldMatrix is the world matrix of the particle system
  52748. * @param directionToUpdate is the direction vector to update with the result
  52749. * @param particle is the particle we are computed the direction for
  52750. */
  52751. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  52752. if (this.angle === 0) {
  52753. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  52754. }
  52755. else {
  52756. // measure the direction Vector from the emitter to the particle.
  52757. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  52758. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52759. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52760. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52761. direction.x += randX;
  52762. direction.y += randY;
  52763. direction.z += randZ;
  52764. direction.normalize();
  52765. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  52766. }
  52767. };
  52768. /**
  52769. * Called by the particle System when the position is computed for the created particle.
  52770. * @param worldMatrix is the world matrix of the particle system
  52771. * @param positionToUpdate is the position vector to update with the result
  52772. * @param particle is the particle we are computed the position for
  52773. */
  52774. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  52775. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  52776. var h = BABYLON.Scalar.RandomRange(0, 1);
  52777. // Better distribution in a cone at normal angles.
  52778. h = 1 - h * h;
  52779. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  52780. radius = radius * h;
  52781. var randX = radius * Math.sin(s);
  52782. var randZ = radius * Math.cos(s);
  52783. var randY = h * this._height;
  52784. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  52785. };
  52786. /**
  52787. * Clones the current emitter and returns a copy of it
  52788. * @returns the new emitter
  52789. */
  52790. ConeParticleEmitter.prototype.clone = function () {
  52791. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  52792. BABYLON.Tools.DeepCopy(this, newOne);
  52793. return newOne;
  52794. };
  52795. /**
  52796. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  52797. * @param effect defines the update shader
  52798. */
  52799. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  52800. effect.setFloat("radius", this.radius);
  52801. effect.setFloat("angle", this.angle);
  52802. effect.setFloat("height", this._height);
  52803. effect.setFloat("directionRandomizer", this.directionRandomizer);
  52804. };
  52805. /**
  52806. * Returns a string to use to update the GPU particles update shader
  52807. * @returns a string containng the defines string
  52808. */
  52809. ConeParticleEmitter.prototype.getEffectDefines = function () {
  52810. return "#define CONEEMITTER";
  52811. };
  52812. /**
  52813. * Returns the string "BoxEmitter"
  52814. * @returns a string containing the class name
  52815. */
  52816. ConeParticleEmitter.prototype.getClassName = function () {
  52817. return "ConeEmitter";
  52818. };
  52819. /**
  52820. * Serializes the particle system to a JSON object.
  52821. * @returns the JSON object
  52822. */
  52823. ConeParticleEmitter.prototype.serialize = function () {
  52824. var serializationObject = {};
  52825. serializationObject.type = this.getClassName();
  52826. serializationObject.radius = this.radius;
  52827. serializationObject.angle = this.angle;
  52828. serializationObject.directionRandomizer = this.directionRandomizer;
  52829. return serializationObject;
  52830. };
  52831. /**
  52832. * Parse properties from a JSON object
  52833. * @param serializationObject defines the JSON object
  52834. */
  52835. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  52836. this.radius = serializationObject.radius;
  52837. this.angle = serializationObject.angle;
  52838. this.directionRandomizer = serializationObject.directionRandomizer;
  52839. };
  52840. return ConeParticleEmitter;
  52841. }());
  52842. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  52843. })(BABYLON || (BABYLON = {}));
  52844. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  52845. "use strict";
  52846. var BABYLON;
  52847. (function (BABYLON) {
  52848. /**
  52849. * Particle emitter emitting particles from the inside of a sphere.
  52850. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  52851. */
  52852. var SphereParticleEmitter = /** @class */ (function () {
  52853. /**
  52854. * Creates a new instance of @see SphereParticleEmitter
  52855. * @param radius the radius of the emission sphere (1 by default)
  52856. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  52857. */
  52858. function SphereParticleEmitter(
  52859. /**
  52860. * The radius of the emission sphere.
  52861. */
  52862. radius,
  52863. /**
  52864. * How much to randomize the particle direction [0-1].
  52865. */
  52866. directionRandomizer) {
  52867. if (radius === void 0) { radius = 1; }
  52868. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  52869. this.radius = radius;
  52870. this.directionRandomizer = directionRandomizer;
  52871. }
  52872. /**
  52873. * Called by the particle System when the direction is computed for the created particle.
  52874. * @param emitPower is the power of the particle (speed)
  52875. * @param worldMatrix is the world matrix of the particle system
  52876. * @param directionToUpdate is the direction vector to update with the result
  52877. * @param particle is the particle we are computed the direction for
  52878. */
  52879. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  52880. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  52881. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52882. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52883. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52884. direction.x += randX;
  52885. direction.y += randY;
  52886. direction.z += randZ;
  52887. direction.normalize();
  52888. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  52889. };
  52890. /**
  52891. * Called by the particle System when the position is computed for the created particle.
  52892. * @param worldMatrix is the world matrix of the particle system
  52893. * @param positionToUpdate is the position vector to update with the result
  52894. * @param particle is the particle we are computed the position for
  52895. */
  52896. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  52897. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  52898. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  52899. var randRadius = BABYLON.Scalar.RandomRange(0, this.radius);
  52900. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  52901. var randY = randRadius * Math.cos(theta);
  52902. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  52903. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  52904. };
  52905. /**
  52906. * Clones the current emitter and returns a copy of it
  52907. * @returns the new emitter
  52908. */
  52909. SphereParticleEmitter.prototype.clone = function () {
  52910. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  52911. BABYLON.Tools.DeepCopy(this, newOne);
  52912. return newOne;
  52913. };
  52914. /**
  52915. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  52916. * @param effect defines the update shader
  52917. */
  52918. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  52919. effect.setFloat("radius", this.radius);
  52920. effect.setFloat("directionRandomizer", this.directionRandomizer);
  52921. };
  52922. /**
  52923. * Returns a string to use to update the GPU particles update shader
  52924. * @returns a string containng the defines string
  52925. */
  52926. SphereParticleEmitter.prototype.getEffectDefines = function () {
  52927. return "#define SPHEREEMITTER";
  52928. };
  52929. /**
  52930. * Returns the string "SphereParticleEmitter"
  52931. * @returns a string containing the class name
  52932. */
  52933. SphereParticleEmitter.prototype.getClassName = function () {
  52934. return "SphereParticleEmitter";
  52935. };
  52936. /**
  52937. * Serializes the particle system to a JSON object.
  52938. * @returns the JSON object
  52939. */
  52940. SphereParticleEmitter.prototype.serialize = function () {
  52941. var serializationObject = {};
  52942. serializationObject.type = this.getClassName();
  52943. serializationObject.radius = this.radius;
  52944. serializationObject.directionRandomizer = this.directionRandomizer;
  52945. return serializationObject;
  52946. };
  52947. /**
  52948. * Parse properties from a JSON object
  52949. * @param serializationObject defines the JSON object
  52950. */
  52951. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  52952. this.radius = serializationObject.radius;
  52953. this.directionRandomizer = serializationObject.directionRandomizer;
  52954. };
  52955. return SphereParticleEmitter;
  52956. }());
  52957. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  52958. /**
  52959. * Particle emitter emitting particles from the inside of a sphere.
  52960. * It emits the particles randomly between two vectors.
  52961. */
  52962. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  52963. __extends(SphereDirectedParticleEmitter, _super);
  52964. /**
  52965. * Creates a new instance of @see SphereDirectedParticleEmitter
  52966. * @param radius the radius of the emission sphere (1 by default)
  52967. * @param direction1 the min limit of the emission direction (up vector by default)
  52968. * @param direction2 the max limit of the emission direction (up vector by default)
  52969. */
  52970. function SphereDirectedParticleEmitter(radius,
  52971. /**
  52972. * The min limit of the emission direction.
  52973. */
  52974. direction1,
  52975. /**
  52976. * The max limit of the emission direction.
  52977. */
  52978. direction2) {
  52979. if (radius === void 0) { radius = 1; }
  52980. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  52981. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  52982. var _this = _super.call(this, radius) || this;
  52983. _this.direction1 = direction1;
  52984. _this.direction2 = direction2;
  52985. return _this;
  52986. }
  52987. /**
  52988. * Called by the particle System when the direction is computed for the created particle.
  52989. * @param emitPower is the power of the particle (speed)
  52990. * @param worldMatrix is the world matrix of the particle system
  52991. * @param directionToUpdate is the direction vector to update with the result
  52992. * @param particle is the particle we are computed the direction for
  52993. */
  52994. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  52995. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  52996. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  52997. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  52998. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  52999. };
  53000. /**
  53001. * Clones the current emitter and returns a copy of it
  53002. * @returns the new emitter
  53003. */
  53004. SphereDirectedParticleEmitter.prototype.clone = function () {
  53005. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  53006. BABYLON.Tools.DeepCopy(this, newOne);
  53007. return newOne;
  53008. };
  53009. /**
  53010. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  53011. * @param effect defines the update shader
  53012. */
  53013. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  53014. effect.setFloat("radius", this.radius);
  53015. effect.setVector3("direction1", this.direction1);
  53016. effect.setVector3("direction2", this.direction2);
  53017. };
  53018. /**
  53019. * Returns a string to use to update the GPU particles update shader
  53020. * @returns a string containng the defines string
  53021. */
  53022. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  53023. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  53024. };
  53025. /**
  53026. * Returns the string "SphereDirectedParticleEmitter"
  53027. * @returns a string containing the class name
  53028. */
  53029. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  53030. return "SphereDirectedParticleEmitter";
  53031. };
  53032. /**
  53033. * Serializes the particle system to a JSON object.
  53034. * @returns the JSON object
  53035. */
  53036. SphereDirectedParticleEmitter.prototype.serialize = function () {
  53037. var serializationObject = _super.prototype.serialize.call(this);
  53038. ;
  53039. serializationObject.direction1 = this.direction1.asArray();
  53040. ;
  53041. serializationObject.direction2 = this.direction2.asArray();
  53042. ;
  53043. return serializationObject;
  53044. };
  53045. /**
  53046. * Parse properties from a JSON object
  53047. * @param serializationObject defines the JSON object
  53048. */
  53049. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  53050. _super.prototype.parse.call(this, serializationObject);
  53051. this.direction1.copyFrom(serializationObject.direction1);
  53052. this.direction2.copyFrom(serializationObject.direction2);
  53053. };
  53054. return SphereDirectedParticleEmitter;
  53055. }(SphereParticleEmitter));
  53056. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  53057. })(BABYLON || (BABYLON = {}));
  53058. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  53059. "use strict";
  53060. var __assign = (this && this.__assign) || Object.assign || function(t) {
  53061. for (var s, i = 1, n = arguments.length; i < n; i++) {
  53062. s = arguments[i];
  53063. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  53064. t[p] = s[p];
  53065. }
  53066. return t;
  53067. };
  53068. var BABYLON;
  53069. (function (BABYLON) {
  53070. /**
  53071. * This represents a GPU particle system in Babylon
  53072. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  53073. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  53074. */
  53075. var GPUParticleSystem = /** @class */ (function () {
  53076. /**
  53077. * Instantiates a GPU particle system.
  53078. * 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.
  53079. * @param name The name of the particle system
  53080. * @param capacity The max number of particles alive at the same time
  53081. * @param scene The scene the particle system belongs to
  53082. */
  53083. function GPUParticleSystem(name, options, scene) {
  53084. /**
  53085. * The emitter represents the Mesh or position we are attaching the particle system to.
  53086. */
  53087. this.emitter = null;
  53088. /**
  53089. * The rendering group used by the Particle system to chose when to render.
  53090. */
  53091. this.renderingGroupId = 0;
  53092. /**
  53093. * The layer mask we are rendering the particles through.
  53094. */
  53095. this.layerMask = 0x0FFFFFFF;
  53096. this._targetIndex = 0;
  53097. this._currentRenderId = -1;
  53098. this._started = false;
  53099. this._stopped = false;
  53100. this._timeDelta = 0;
  53101. this._attributesStrideSize = 14;
  53102. this._actualFrame = 0;
  53103. /**
  53104. * List of animations used by the particle system.
  53105. */
  53106. this.animations = [];
  53107. /**
  53108. * An event triggered when the system is disposed.
  53109. */
  53110. this.onDisposeObservable = new BABYLON.Observable();
  53111. /**
  53112. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  53113. */
  53114. this.updateSpeed = 0.01;
  53115. /**
  53116. * The amount of time the particle system is running (depends of the overall update speed).
  53117. */
  53118. this.targetStopDuration = 0;
  53119. /**
  53120. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  53121. */
  53122. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  53123. /**
  53124. * Minimum life time of emitting particles.
  53125. */
  53126. this.minLifeTime = 1;
  53127. /**
  53128. * Maximum life time of emitting particles.
  53129. */
  53130. this.maxLifeTime = 1;
  53131. /**
  53132. * Minimum Size of emitting particles.
  53133. */
  53134. this.minSize = 1;
  53135. /**
  53136. * Maximum Size of emitting particles.
  53137. */
  53138. this.maxSize = 1;
  53139. /**
  53140. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  53141. */
  53142. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53143. /**
  53144. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  53145. */
  53146. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53147. /**
  53148. * Color the particle will have at the end of its lifetime.
  53149. */
  53150. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  53151. /**
  53152. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  53153. */
  53154. this.emitRate = 100;
  53155. /**
  53156. * You can use gravity if you want to give an orientation to your particles.
  53157. */
  53158. this.gravity = BABYLON.Vector3.Zero();
  53159. /**
  53160. * Minimum power of emitting particles.
  53161. */
  53162. this.minEmitPower = 1;
  53163. /**
  53164. * Maximum power of emitting particles.
  53165. */
  53166. this.maxEmitPower = 1;
  53167. /**
  53168. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  53169. * to override the particles.
  53170. */
  53171. this.forceDepthWrite = false;
  53172. this.id = name;
  53173. this.name = name;
  53174. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  53175. this._engine = this._scene.getEngine();
  53176. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  53177. this._capacity = fullOptions.capacity;
  53178. this._activeCount = fullOptions.capacity;
  53179. this._currentActiveCount = 0;
  53180. this._scene.particleSystems.push(this);
  53181. this._updateEffectOptions = {
  53182. attributes: ["position", "age", "life", "seed", "size", "color", "direction"],
  53183. uniformsNames: ["currentCount", "timeDelta", "generalRandoms", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "gravity", "emitPower",
  53184. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "angle", "stopFactor"],
  53185. uniformBuffersNames: [],
  53186. samplers: ["randomSampler"],
  53187. defines: "",
  53188. fallbacks: null,
  53189. onCompiled: null,
  53190. onError: null,
  53191. indexParameters: null,
  53192. maxSimultaneousLights: 0,
  53193. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outSeed", "outSize", "outColor", "outDirection"]
  53194. };
  53195. // Random data
  53196. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  53197. var d = [];
  53198. for (var i = 0; i < maxTextureSize; ++i) {
  53199. d.push(Math.random());
  53200. d.push(Math.random());
  53201. d.push(Math.random());
  53202. d.push(Math.random());
  53203. }
  53204. 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);
  53205. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  53206. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  53207. this._randomTextureSize = maxTextureSize;
  53208. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  53209. }
  53210. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  53211. /**
  53212. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  53213. */
  53214. get: function () {
  53215. if (!BABYLON.Engine.LastCreatedEngine) {
  53216. return false;
  53217. }
  53218. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  53219. },
  53220. enumerable: true,
  53221. configurable: true
  53222. });
  53223. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  53224. /**
  53225. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  53226. * This only works when particleEmitterTyps is a BoxParticleEmitter
  53227. */
  53228. get: function () {
  53229. if (this.particleEmitterType.direction1) {
  53230. return this.particleEmitterType.direction1;
  53231. }
  53232. return BABYLON.Vector3.Zero();
  53233. },
  53234. set: function (value) {
  53235. if (this.particleEmitterType.direction1) {
  53236. this.particleEmitterType.direction1 = value;
  53237. }
  53238. },
  53239. enumerable: true,
  53240. configurable: true
  53241. });
  53242. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  53243. /**
  53244. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  53245. * This only works when particleEmitterTyps is a BoxParticleEmitter
  53246. */
  53247. get: function () {
  53248. if (this.particleEmitterType.direction2) {
  53249. return this.particleEmitterType.direction2;
  53250. }
  53251. return BABYLON.Vector3.Zero();
  53252. },
  53253. set: function (value) {
  53254. if (this.particleEmitterType.direction2) {
  53255. this.particleEmitterType.direction2 = value;
  53256. }
  53257. },
  53258. enumerable: true,
  53259. configurable: true
  53260. });
  53261. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  53262. /**
  53263. * 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.
  53264. * This only works when particleEmitterTyps is a BoxParticleEmitter
  53265. */
  53266. get: function () {
  53267. if (this.particleEmitterType.minEmitBox) {
  53268. return this.particleEmitterType.minEmitBox;
  53269. }
  53270. return BABYLON.Vector3.Zero();
  53271. },
  53272. set: function (value) {
  53273. if (this.particleEmitterType.minEmitBox) {
  53274. this.particleEmitterType.minEmitBox = value;
  53275. }
  53276. },
  53277. enumerable: true,
  53278. configurable: true
  53279. });
  53280. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  53281. /**
  53282. * 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.
  53283. * This only works when particleEmitterTyps is a BoxParticleEmitter
  53284. */
  53285. get: function () {
  53286. if (this.particleEmitterType.maxEmitBox) {
  53287. return this.particleEmitterType.maxEmitBox;
  53288. }
  53289. return BABYLON.Vector3.Zero();
  53290. },
  53291. set: function (value) {
  53292. if (this.particleEmitterType.maxEmitBox) {
  53293. this.particleEmitterType.maxEmitBox = value;
  53294. }
  53295. },
  53296. enumerable: true,
  53297. configurable: true
  53298. });
  53299. /**
  53300. * Gets the maximum number of particles active at the same time.
  53301. * @returns The max number of active particles.
  53302. */
  53303. GPUParticleSystem.prototype.getCapacity = function () {
  53304. return this._capacity;
  53305. };
  53306. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  53307. /**
  53308. * Gets or set the number of active particles
  53309. */
  53310. get: function () {
  53311. return this._activeCount;
  53312. },
  53313. set: function (value) {
  53314. this._activeCount = Math.min(value, this._capacity);
  53315. },
  53316. enumerable: true,
  53317. configurable: true
  53318. });
  53319. /**
  53320. * Is this system ready to be used/rendered
  53321. * @return true if the system is ready
  53322. */
  53323. GPUParticleSystem.prototype.isReady = function () {
  53324. if (!this._updateEffect) {
  53325. this._recreateUpdateEffect();
  53326. this._recreateRenderEffect();
  53327. return false;
  53328. }
  53329. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  53330. return false;
  53331. }
  53332. return true;
  53333. };
  53334. /**
  53335. * Gets Wether the system has been started.
  53336. * @returns True if it has been started, otherwise false.
  53337. */
  53338. GPUParticleSystem.prototype.isStarted = function () {
  53339. return this._started;
  53340. };
  53341. /**
  53342. * Starts the particle system and begins to emit.
  53343. */
  53344. GPUParticleSystem.prototype.start = function () {
  53345. this._started = true;
  53346. this._stopped = false;
  53347. };
  53348. /**
  53349. * Stops the particle system.
  53350. */
  53351. GPUParticleSystem.prototype.stop = function () {
  53352. this._stopped = true;
  53353. };
  53354. /**
  53355. * Remove all active particles
  53356. */
  53357. GPUParticleSystem.prototype.reset = function () {
  53358. this._releaseBuffers();
  53359. this._releaseVAOs();
  53360. this._currentActiveCount = 0;
  53361. this._targetIndex = 0;
  53362. };
  53363. /**
  53364. * Returns the string "GPUParticleSystem"
  53365. * @returns a string containing the class name
  53366. */
  53367. GPUParticleSystem.prototype.getClassName = function () {
  53368. return "GPUParticleSystem";
  53369. };
  53370. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  53371. var updateVertexBuffers = {};
  53372. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  53373. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  53374. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  53375. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 1);
  53376. updateVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1);
  53377. updateVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4);
  53378. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", 11, 3);
  53379. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  53380. this._engine.bindArrayBuffer(null);
  53381. return vao;
  53382. };
  53383. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  53384. var renderVertexBuffers = {};
  53385. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  53386. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  53387. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  53388. renderVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1, this._attributesStrideSize, true);
  53389. renderVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4, this._attributesStrideSize, true);
  53390. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  53391. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  53392. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  53393. this._engine.bindArrayBuffer(null);
  53394. return vao;
  53395. };
  53396. GPUParticleSystem.prototype._initialize = function (force) {
  53397. if (force === void 0) { force = false; }
  53398. if (this._buffer0 && !force) {
  53399. return;
  53400. }
  53401. var engine = this._scene.getEngine();
  53402. var data = new Array();
  53403. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  53404. // position
  53405. data.push(0.0);
  53406. data.push(0.0);
  53407. data.push(0.0);
  53408. // Age and life
  53409. data.push(0.0); // create the particle as a dead one to create a new one at start
  53410. data.push(0.0);
  53411. // Seed
  53412. data.push(Math.random());
  53413. // Size
  53414. data.push(0.0);
  53415. // color
  53416. data.push(0.0);
  53417. data.push(0.0);
  53418. data.push(0.0);
  53419. data.push(0.0);
  53420. // direction
  53421. data.push(0.0);
  53422. data.push(0.0);
  53423. data.push(0.0);
  53424. }
  53425. // Sprite data
  53426. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  53427. -0.5, 0.5, 0, 1,
  53428. -0.5, -0.5, 0, 0,
  53429. 0.5, -0.5, 1, 0]);
  53430. // Buffers
  53431. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  53432. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  53433. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  53434. // Update VAO
  53435. this._updateVAO = [];
  53436. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  53437. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  53438. // Render VAO
  53439. this._renderVAO = [];
  53440. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  53441. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  53442. // Links
  53443. this._sourceBuffer = this._buffer0;
  53444. this._targetBuffer = this._buffer1;
  53445. };
  53446. /** @ignore */
  53447. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  53448. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  53449. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  53450. return;
  53451. }
  53452. this._updateEffectOptions.defines = defines;
  53453. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  53454. };
  53455. /** @ignore */
  53456. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  53457. var defines = "";
  53458. if (this._scene.clipPlane) {
  53459. defines = "\n#define CLIPPLANE";
  53460. }
  53461. if (this._renderEffect && this._renderEffect.defines === defines) {
  53462. return;
  53463. }
  53464. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv"], ["view", "projection", "colorDead", "invView", "vClipPlane"], ["textureSampler"], this._scene.getEngine(), defines);
  53465. };
  53466. /**
  53467. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  53468. */
  53469. GPUParticleSystem.prototype.animate = function () {
  53470. this._timeDelta = this.updateSpeed * this._scene.getAnimationRatio();
  53471. this._actualFrame += this._timeDelta;
  53472. if (!this._stopped) {
  53473. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  53474. this.stop();
  53475. }
  53476. }
  53477. };
  53478. /**
  53479. * Renders the particle system in its current state.
  53480. * @returns the current number of particles
  53481. */
  53482. GPUParticleSystem.prototype.render = function () {
  53483. if (!this._started) {
  53484. return 0;
  53485. }
  53486. this._recreateUpdateEffect();
  53487. this._recreateRenderEffect();
  53488. if (!this.isReady()) {
  53489. return 0;
  53490. }
  53491. if (this._currentRenderId === this._scene.getRenderId()) {
  53492. return 0;
  53493. }
  53494. this._currentRenderId = this._scene.getRenderId();
  53495. // Get everything ready to render
  53496. this._initialize();
  53497. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + (this.emitRate * this._timeDelta) | 0);
  53498. // Enable update effect
  53499. this._engine.enableEffect(this._updateEffect);
  53500. this._engine.setState(false);
  53501. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  53502. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  53503. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  53504. this._updateEffect.setFloat3("generalRandoms", Math.random(), Math.random(), Math.random());
  53505. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  53506. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  53507. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  53508. this._updateEffect.setDirectColor4("color1", this.color1);
  53509. this._updateEffect.setDirectColor4("color2", this.color2);
  53510. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  53511. this._updateEffect.setVector3("gravity", this.gravity);
  53512. if (this.particleEmitterType) {
  53513. this.particleEmitterType.applyToShader(this._updateEffect);
  53514. }
  53515. var emitterWM;
  53516. if (this.emitter.position) {
  53517. var emitterMesh = this.emitter;
  53518. emitterWM = emitterMesh.getWorldMatrix();
  53519. }
  53520. else {
  53521. var emitterPosition = this.emitter;
  53522. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  53523. }
  53524. this._updateEffect.setMatrix("emitterWM", emitterWM);
  53525. // Bind source VAO
  53526. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  53527. // Update
  53528. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  53529. this._engine.setRasterizerState(false);
  53530. this._engine.beginTransformFeedback();
  53531. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  53532. this._engine.endTransformFeedback();
  53533. this._engine.setRasterizerState(true);
  53534. this._engine.bindTransformFeedbackBuffer(null);
  53535. // Enable render effect
  53536. this._engine.enableEffect(this._renderEffect);
  53537. var viewMatrix = this._scene.getViewMatrix();
  53538. this._renderEffect.setMatrix("view", viewMatrix);
  53539. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  53540. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  53541. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  53542. if (this._scene.clipPlane) {
  53543. var clipPlane = this._scene.clipPlane;
  53544. var invView = viewMatrix.clone();
  53545. invView.invert();
  53546. this._renderEffect.setMatrix("invView", invView);
  53547. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  53548. }
  53549. // Draw order
  53550. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  53551. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  53552. }
  53553. else {
  53554. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  53555. }
  53556. if (this.forceDepthWrite) {
  53557. this._engine.setDepthWrite(true);
  53558. }
  53559. // Bind source VAO
  53560. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  53561. // Render
  53562. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  53563. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  53564. // Switch VAOs
  53565. this._targetIndex++;
  53566. if (this._targetIndex === 2) {
  53567. this._targetIndex = 0;
  53568. }
  53569. // Switch buffers
  53570. var tmpBuffer = this._sourceBuffer;
  53571. this._sourceBuffer = this._targetBuffer;
  53572. this._targetBuffer = tmpBuffer;
  53573. return this._currentActiveCount;
  53574. };
  53575. /**
  53576. * Rebuilds the particle system
  53577. */
  53578. GPUParticleSystem.prototype.rebuild = function () {
  53579. this._initialize(true);
  53580. };
  53581. GPUParticleSystem.prototype._releaseBuffers = function () {
  53582. if (this._buffer0) {
  53583. this._buffer0.dispose();
  53584. this._buffer0 = null;
  53585. }
  53586. if (this._buffer1) {
  53587. this._buffer1.dispose();
  53588. this._buffer1 = null;
  53589. }
  53590. if (this._spriteBuffer) {
  53591. this._spriteBuffer.dispose();
  53592. this._spriteBuffer = null;
  53593. }
  53594. };
  53595. GPUParticleSystem.prototype._releaseVAOs = function () {
  53596. if (!this._updateVAO) {
  53597. return;
  53598. }
  53599. for (var index = 0; index < this._updateVAO.length; index++) {
  53600. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  53601. }
  53602. this._updateVAO = [];
  53603. for (var index = 0; index < this._renderVAO.length; index++) {
  53604. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  53605. }
  53606. this._renderVAO = [];
  53607. };
  53608. /**
  53609. * Disposes the particle system and free the associated resources
  53610. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  53611. */
  53612. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  53613. if (disposeTexture === void 0) { disposeTexture = true; }
  53614. var index = this._scene.particleSystems.indexOf(this);
  53615. if (index > -1) {
  53616. this._scene.particleSystems.splice(index, 1);
  53617. }
  53618. this._releaseBuffers();
  53619. this._releaseVAOs();
  53620. if (this._randomTexture) {
  53621. this._randomTexture.dispose();
  53622. this._randomTexture = null;
  53623. }
  53624. if (disposeTexture && this.particleTexture) {
  53625. this.particleTexture.dispose();
  53626. this.particleTexture = null;
  53627. }
  53628. // Callback
  53629. this.onDisposeObservable.notifyObservers(this);
  53630. this.onDisposeObservable.clear();
  53631. };
  53632. /**
  53633. * Clones the particle system.
  53634. * @param name The name of the cloned object
  53635. * @param newEmitter The new emitter to use
  53636. * @returns the cloned particle system
  53637. */
  53638. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  53639. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  53640. BABYLON.Tools.DeepCopy(this, result);
  53641. if (newEmitter === undefined) {
  53642. newEmitter = this.emitter;
  53643. }
  53644. result.emitter = newEmitter;
  53645. if (this.particleTexture) {
  53646. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  53647. }
  53648. return result;
  53649. };
  53650. /**
  53651. * Serializes the particle system to a JSON object.
  53652. * @returns the JSON object
  53653. */
  53654. GPUParticleSystem.prototype.serialize = function () {
  53655. var serializationObject = {};
  53656. serializationObject.name = this.name;
  53657. serializationObject.id = this.id;
  53658. // Emitter
  53659. if (this.emitter.position) {
  53660. var emitterMesh = this.emitter;
  53661. serializationObject.emitterId = emitterMesh.id;
  53662. }
  53663. else {
  53664. var emitterPosition = this.emitter;
  53665. serializationObject.emitter = emitterPosition.asArray();
  53666. }
  53667. serializationObject.capacity = this.getCapacity();
  53668. if (this.particleTexture) {
  53669. serializationObject.textureName = this.particleTexture.name;
  53670. }
  53671. // Animations
  53672. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  53673. // Particle system
  53674. serializationObject.activeParticleCount = this.activeParticleCount;
  53675. serializationObject.randomTextureSize = this._randomTextureSize;
  53676. serializationObject.minSize = this.minSize;
  53677. serializationObject.maxSize = this.maxSize;
  53678. serializationObject.minEmitPower = this.minEmitPower;
  53679. serializationObject.maxEmitPower = this.maxEmitPower;
  53680. serializationObject.minLifeTime = this.minLifeTime;
  53681. serializationObject.maxLifeTime = this.maxLifeTime;
  53682. serializationObject.emitRate = this.emitRate;
  53683. serializationObject.gravity = this.gravity.asArray();
  53684. serializationObject.color1 = this.color1.asArray();
  53685. serializationObject.color2 = this.color2.asArray();
  53686. serializationObject.colorDead = this.colorDead.asArray();
  53687. serializationObject.updateSpeed = this.updateSpeed;
  53688. serializationObject.targetStopDuration = this.targetStopDuration;
  53689. serializationObject.blendMode = this.blendMode;
  53690. // Emitter
  53691. if (this.particleEmitterType) {
  53692. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  53693. }
  53694. return serializationObject;
  53695. };
  53696. /**
  53697. * Parses a JSON object to create a GPU particle system.
  53698. * @param parsedParticleSystem The JSON object to parse
  53699. * @param scene The scene to create the particle system in
  53700. * @param rootUrl The root url to use to load external dependencies like texture
  53701. * @returns the parsed GPU particle system
  53702. */
  53703. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  53704. var name = parsedParticleSystem.name;
  53705. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  53706. if (parsedParticleSystem.id) {
  53707. particleSystem.id = parsedParticleSystem.id;
  53708. }
  53709. // Texture
  53710. if (parsedParticleSystem.textureName) {
  53711. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  53712. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  53713. }
  53714. // Emitter
  53715. if (parsedParticleSystem.emitterId) {
  53716. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  53717. }
  53718. else {
  53719. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  53720. }
  53721. // Animations
  53722. if (parsedParticleSystem.animations) {
  53723. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  53724. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  53725. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  53726. }
  53727. }
  53728. // Particle system
  53729. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  53730. particleSystem.minSize = parsedParticleSystem.minSize;
  53731. particleSystem.maxSize = parsedParticleSystem.maxSize;
  53732. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  53733. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  53734. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  53735. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  53736. particleSystem.emitRate = parsedParticleSystem.emitRate;
  53737. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  53738. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  53739. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  53740. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  53741. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  53742. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  53743. particleSystem.blendMode = parsedParticleSystem.blendMode;
  53744. // Emitter
  53745. if (parsedParticleSystem.particleEmitterType) {
  53746. var emitterType = void 0;
  53747. switch (parsedParticleSystem.particleEmitterType.type) {
  53748. case "SphereEmitter":
  53749. emitterType = new BABYLON.SphereParticleEmitter();
  53750. break;
  53751. case "SphereDirectedParticleEmitter":
  53752. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  53753. break;
  53754. case "ConeEmitter":
  53755. emitterType = new BABYLON.ConeParticleEmitter();
  53756. break;
  53757. case "BoxEmitter":
  53758. default:
  53759. emitterType = new BABYLON.BoxParticleEmitter();
  53760. break;
  53761. }
  53762. emitterType.parse(parsedParticleSystem.particleEmitterType);
  53763. particleSystem.particleEmitterType = emitterType;
  53764. }
  53765. return particleSystem;
  53766. };
  53767. return GPUParticleSystem;
  53768. }());
  53769. BABYLON.GPUParticleSystem = GPUParticleSystem;
  53770. })(BABYLON || (BABYLON = {}));
  53771. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  53772. "use strict";
  53773. var BABYLON;
  53774. (function (BABYLON) {
  53775. /**
  53776. * Represents one particle of a solid particle system.
  53777. * @see SolidParticleSystem
  53778. */
  53779. var SolidParticle = /** @class */ (function () {
  53780. /**
  53781. * Creates a Solid Particle object.
  53782. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  53783. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  53784. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  53785. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  53786. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  53787. * @param shapeId (integer) is the model shape identifier in the SPS.
  53788. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  53789. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  53790. */
  53791. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  53792. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  53793. /**
  53794. * particle global index
  53795. */
  53796. this.idx = 0;
  53797. /**
  53798. * The color of the particle
  53799. */
  53800. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53801. /**
  53802. * The world space position of the particle.
  53803. */
  53804. this.position = BABYLON.Vector3.Zero();
  53805. /**
  53806. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  53807. */
  53808. this.rotation = BABYLON.Vector3.Zero();
  53809. /**
  53810. * The scaling of the particle.
  53811. */
  53812. this.scaling = BABYLON.Vector3.One();
  53813. /**
  53814. * The uvs of the particle.
  53815. */
  53816. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  53817. /**
  53818. * The current speed of the particle.
  53819. */
  53820. this.velocity = BABYLON.Vector3.Zero();
  53821. /**
  53822. * The pivot point in the particle local space.
  53823. */
  53824. this.pivot = BABYLON.Vector3.Zero();
  53825. /**
  53826. * Must the particle be translated from its pivot point in its local space ?
  53827. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  53828. * Default : false
  53829. */
  53830. this.translateFromPivot = false;
  53831. /**
  53832. * Is the particle active or not ?
  53833. */
  53834. this.alive = true;
  53835. /**
  53836. * Is the particle visible or not ?
  53837. */
  53838. this.isVisible = true;
  53839. /**
  53840. * Index of this particle in the global "positions" array (Internal use)
  53841. */
  53842. this._pos = 0;
  53843. /**
  53844. * Index of this particle in the global "indices" array (Internal use)
  53845. */
  53846. this._ind = 0;
  53847. /**
  53848. * ModelShape id of this particle
  53849. */
  53850. this.shapeId = 0;
  53851. /**
  53852. * Index of the particle in its shape id (Internal use)
  53853. */
  53854. this.idxInShape = 0;
  53855. /**
  53856. * Still set as invisible in order to skip useless computations (Internal use)
  53857. */
  53858. this._stillInvisible = false;
  53859. /**
  53860. * Last computed particle rotation matrix
  53861. */
  53862. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  53863. /**
  53864. * Parent particle Id, if any.
  53865. * Default null.
  53866. */
  53867. this.parentId = null;
  53868. /**
  53869. * Internal global position in the SPS.
  53870. */
  53871. this._globalPosition = BABYLON.Vector3.Zero();
  53872. this.idx = particleIndex;
  53873. this._pos = positionIndex;
  53874. this._ind = indiceIndex;
  53875. this._model = model;
  53876. this.shapeId = shapeId;
  53877. this.idxInShape = idxInShape;
  53878. this._sps = sps;
  53879. if (modelBoundingInfo) {
  53880. this._modelBoundingInfo = modelBoundingInfo;
  53881. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  53882. }
  53883. }
  53884. Object.defineProperty(SolidParticle.prototype, "scale", {
  53885. /**
  53886. * Legacy support, changed scale to scaling
  53887. */
  53888. get: function () {
  53889. return this.scaling;
  53890. },
  53891. /**
  53892. * Legacy support, changed scale to scaling
  53893. */
  53894. set: function (scale) {
  53895. this.scaling = scale;
  53896. },
  53897. enumerable: true,
  53898. configurable: true
  53899. });
  53900. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  53901. /**
  53902. * Legacy support, changed quaternion to rotationQuaternion
  53903. */
  53904. get: function () {
  53905. return this.rotationQuaternion;
  53906. },
  53907. /**
  53908. * Legacy support, changed quaternion to rotationQuaternion
  53909. */
  53910. set: function (q) {
  53911. this.rotationQuaternion = q;
  53912. },
  53913. enumerable: true,
  53914. configurable: true
  53915. });
  53916. /**
  53917. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  53918. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  53919. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  53920. * @returns true if it intersects
  53921. */
  53922. SolidParticle.prototype.intersectsMesh = function (target) {
  53923. if (!this._boundingInfo || !target._boundingInfo) {
  53924. return false;
  53925. }
  53926. if (this._sps._bSphereOnly) {
  53927. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  53928. }
  53929. return this._boundingInfo.intersects(target._boundingInfo, false);
  53930. };
  53931. return SolidParticle;
  53932. }());
  53933. BABYLON.SolidParticle = SolidParticle;
  53934. /**
  53935. * Represents the shape of the model used by one particle of a solid particle system.
  53936. * SPS internal tool, don't use it manually.
  53937. * @see SolidParticleSystem
  53938. */
  53939. var ModelShape = /** @class */ (function () {
  53940. /**
  53941. * 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.
  53942. * SPS internal tool, don't use it manually.
  53943. * @ignore
  53944. */
  53945. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  53946. /**
  53947. * length of the shape in the model indices array (internal use)
  53948. */
  53949. this._indicesLength = 0;
  53950. this.shapeID = id;
  53951. this._shape = shape;
  53952. this._indicesLength = indicesLength;
  53953. this._shapeUV = shapeUV;
  53954. this._positionFunction = posFunction;
  53955. this._vertexFunction = vtxFunction;
  53956. }
  53957. return ModelShape;
  53958. }());
  53959. BABYLON.ModelShape = ModelShape;
  53960. /**
  53961. * Represents a Depth Sorted Particle in the solid particle system.
  53962. * @see SolidParticleSystem
  53963. */
  53964. var DepthSortedParticle = /** @class */ (function () {
  53965. function DepthSortedParticle() {
  53966. /**
  53967. * Index of the particle in the "indices" array
  53968. */
  53969. this.ind = 0;
  53970. /**
  53971. * Length of the particle shape in the "indices" array
  53972. */
  53973. this.indicesLength = 0;
  53974. /**
  53975. * Squared distance from the particle to the camera
  53976. */
  53977. this.sqDistance = 0.0;
  53978. }
  53979. return DepthSortedParticle;
  53980. }());
  53981. BABYLON.DepthSortedParticle = DepthSortedParticle;
  53982. })(BABYLON || (BABYLON = {}));
  53983. //# sourceMappingURL=babylon.solidParticle.js.map
  53984. "use strict";
  53985. var BABYLON;
  53986. (function (BABYLON) {
  53987. /**
  53988. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  53989. *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.
  53990. * The SPS is also a particle system. It provides some methods to manage the particles.
  53991. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  53992. *
  53993. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  53994. */
  53995. var SolidParticleSystem = /** @class */ (function () {
  53996. /**
  53997. * Creates a SPS (Solid Particle System) object.
  53998. * @param name (String) is the SPS name, this will be the underlying mesh name.
  53999. * @param scene (Scene) is the scene in which the SPS is added.
  54000. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  54001. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  54002. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  54003. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  54004. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  54005. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  54006. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  54007. */
  54008. function SolidParticleSystem(name, scene, options) {
  54009. /**
  54010. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  54011. * Example : var p = SPS.particles[i];
  54012. */
  54013. this.particles = new Array();
  54014. /**
  54015. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  54016. */
  54017. this.nbParticles = 0;
  54018. /**
  54019. * If the particles must ever face the camera (default false). Useful for planar particles.
  54020. */
  54021. this.billboard = false;
  54022. /**
  54023. * Recompute normals when adding a shape
  54024. */
  54025. this.recomputeNormals = true;
  54026. /**
  54027. * This a counter ofr your own usage. It's not set by any SPS functions.
  54028. */
  54029. this.counter = 0;
  54030. /**
  54031. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  54032. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  54033. */
  54034. this.vars = {};
  54035. /**
  54036. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  54037. */
  54038. this._bSphereOnly = false;
  54039. /**
  54040. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  54041. */
  54042. this._bSphereRadiusFactor = 1.0;
  54043. this._positions = new Array();
  54044. this._indices = new Array();
  54045. this._normals = new Array();
  54046. this._colors = new Array();
  54047. this._uvs = new Array();
  54048. this._index = 0; // indices index
  54049. this._updatable = true;
  54050. this._pickable = false;
  54051. this._isVisibilityBoxLocked = false;
  54052. this._alwaysVisible = false;
  54053. this._depthSort = false;
  54054. this._shapeCounter = 0;
  54055. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  54056. this._color = new BABYLON.Color4(0, 0, 0, 0);
  54057. this._computeParticleColor = true;
  54058. this._computeParticleTexture = true;
  54059. this._computeParticleRotation = true;
  54060. this._computeParticleVertex = false;
  54061. this._computeBoundingBox = false;
  54062. this._depthSortParticles = true;
  54063. this._cam_axisZ = BABYLON.Vector3.Zero();
  54064. this._cam_axisY = BABYLON.Vector3.Zero();
  54065. this._cam_axisX = BABYLON.Vector3.Zero();
  54066. this._axisZ = BABYLON.Axis.Z;
  54067. this._camDir = BABYLON.Vector3.Zero();
  54068. this._camInvertedPosition = BABYLON.Vector3.Zero();
  54069. this._rotMatrix = new BABYLON.Matrix();
  54070. this._invertMatrix = new BABYLON.Matrix();
  54071. this._rotated = BABYLON.Vector3.Zero();
  54072. this._quaternion = new BABYLON.Quaternion();
  54073. this._vertex = BABYLON.Vector3.Zero();
  54074. this._normal = BABYLON.Vector3.Zero();
  54075. this._yaw = 0.0;
  54076. this._pitch = 0.0;
  54077. this._roll = 0.0;
  54078. this._halfroll = 0.0;
  54079. this._halfpitch = 0.0;
  54080. this._halfyaw = 0.0;
  54081. this._sinRoll = 0.0;
  54082. this._cosRoll = 0.0;
  54083. this._sinPitch = 0.0;
  54084. this._cosPitch = 0.0;
  54085. this._sinYaw = 0.0;
  54086. this._cosYaw = 0.0;
  54087. this._mustUnrotateFixedNormals = false;
  54088. this._minimum = BABYLON.Vector3.Zero();
  54089. this._maximum = BABYLON.Vector3.Zero();
  54090. this._minBbox = BABYLON.Vector3.Zero();
  54091. this._maxBbox = BABYLON.Vector3.Zero();
  54092. this._particlesIntersect = false;
  54093. this._depthSortFunction = function (p1, p2) {
  54094. return (p2.sqDistance - p1.sqDistance);
  54095. };
  54096. this._needs32Bits = false;
  54097. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  54098. this._scaledPivot = BABYLON.Vector3.Zero();
  54099. this._particleHasParent = false;
  54100. this.name = name;
  54101. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  54102. this._camera = scene.activeCamera;
  54103. this._pickable = options ? options.isPickable : false;
  54104. this._depthSort = options ? options.enableDepthSort : false;
  54105. this._particlesIntersect = options ? options.particleIntersection : false;
  54106. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  54107. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  54108. if (options && options.updatable) {
  54109. this._updatable = options.updatable;
  54110. }
  54111. else {
  54112. this._updatable = true;
  54113. }
  54114. if (this._pickable) {
  54115. this.pickedParticles = [];
  54116. }
  54117. if (this._depthSort) {
  54118. this.depthSortedParticles = [];
  54119. }
  54120. }
  54121. /**
  54122. * Builds the SPS underlying mesh. Returns a standard Mesh.
  54123. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  54124. * @returns the created mesh
  54125. */
  54126. SolidParticleSystem.prototype.buildMesh = function () {
  54127. if (this.nbParticles === 0) {
  54128. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  54129. this.addShape(triangle, 1);
  54130. triangle.dispose();
  54131. }
  54132. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  54133. this._positions32 = new Float32Array(this._positions);
  54134. this._uvs32 = new Float32Array(this._uvs);
  54135. this._colors32 = new Float32Array(this._colors);
  54136. if (this.recomputeNormals) {
  54137. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  54138. }
  54139. this._normals32 = new Float32Array(this._normals);
  54140. this._fixedNormal32 = new Float32Array(this._normals);
  54141. if (this._mustUnrotateFixedNormals) {
  54142. this._unrotateFixedNormals();
  54143. }
  54144. var vertexData = new BABYLON.VertexData();
  54145. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  54146. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  54147. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  54148. if (this._uvs32) {
  54149. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  54150. ;
  54151. }
  54152. if (this._colors32) {
  54153. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  54154. }
  54155. var mesh = new BABYLON.Mesh(this.name, this._scene);
  54156. vertexData.applyToMesh(mesh, this._updatable);
  54157. this.mesh = mesh;
  54158. this.mesh.isPickable = this._pickable;
  54159. // free memory
  54160. if (!this._depthSort) {
  54161. this._indices = null;
  54162. }
  54163. this._positions = null;
  54164. this._normals = null;
  54165. this._uvs = null;
  54166. this._colors = null;
  54167. if (!this._updatable) {
  54168. this.particles.length = 0;
  54169. }
  54170. return mesh;
  54171. };
  54172. /**
  54173. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  54174. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  54175. * Thus the particles generated from `digest()` have their property `position` set yet.
  54176. * @param mesh ( Mesh ) is the mesh to be digested
  54177. * @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
  54178. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  54179. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  54180. * @returns the current SPS
  54181. */
  54182. SolidParticleSystem.prototype.digest = function (mesh, options) {
  54183. var size = (options && options.facetNb) || 1;
  54184. var number = (options && options.number) || 0;
  54185. var delta = (options && options.delta) || 0;
  54186. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54187. var meshInd = mesh.getIndices();
  54188. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54189. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  54190. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54191. var f = 0; // facet counter
  54192. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  54193. // compute size from number
  54194. if (number) {
  54195. number = (number > totalFacets) ? totalFacets : number;
  54196. size = Math.round(totalFacets / number);
  54197. delta = 0;
  54198. }
  54199. else {
  54200. size = (size > totalFacets) ? totalFacets : size;
  54201. }
  54202. var facetPos = []; // submesh positions
  54203. var facetInd = []; // submesh indices
  54204. var facetUV = []; // submesh UV
  54205. var facetCol = []; // submesh colors
  54206. var barycenter = BABYLON.Vector3.Zero();
  54207. var sizeO = size;
  54208. while (f < totalFacets) {
  54209. size = sizeO + Math.floor((1 + delta) * Math.random());
  54210. if (f > totalFacets - size) {
  54211. size = totalFacets - f;
  54212. }
  54213. // reset temp arrays
  54214. facetPos.length = 0;
  54215. facetInd.length = 0;
  54216. facetUV.length = 0;
  54217. facetCol.length = 0;
  54218. // iterate over "size" facets
  54219. var fi = 0;
  54220. for (var j = f * 3; j < (f + size) * 3; j++) {
  54221. facetInd.push(fi);
  54222. var i = meshInd[j];
  54223. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  54224. if (meshUV) {
  54225. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  54226. }
  54227. if (meshCol) {
  54228. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  54229. }
  54230. fi++;
  54231. }
  54232. // create a model shape for each single particle
  54233. var idx = this.nbParticles;
  54234. var shape = this._posToShape(facetPos);
  54235. var shapeUV = this._uvsToShapeUV(facetUV);
  54236. // compute the barycenter of the shape
  54237. var v;
  54238. for (v = 0; v < shape.length; v++) {
  54239. barycenter.addInPlace(shape[v]);
  54240. }
  54241. barycenter.scaleInPlace(1 / shape.length);
  54242. // shift the shape from its barycenter to the origin
  54243. for (v = 0; v < shape.length; v++) {
  54244. shape[v].subtractInPlace(barycenter);
  54245. }
  54246. var bInfo;
  54247. if (this._particlesIntersect) {
  54248. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  54249. }
  54250. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  54251. // add the particle in the SPS
  54252. var currentPos = this._positions.length;
  54253. var currentInd = this._indices.length;
  54254. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  54255. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  54256. // initialize the particle position
  54257. this.particles[this.nbParticles].position.addInPlace(barycenter);
  54258. this._index += shape.length;
  54259. idx++;
  54260. this.nbParticles++;
  54261. this._shapeCounter++;
  54262. f += size;
  54263. }
  54264. return this;
  54265. };
  54266. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  54267. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  54268. var index = 0;
  54269. var idx = 0;
  54270. for (var p = 0; p < this.particles.length; p++) {
  54271. this._particle = this.particles[p];
  54272. this._shape = this._particle._model._shape;
  54273. if (this._particle.rotationQuaternion) {
  54274. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  54275. }
  54276. else {
  54277. this._yaw = this._particle.rotation.y;
  54278. this._pitch = this._particle.rotation.x;
  54279. this._roll = this._particle.rotation.z;
  54280. this._quaternionRotationYPR();
  54281. }
  54282. this._quaternionToRotationMatrix();
  54283. this._rotMatrix.invertToRef(this._invertMatrix);
  54284. for (var pt = 0; pt < this._shape.length; pt++) {
  54285. idx = index + pt * 3;
  54286. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  54287. this._fixedNormal32[idx] = this._normal.x;
  54288. this._fixedNormal32[idx + 1] = this._normal.y;
  54289. this._fixedNormal32[idx + 2] = this._normal.z;
  54290. }
  54291. index = idx + 3;
  54292. }
  54293. };
  54294. //reset copy
  54295. SolidParticleSystem.prototype._resetCopy = function () {
  54296. this._copy.position.x = 0;
  54297. this._copy.position.y = 0;
  54298. this._copy.position.z = 0;
  54299. this._copy.rotation.x = 0;
  54300. this._copy.rotation.y = 0;
  54301. this._copy.rotation.z = 0;
  54302. this._copy.rotationQuaternion = null;
  54303. this._copy.scaling.x = 1.0;
  54304. this._copy.scaling.y = 1.0;
  54305. this._copy.scaling.z = 1.0;
  54306. this._copy.uvs.x = 0;
  54307. this._copy.uvs.y = 0;
  54308. this._copy.uvs.z = 1.0;
  54309. this._copy.uvs.w = 1.0;
  54310. this._copy.color = null;
  54311. this._copy.translateFromPivot = false;
  54312. };
  54313. // _meshBuilder : inserts the shape model in the global SPS mesh
  54314. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  54315. var i;
  54316. var u = 0;
  54317. var c = 0;
  54318. var n = 0;
  54319. this._resetCopy();
  54320. if (options && options.positionFunction) {
  54321. options.positionFunction(this._copy, idx, idxInShape);
  54322. this._mustUnrotateFixedNormals = true;
  54323. }
  54324. if (this._copy.rotationQuaternion) {
  54325. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  54326. }
  54327. else {
  54328. this._yaw = this._copy.rotation.y;
  54329. this._pitch = this._copy.rotation.x;
  54330. this._roll = this._copy.rotation.z;
  54331. this._quaternionRotationYPR();
  54332. }
  54333. this._quaternionToRotationMatrix();
  54334. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  54335. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  54336. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  54337. if (this._copy.translateFromPivot) {
  54338. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  54339. }
  54340. else {
  54341. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  54342. }
  54343. for (i = 0; i < shape.length; i++) {
  54344. this._vertex.x = shape[i].x;
  54345. this._vertex.y = shape[i].y;
  54346. this._vertex.z = shape[i].z;
  54347. if (options && options.vertexFunction) {
  54348. options.vertexFunction(this._copy, this._vertex, i);
  54349. }
  54350. this._vertex.x *= this._copy.scaling.x;
  54351. this._vertex.y *= this._copy.scaling.y;
  54352. this._vertex.z *= this._copy.scaling.z;
  54353. this._vertex.x -= this._scaledPivot.x;
  54354. this._vertex.y -= this._scaledPivot.y;
  54355. this._vertex.z -= this._scaledPivot.z;
  54356. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  54357. this._rotated.addInPlace(this._pivotBackTranslation);
  54358. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  54359. if (meshUV) {
  54360. 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);
  54361. u += 2;
  54362. }
  54363. if (this._copy.color) {
  54364. this._color = this._copy.color;
  54365. }
  54366. else if (meshCol && meshCol[c] !== undefined) {
  54367. this._color.r = meshCol[c];
  54368. this._color.g = meshCol[c + 1];
  54369. this._color.b = meshCol[c + 2];
  54370. this._color.a = meshCol[c + 3];
  54371. }
  54372. else {
  54373. this._color.r = 1.0;
  54374. this._color.g = 1.0;
  54375. this._color.b = 1.0;
  54376. this._color.a = 1.0;
  54377. }
  54378. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  54379. c += 4;
  54380. if (!this.recomputeNormals && meshNor) {
  54381. this._normal.x = meshNor[n];
  54382. this._normal.y = meshNor[n + 1];
  54383. this._normal.z = meshNor[n + 2];
  54384. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  54385. normals.push(this._normal.x, this._normal.y, this._normal.z);
  54386. n += 3;
  54387. }
  54388. }
  54389. for (i = 0; i < meshInd.length; i++) {
  54390. var current_ind = p + meshInd[i];
  54391. indices.push(current_ind);
  54392. if (current_ind > 65535) {
  54393. this._needs32Bits = true;
  54394. }
  54395. }
  54396. if (this._pickable) {
  54397. var nbfaces = meshInd.length / 3;
  54398. for (i = 0; i < nbfaces; i++) {
  54399. this.pickedParticles.push({ idx: idx, faceId: i });
  54400. }
  54401. }
  54402. if (this._depthSort) {
  54403. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  54404. }
  54405. return this._copy;
  54406. };
  54407. // returns a shape array from positions array
  54408. SolidParticleSystem.prototype._posToShape = function (positions) {
  54409. var shape = [];
  54410. for (var i = 0; i < positions.length; i += 3) {
  54411. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  54412. }
  54413. return shape;
  54414. };
  54415. // returns a shapeUV array from a Vector4 uvs
  54416. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  54417. var shapeUV = [];
  54418. if (uvs) {
  54419. for (var i = 0; i < uvs.length; i++)
  54420. shapeUV.push(uvs[i]);
  54421. }
  54422. return shapeUV;
  54423. };
  54424. // adds a new particle object in the particles array
  54425. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  54426. if (bInfo === void 0) { bInfo = null; }
  54427. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  54428. this.particles.push(sp);
  54429. return sp;
  54430. };
  54431. /**
  54432. * Adds some particles to the SPS from the model shape. Returns the shape id.
  54433. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  54434. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  54435. * @param nb (positive integer) the number of particles to be created from this model
  54436. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  54437. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  54438. * @returns the number of shapes in the system
  54439. */
  54440. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  54441. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54442. var meshInd = mesh.getIndices();
  54443. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54444. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  54445. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54446. var bbInfo;
  54447. if (this._particlesIntersect) {
  54448. bbInfo = mesh.getBoundingInfo();
  54449. }
  54450. var shape = this._posToShape(meshPos);
  54451. var shapeUV = this._uvsToShapeUV(meshUV);
  54452. var posfunc = options ? options.positionFunction : null;
  54453. var vtxfunc = options ? options.vertexFunction : null;
  54454. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  54455. // particles
  54456. var sp;
  54457. var currentCopy;
  54458. var idx = this.nbParticles;
  54459. for (var i = 0; i < nb; i++) {
  54460. var currentPos = this._positions.length;
  54461. var currentInd = this._indices.length;
  54462. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  54463. if (this._updatable) {
  54464. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  54465. sp.position.copyFrom(currentCopy.position);
  54466. sp.rotation.copyFrom(currentCopy.rotation);
  54467. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  54468. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  54469. }
  54470. if (currentCopy.color && sp.color) {
  54471. sp.color.copyFrom(currentCopy.color);
  54472. }
  54473. sp.scaling.copyFrom(currentCopy.scaling);
  54474. sp.uvs.copyFrom(currentCopy.uvs);
  54475. }
  54476. this._index += shape.length;
  54477. idx++;
  54478. }
  54479. this.nbParticles += nb;
  54480. this._shapeCounter++;
  54481. return this._shapeCounter - 1;
  54482. };
  54483. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  54484. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  54485. this._resetCopy();
  54486. if (particle._model._positionFunction) {
  54487. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  54488. }
  54489. if (this._copy.rotationQuaternion) {
  54490. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  54491. }
  54492. else {
  54493. this._yaw = this._copy.rotation.y;
  54494. this._pitch = this._copy.rotation.x;
  54495. this._roll = this._copy.rotation.z;
  54496. this._quaternionRotationYPR();
  54497. }
  54498. this._quaternionToRotationMatrix();
  54499. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  54500. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  54501. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  54502. if (this._copy.translateFromPivot) {
  54503. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  54504. }
  54505. else {
  54506. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  54507. }
  54508. this._shape = particle._model._shape;
  54509. for (var pt = 0; pt < this._shape.length; pt++) {
  54510. this._vertex.x = this._shape[pt].x;
  54511. this._vertex.y = this._shape[pt].y;
  54512. this._vertex.z = this._shape[pt].z;
  54513. if (particle._model._vertexFunction) {
  54514. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  54515. }
  54516. this._vertex.x *= this._copy.scaling.x;
  54517. this._vertex.y *= this._copy.scaling.y;
  54518. this._vertex.z *= this._copy.scaling.z;
  54519. this._vertex.x -= this._scaledPivot.x;
  54520. this._vertex.y -= this._scaledPivot.y;
  54521. this._vertex.z -= this._scaledPivot.z;
  54522. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  54523. this._rotated.addInPlace(this._pivotBackTranslation);
  54524. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  54525. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  54526. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  54527. }
  54528. particle.position.x = 0.0;
  54529. particle.position.y = 0.0;
  54530. particle.position.z = 0.0;
  54531. particle.rotation.x = 0.0;
  54532. particle.rotation.y = 0.0;
  54533. particle.rotation.z = 0.0;
  54534. particle.rotationQuaternion = null;
  54535. particle.scaling.x = 1.0;
  54536. particle.scaling.y = 1.0;
  54537. particle.scaling.z = 1.0;
  54538. particle.uvs.x = 0.0;
  54539. particle.uvs.y = 0.0;
  54540. particle.uvs.z = 1.0;
  54541. particle.uvs.w = 1.0;
  54542. particle.pivot.x = 0.0;
  54543. particle.pivot.y = 0.0;
  54544. particle.pivot.z = 0.0;
  54545. particle.translateFromPivot = false;
  54546. particle.parentId = null;
  54547. };
  54548. /**
  54549. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  54550. * @returns the SPS.
  54551. */
  54552. SolidParticleSystem.prototype.rebuildMesh = function () {
  54553. for (var p = 0; p < this.particles.length; p++) {
  54554. this._rebuildParticle(this.particles[p]);
  54555. }
  54556. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  54557. return this;
  54558. };
  54559. /**
  54560. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  54561. * This method calls `updateParticle()` for each particle of the SPS.
  54562. * For an animated SPS, it is usually called within the render loop.
  54563. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  54564. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  54565. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  54566. * @returns the SPS.
  54567. */
  54568. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  54569. if (start === void 0) { start = 0; }
  54570. if (end === void 0) { end = this.nbParticles - 1; }
  54571. if (update === void 0) { update = true; }
  54572. if (!this._updatable) {
  54573. return this;
  54574. }
  54575. // custom beforeUpdate
  54576. this.beforeUpdateParticles(start, end, update);
  54577. this._cam_axisX.x = 1.0;
  54578. this._cam_axisX.y = 0.0;
  54579. this._cam_axisX.z = 0.0;
  54580. this._cam_axisY.x = 0.0;
  54581. this._cam_axisY.y = 1.0;
  54582. this._cam_axisY.z = 0.0;
  54583. this._cam_axisZ.x = 0.0;
  54584. this._cam_axisZ.y = 0.0;
  54585. this._cam_axisZ.z = 1.0;
  54586. // cases when the World Matrix is to be computed first
  54587. if (this.billboard || this._depthSort) {
  54588. this.mesh.computeWorldMatrix(true);
  54589. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  54590. }
  54591. // if the particles will always face the camera
  54592. if (this.billboard) {
  54593. // compute the camera position and un-rotate it by the current mesh rotation
  54594. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  54595. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  54596. this._cam_axisZ.normalize();
  54597. // same for camera up vector extracted from the cam view matrix
  54598. var view = this._camera.getViewMatrix(true);
  54599. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  54600. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  54601. this._cam_axisY.normalize();
  54602. this._cam_axisX.normalize();
  54603. }
  54604. // if depthSort, compute the camera global position in the mesh local system
  54605. if (this._depthSort) {
  54606. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  54607. }
  54608. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  54609. var idx = 0; // current position index in the global array positions32
  54610. var index = 0; // position start index in the global array positions32 of the current particle
  54611. var colidx = 0; // current color index in the global array colors32
  54612. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  54613. var uvidx = 0; // current uv index in the global array uvs32
  54614. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  54615. var pt = 0; // current index in the particle model shape
  54616. if (this.mesh.isFacetDataEnabled) {
  54617. this._computeBoundingBox = true;
  54618. }
  54619. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  54620. if (this._computeBoundingBox) {
  54621. if (start == 0 && end == this.nbParticles - 1) {
  54622. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  54623. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  54624. }
  54625. else {
  54626. if (this.mesh._boundingInfo) {
  54627. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  54628. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  54629. }
  54630. }
  54631. }
  54632. // particle loop
  54633. index = this.particles[start]._pos;
  54634. var vpos = (index / 3) | 0;
  54635. colorIndex = vpos * 4;
  54636. uvIndex = vpos * 2;
  54637. for (var p = start; p <= end; p++) {
  54638. this._particle = this.particles[p];
  54639. this._shape = this._particle._model._shape;
  54640. this._shapeUV = this._particle._model._shapeUV;
  54641. // call to custom user function to update the particle properties
  54642. this.updateParticle(this._particle);
  54643. // camera-particle distance for depth sorting
  54644. if (this._depthSort && this._depthSortParticles) {
  54645. var dsp = this.depthSortedParticles[p];
  54646. dsp.ind = this._particle._ind;
  54647. dsp.indicesLength = this._particle._model._indicesLength;
  54648. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  54649. }
  54650. // skip the computations for inactive or already invisible particles
  54651. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  54652. // increment indexes for the next particle
  54653. pt = this._shape.length;
  54654. index += pt * 3;
  54655. colorIndex += pt * 4;
  54656. uvIndex += pt * 2;
  54657. continue;
  54658. }
  54659. if (this._particle.isVisible) {
  54660. this._particle._stillInvisible = false; // un-mark permanent invisibility
  54661. this._particleHasParent = (this._particle.parentId !== null);
  54662. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  54663. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  54664. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  54665. // particle rotation matrix
  54666. if (this.billboard) {
  54667. this._particle.rotation.x = 0.0;
  54668. this._particle.rotation.y = 0.0;
  54669. }
  54670. if (this._computeParticleRotation || this.billboard) {
  54671. if (this._particle.rotationQuaternion) {
  54672. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  54673. }
  54674. else {
  54675. this._yaw = this._particle.rotation.y;
  54676. this._pitch = this._particle.rotation.x;
  54677. this._roll = this._particle.rotation.z;
  54678. this._quaternionRotationYPR();
  54679. }
  54680. this._quaternionToRotationMatrix();
  54681. }
  54682. if (this._particleHasParent) {
  54683. this._parent = this.particles[this._particle.parentId];
  54684. 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];
  54685. 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];
  54686. 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];
  54687. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  54688. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  54689. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  54690. if (this._computeParticleRotation || this.billboard) {
  54691. 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];
  54692. 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];
  54693. 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];
  54694. 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];
  54695. 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];
  54696. 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];
  54697. 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];
  54698. 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];
  54699. 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];
  54700. }
  54701. }
  54702. else {
  54703. this._particle._globalPosition.x = this._particle.position.x;
  54704. this._particle._globalPosition.y = this._particle.position.y;
  54705. this._particle._globalPosition.z = this._particle.position.z;
  54706. if (this._computeParticleRotation || this.billboard) {
  54707. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  54708. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  54709. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  54710. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  54711. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  54712. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  54713. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  54714. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  54715. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  54716. }
  54717. }
  54718. if (this._particle.translateFromPivot) {
  54719. this._pivotBackTranslation.x = 0.0;
  54720. this._pivotBackTranslation.y = 0.0;
  54721. this._pivotBackTranslation.z = 0.0;
  54722. }
  54723. else {
  54724. this._pivotBackTranslation.x = this._scaledPivot.x;
  54725. this._pivotBackTranslation.y = this._scaledPivot.y;
  54726. this._pivotBackTranslation.z = this._scaledPivot.z;
  54727. }
  54728. // particle vertex loop
  54729. for (pt = 0; pt < this._shape.length; pt++) {
  54730. idx = index + pt * 3;
  54731. colidx = colorIndex + pt * 4;
  54732. uvidx = uvIndex + pt * 2;
  54733. this._vertex.x = this._shape[pt].x;
  54734. this._vertex.y = this._shape[pt].y;
  54735. this._vertex.z = this._shape[pt].z;
  54736. if (this._computeParticleVertex) {
  54737. this.updateParticleVertex(this._particle, this._vertex, pt);
  54738. }
  54739. // positions
  54740. this._vertex.x *= this._particle.scaling.x;
  54741. this._vertex.y *= this._particle.scaling.y;
  54742. this._vertex.z *= this._particle.scaling.z;
  54743. this._vertex.x -= this._scaledPivot.x;
  54744. this._vertex.y -= this._scaledPivot.y;
  54745. this._vertex.z -= this._scaledPivot.z;
  54746. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  54747. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  54748. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  54749. this._rotated.x += this._pivotBackTranslation.x;
  54750. this._rotated.y += this._pivotBackTranslation.y;
  54751. this._rotated.z += this._pivotBackTranslation.z;
  54752. 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;
  54753. 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;
  54754. 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;
  54755. if (this._computeBoundingBox) {
  54756. if (this._positions32[idx] < this._minimum.x) {
  54757. this._minimum.x = this._positions32[idx];
  54758. }
  54759. if (this._positions32[idx] > this._maximum.x) {
  54760. this._maximum.x = this._positions32[idx];
  54761. }
  54762. if (this._positions32[idx + 1] < this._minimum.y) {
  54763. this._minimum.y = this._positions32[idx + 1];
  54764. }
  54765. if (this._positions32[idx + 1] > this._maximum.y) {
  54766. this._maximum.y = this._positions32[idx + 1];
  54767. }
  54768. if (this._positions32[idx + 2] < this._minimum.z) {
  54769. this._minimum.z = this._positions32[idx + 2];
  54770. }
  54771. if (this._positions32[idx + 2] > this._maximum.z) {
  54772. this._maximum.z = this._positions32[idx + 2];
  54773. }
  54774. }
  54775. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  54776. if (!this._computeParticleVertex) {
  54777. this._normal.x = this._fixedNormal32[idx];
  54778. this._normal.y = this._fixedNormal32[idx + 1];
  54779. this._normal.z = this._fixedNormal32[idx + 2];
  54780. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  54781. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  54782. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  54783. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  54784. 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;
  54785. 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;
  54786. }
  54787. if (this._computeParticleColor && this._particle.color) {
  54788. this._colors32[colidx] = this._particle.color.r;
  54789. this._colors32[colidx + 1] = this._particle.color.g;
  54790. this._colors32[colidx + 2] = this._particle.color.b;
  54791. this._colors32[colidx + 3] = this._particle.color.a;
  54792. }
  54793. if (this._computeParticleTexture) {
  54794. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  54795. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  54796. }
  54797. }
  54798. }
  54799. else {
  54800. this._particle._stillInvisible = true; // mark the particle as invisible
  54801. for (pt = 0; pt < this._shape.length; pt++) {
  54802. idx = index + pt * 3;
  54803. colidx = colorIndex + pt * 4;
  54804. uvidx = uvIndex + pt * 2;
  54805. this._positions32[idx] = 0.0;
  54806. this._positions32[idx + 1] = 0.0;
  54807. this._positions32[idx + 2] = 0.0;
  54808. this._normals32[idx] = 0.0;
  54809. this._normals32[idx + 1] = 0.0;
  54810. this._normals32[idx + 2] = 0.0;
  54811. if (this._computeParticleColor && this._particle.color) {
  54812. this._colors32[colidx] = this._particle.color.r;
  54813. this._colors32[colidx + 1] = this._particle.color.g;
  54814. this._colors32[colidx + 2] = this._particle.color.b;
  54815. this._colors32[colidx + 3] = this._particle.color.a;
  54816. }
  54817. if (this._computeParticleTexture) {
  54818. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  54819. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  54820. }
  54821. }
  54822. }
  54823. // if the particle intersections must be computed : update the bbInfo
  54824. if (this._particlesIntersect) {
  54825. var bInfo = this._particle._boundingInfo;
  54826. var bBox = bInfo.boundingBox;
  54827. var bSphere = bInfo.boundingSphere;
  54828. if (!this._bSphereOnly) {
  54829. // place, scale and rotate the particle bbox within the SPS local system, then update it
  54830. for (var b = 0; b < bBox.vectors.length; b++) {
  54831. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  54832. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  54833. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  54834. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  54835. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  54836. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  54837. 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;
  54838. 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;
  54839. 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;
  54840. }
  54841. bBox._update(this.mesh._worldMatrix);
  54842. }
  54843. // place and scale the particle bouding sphere in the SPS local system, then update it
  54844. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  54845. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  54846. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  54847. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  54848. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  54849. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  54850. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  54851. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  54852. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  54853. 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));
  54854. bSphere._update(this.mesh._worldMatrix);
  54855. }
  54856. // increment indexes for the next particle
  54857. index = idx + 3;
  54858. colorIndex = colidx + 4;
  54859. uvIndex = uvidx + 2;
  54860. }
  54861. // if the VBO must be updated
  54862. if (update) {
  54863. if (this._computeParticleColor) {
  54864. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  54865. }
  54866. if (this._computeParticleTexture) {
  54867. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  54868. }
  54869. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  54870. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  54871. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  54872. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  54873. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  54874. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  54875. for (var i = 0; i < this._normals32.length; i++) {
  54876. this._fixedNormal32[i] = this._normals32[i];
  54877. }
  54878. }
  54879. if (!this.mesh.areNormalsFrozen) {
  54880. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  54881. }
  54882. }
  54883. if (this._depthSort && this._depthSortParticles) {
  54884. this.depthSortedParticles.sort(this._depthSortFunction);
  54885. var dspl = this.depthSortedParticles.length;
  54886. var sorted = 0;
  54887. var lind = 0;
  54888. var sind = 0;
  54889. var sid = 0;
  54890. for (sorted = 0; sorted < dspl; sorted++) {
  54891. lind = this.depthSortedParticles[sorted].indicesLength;
  54892. sind = this.depthSortedParticles[sorted].ind;
  54893. for (var i = 0; i < lind; i++) {
  54894. this._indices32[sid] = this._indices[sind + i];
  54895. sid++;
  54896. }
  54897. }
  54898. this.mesh.updateIndices(this._indices32);
  54899. }
  54900. }
  54901. if (this._computeBoundingBox) {
  54902. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  54903. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  54904. }
  54905. this.afterUpdateParticles(start, end, update);
  54906. return this;
  54907. };
  54908. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  54909. this._halfroll = this._roll * 0.5;
  54910. this._halfpitch = this._pitch * 0.5;
  54911. this._halfyaw = this._yaw * 0.5;
  54912. this._sinRoll = Math.sin(this._halfroll);
  54913. this._cosRoll = Math.cos(this._halfroll);
  54914. this._sinPitch = Math.sin(this._halfpitch);
  54915. this._cosPitch = Math.cos(this._halfpitch);
  54916. this._sinYaw = Math.sin(this._halfyaw);
  54917. this._cosYaw = Math.cos(this._halfyaw);
  54918. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  54919. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  54920. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  54921. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  54922. };
  54923. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  54924. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  54925. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  54926. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  54927. this._rotMatrix.m[3] = 0;
  54928. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  54929. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  54930. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  54931. this._rotMatrix.m[7] = 0;
  54932. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  54933. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  54934. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  54935. this._rotMatrix.m[11] = 0;
  54936. this._rotMatrix.m[12] = 0;
  54937. this._rotMatrix.m[13] = 0;
  54938. this._rotMatrix.m[14] = 0;
  54939. this._rotMatrix.m[15] = 1.0;
  54940. };
  54941. /**
  54942. * Disposes the SPS.
  54943. */
  54944. SolidParticleSystem.prototype.dispose = function () {
  54945. this.mesh.dispose();
  54946. this.vars = null;
  54947. // drop references to internal big arrays for the GC
  54948. this._positions = null;
  54949. this._indices = null;
  54950. this._normals = null;
  54951. this._uvs = null;
  54952. this._colors = null;
  54953. this._indices32 = null;
  54954. this._positions32 = null;
  54955. this._normals32 = null;
  54956. this._fixedNormal32 = null;
  54957. this._uvs32 = null;
  54958. this._colors32 = null;
  54959. this.pickedParticles = null;
  54960. };
  54961. /**
  54962. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  54963. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54964. * @returns the SPS.
  54965. */
  54966. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  54967. if (!this._isVisibilityBoxLocked) {
  54968. this.mesh.refreshBoundingInfo();
  54969. }
  54970. return this;
  54971. };
  54972. /**
  54973. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  54974. * @param size the size (float) of the visibility box
  54975. * note : this doesn't lock the SPS mesh bounding box.
  54976. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54977. */
  54978. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  54979. var vis = size / 2;
  54980. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  54981. };
  54982. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  54983. /**
  54984. * Gets whether the SPS as always visible or not
  54985. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54986. */
  54987. get: function () {
  54988. return this._alwaysVisible;
  54989. },
  54990. /**
  54991. * Sets the SPS as always visible or not
  54992. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54993. */
  54994. set: function (val) {
  54995. this._alwaysVisible = val;
  54996. this.mesh.alwaysSelectAsActiveMesh = val;
  54997. },
  54998. enumerable: true,
  54999. configurable: true
  55000. });
  55001. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  55002. /**
  55003. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  55004. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  55005. */
  55006. get: function () {
  55007. return this._isVisibilityBoxLocked;
  55008. },
  55009. /**
  55010. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  55011. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  55012. */
  55013. set: function (val) {
  55014. this._isVisibilityBoxLocked = val;
  55015. var boundingInfo = this.mesh.getBoundingInfo();
  55016. boundingInfo.isLocked = val;
  55017. },
  55018. enumerable: true,
  55019. configurable: true
  55020. });
  55021. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  55022. /**
  55023. * Gets if `setParticles()` computes the particle rotations or not.
  55024. * Default value : true. The SPS is faster when it's set to false.
  55025. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  55026. */
  55027. get: function () {
  55028. return this._computeParticleRotation;
  55029. },
  55030. /**
  55031. * Tells to `setParticles()` to compute the particle rotations or not.
  55032. * Default value : true. The SPS is faster when it's set to false.
  55033. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  55034. */
  55035. set: function (val) {
  55036. this._computeParticleRotation = val;
  55037. },
  55038. enumerable: true,
  55039. configurable: true
  55040. });
  55041. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  55042. /**
  55043. * Gets if `setParticles()` computes the particle colors or not.
  55044. * Default value : true. The SPS is faster when it's set to false.
  55045. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  55046. */
  55047. get: function () {
  55048. return this._computeParticleColor;
  55049. },
  55050. /**
  55051. * Tells to `setParticles()` to compute the particle colors or not.
  55052. * Default value : true. The SPS is faster when it's set to false.
  55053. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  55054. */
  55055. set: function (val) {
  55056. this._computeParticleColor = val;
  55057. },
  55058. enumerable: true,
  55059. configurable: true
  55060. });
  55061. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  55062. /**
  55063. * Gets if `setParticles()` computes the particle textures or not.
  55064. * Default value : true. The SPS is faster when it's set to false.
  55065. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  55066. */
  55067. get: function () {
  55068. return this._computeParticleTexture;
  55069. },
  55070. set: function (val) {
  55071. this._computeParticleTexture = val;
  55072. },
  55073. enumerable: true,
  55074. configurable: true
  55075. });
  55076. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  55077. /**
  55078. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  55079. * Default value : false. The SPS is faster when it's set to false.
  55080. * Note : the particle custom vertex positions aren't stored values.
  55081. */
  55082. get: function () {
  55083. return this._computeParticleVertex;
  55084. },
  55085. /**
  55086. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  55087. * Default value : false. The SPS is faster when it's set to false.
  55088. * Note : the particle custom vertex positions aren't stored values.
  55089. */
  55090. set: function (val) {
  55091. this._computeParticleVertex = val;
  55092. },
  55093. enumerable: true,
  55094. configurable: true
  55095. });
  55096. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  55097. /**
  55098. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  55099. */
  55100. get: function () {
  55101. return this._computeBoundingBox;
  55102. },
  55103. /**
  55104. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  55105. */
  55106. set: function (val) {
  55107. this._computeBoundingBox = val;
  55108. },
  55109. enumerable: true,
  55110. configurable: true
  55111. });
  55112. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  55113. /**
  55114. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  55115. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  55116. * Default : `true`
  55117. */
  55118. get: function () {
  55119. return this._depthSortParticles;
  55120. },
  55121. /**
  55122. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  55123. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  55124. * Default : `true`
  55125. */
  55126. set: function (val) {
  55127. this._depthSortParticles = val;
  55128. },
  55129. enumerable: true,
  55130. configurable: true
  55131. });
  55132. // =======================================================================
  55133. // Particle behavior logic
  55134. // these following methods may be overwritten by the user to fit his needs
  55135. /**
  55136. * This function does nothing. It may be overwritten to set all the particle first values.
  55137. * The SPS doesn't call this function, you may have to call it by your own.
  55138. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  55139. */
  55140. SolidParticleSystem.prototype.initParticles = function () {
  55141. };
  55142. /**
  55143. * This function does nothing. It may be overwritten to recycle a particle.
  55144. * The SPS doesn't call this function, you may have to call it by your own.
  55145. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  55146. * @param particle The particle to recycle
  55147. * @returns the recycled particle
  55148. */
  55149. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  55150. return particle;
  55151. };
  55152. /**
  55153. * Updates a particle : this function should be overwritten by the user.
  55154. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  55155. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  55156. * @example : just set a particle position or velocity and recycle conditions
  55157. * @param particle The particle to update
  55158. * @returns the updated particle
  55159. */
  55160. SolidParticleSystem.prototype.updateParticle = function (particle) {
  55161. return particle;
  55162. };
  55163. /**
  55164. * Updates a vertex of a particle : it can be overwritten by the user.
  55165. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  55166. * @param particle the current particle
  55167. * @param vertex the current index of the current particle
  55168. * @param pt the index of the current vertex in the particle shape
  55169. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  55170. * @example : just set a vertex particle position
  55171. * @returns the updated vertex
  55172. */
  55173. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  55174. return vertex;
  55175. };
  55176. /**
  55177. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  55178. * This does nothing and may be overwritten by the user.
  55179. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  55180. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  55181. * @param update the boolean update value actually passed to setParticles()
  55182. */
  55183. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  55184. };
  55185. /**
  55186. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  55187. * This will be passed three parameters.
  55188. * This does nothing and may be overwritten by the user.
  55189. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  55190. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  55191. * @param update the boolean update value actually passed to setParticles()
  55192. */
  55193. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  55194. };
  55195. return SolidParticleSystem;
  55196. }());
  55197. BABYLON.SolidParticleSystem = SolidParticleSystem;
  55198. })(BABYLON || (BABYLON = {}));
  55199. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  55200. "use strict";
  55201. var BABYLON;
  55202. (function (BABYLON) {
  55203. var ShaderMaterial = /** @class */ (function (_super) {
  55204. __extends(ShaderMaterial, _super);
  55205. function ShaderMaterial(name, scene, shaderPath, options) {
  55206. var _this = _super.call(this, name, scene) || this;
  55207. _this._textures = {};
  55208. _this._textureArrays = {};
  55209. _this._floats = {};
  55210. _this._ints = {};
  55211. _this._floatsArrays = {};
  55212. _this._colors3 = {};
  55213. _this._colors3Arrays = {};
  55214. _this._colors4 = {};
  55215. _this._vectors2 = {};
  55216. _this._vectors3 = {};
  55217. _this._vectors4 = {};
  55218. _this._matrices = {};
  55219. _this._matrices3x3 = {};
  55220. _this._matrices2x2 = {};
  55221. _this._vectors2Arrays = {};
  55222. _this._vectors3Arrays = {};
  55223. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  55224. _this._shaderPath = shaderPath;
  55225. options.needAlphaBlending = options.needAlphaBlending || false;
  55226. options.needAlphaTesting = options.needAlphaTesting || false;
  55227. options.attributes = options.attributes || ["position", "normal", "uv"];
  55228. options.uniforms = options.uniforms || ["worldViewProjection"];
  55229. options.uniformBuffers = options.uniformBuffers || [];
  55230. options.samplers = options.samplers || [];
  55231. options.defines = options.defines || [];
  55232. _this._options = options;
  55233. return _this;
  55234. }
  55235. ShaderMaterial.prototype.getClassName = function () {
  55236. return "ShaderMaterial";
  55237. };
  55238. ShaderMaterial.prototype.needAlphaBlending = function () {
  55239. return this._options.needAlphaBlending;
  55240. };
  55241. ShaderMaterial.prototype.needAlphaTesting = function () {
  55242. return this._options.needAlphaTesting;
  55243. };
  55244. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  55245. if (this._options.uniforms.indexOf(uniformName) === -1) {
  55246. this._options.uniforms.push(uniformName);
  55247. }
  55248. };
  55249. ShaderMaterial.prototype.setTexture = function (name, texture) {
  55250. if (this._options.samplers.indexOf(name) === -1) {
  55251. this._options.samplers.push(name);
  55252. }
  55253. this._textures[name] = texture;
  55254. return this;
  55255. };
  55256. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  55257. if (this._options.samplers.indexOf(name) === -1) {
  55258. this._options.samplers.push(name);
  55259. }
  55260. this._checkUniform(name);
  55261. this._textureArrays[name] = textures;
  55262. return this;
  55263. };
  55264. ShaderMaterial.prototype.setFloat = function (name, value) {
  55265. this._checkUniform(name);
  55266. this._floats[name] = value;
  55267. return this;
  55268. };
  55269. ShaderMaterial.prototype.setInt = function (name, value) {
  55270. this._checkUniform(name);
  55271. this._ints[name] = value;
  55272. return this;
  55273. };
  55274. ShaderMaterial.prototype.setFloats = function (name, value) {
  55275. this._checkUniform(name);
  55276. this._floatsArrays[name] = value;
  55277. return this;
  55278. };
  55279. ShaderMaterial.prototype.setColor3 = function (name, value) {
  55280. this._checkUniform(name);
  55281. this._colors3[name] = value;
  55282. return this;
  55283. };
  55284. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  55285. this._checkUniform(name);
  55286. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  55287. color.toArray(arr, arr.length);
  55288. return arr;
  55289. }, []);
  55290. return this;
  55291. };
  55292. ShaderMaterial.prototype.setColor4 = function (name, value) {
  55293. this._checkUniform(name);
  55294. this._colors4[name] = value;
  55295. return this;
  55296. };
  55297. ShaderMaterial.prototype.setVector2 = function (name, value) {
  55298. this._checkUniform(name);
  55299. this._vectors2[name] = value;
  55300. return this;
  55301. };
  55302. ShaderMaterial.prototype.setVector3 = function (name, value) {
  55303. this._checkUniform(name);
  55304. this._vectors3[name] = value;
  55305. return this;
  55306. };
  55307. ShaderMaterial.prototype.setVector4 = function (name, value) {
  55308. this._checkUniform(name);
  55309. this._vectors4[name] = value;
  55310. return this;
  55311. };
  55312. ShaderMaterial.prototype.setMatrix = function (name, value) {
  55313. this._checkUniform(name);
  55314. this._matrices[name] = value;
  55315. return this;
  55316. };
  55317. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  55318. this._checkUniform(name);
  55319. this._matrices3x3[name] = value;
  55320. return this;
  55321. };
  55322. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  55323. this._checkUniform(name);
  55324. this._matrices2x2[name] = value;
  55325. return this;
  55326. };
  55327. ShaderMaterial.prototype.setArray2 = function (name, value) {
  55328. this._checkUniform(name);
  55329. this._vectors2Arrays[name] = value;
  55330. return this;
  55331. };
  55332. ShaderMaterial.prototype.setArray3 = function (name, value) {
  55333. this._checkUniform(name);
  55334. this._vectors3Arrays[name] = value;
  55335. return this;
  55336. };
  55337. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  55338. if (!mesh) {
  55339. return true;
  55340. }
  55341. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  55342. return false;
  55343. }
  55344. return false;
  55345. };
  55346. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  55347. var scene = this.getScene();
  55348. var engine = scene.getEngine();
  55349. if (!this.checkReadyOnEveryCall) {
  55350. if (this._renderId === scene.getRenderId()) {
  55351. if (this._checkCache(scene, mesh, useInstances)) {
  55352. return true;
  55353. }
  55354. }
  55355. }
  55356. // Instances
  55357. var defines = [];
  55358. var attribs = [];
  55359. var fallbacks = new BABYLON.EffectFallbacks();
  55360. if (useInstances) {
  55361. defines.push("#define INSTANCES");
  55362. }
  55363. for (var index = 0; index < this._options.defines.length; index++) {
  55364. defines.push(this._options.defines[index]);
  55365. }
  55366. for (var index = 0; index < this._options.attributes.length; index++) {
  55367. attribs.push(this._options.attributes[index]);
  55368. }
  55369. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  55370. attribs.push(BABYLON.VertexBuffer.ColorKind);
  55371. defines.push("#define VERTEXCOLOR");
  55372. }
  55373. // Bones
  55374. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  55375. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  55376. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  55377. if (mesh.numBoneInfluencers > 4) {
  55378. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  55379. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  55380. }
  55381. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  55382. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  55383. fallbacks.addCPUSkinningFallback(0, mesh);
  55384. if (this._options.uniforms.indexOf("mBones") === -1) {
  55385. this._options.uniforms.push("mBones");
  55386. }
  55387. }
  55388. else {
  55389. defines.push("#define NUM_BONE_INFLUENCERS 0");
  55390. }
  55391. // Textures
  55392. for (var name in this._textures) {
  55393. if (!this._textures[name].isReady()) {
  55394. return false;
  55395. }
  55396. }
  55397. // Alpha test
  55398. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  55399. defines.push("#define ALPHATEST");
  55400. }
  55401. var previousEffect = this._effect;
  55402. var join = defines.join("\n");
  55403. this._effect = engine.createEffect(this._shaderPath, {
  55404. attributes: attribs,
  55405. uniformsNames: this._options.uniforms,
  55406. uniformBuffersNames: this._options.uniformBuffers,
  55407. samplers: this._options.samplers,
  55408. defines: join,
  55409. fallbacks: fallbacks,
  55410. onCompiled: this.onCompiled,
  55411. onError: this.onError
  55412. }, engine);
  55413. if (!this._effect.isReady()) {
  55414. return false;
  55415. }
  55416. if (previousEffect !== this._effect) {
  55417. scene.resetCachedMaterial();
  55418. }
  55419. this._renderId = scene.getRenderId();
  55420. return true;
  55421. };
  55422. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  55423. var scene = this.getScene();
  55424. if (!this._effect) {
  55425. return;
  55426. }
  55427. if (this._options.uniforms.indexOf("world") !== -1) {
  55428. this._effect.setMatrix("world", world);
  55429. }
  55430. if (this._options.uniforms.indexOf("worldView") !== -1) {
  55431. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  55432. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  55433. }
  55434. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  55435. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  55436. }
  55437. };
  55438. ShaderMaterial.prototype.bind = function (world, mesh) {
  55439. // Std values
  55440. this.bindOnlyWorldMatrix(world);
  55441. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  55442. if (this._options.uniforms.indexOf("view") !== -1) {
  55443. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  55444. }
  55445. if (this._options.uniforms.indexOf("projection") !== -1) {
  55446. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  55447. }
  55448. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  55449. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  55450. }
  55451. // Bones
  55452. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  55453. var name;
  55454. // Texture
  55455. for (name in this._textures) {
  55456. this._effect.setTexture(name, this._textures[name]);
  55457. }
  55458. // Texture arrays
  55459. for (name in this._textureArrays) {
  55460. this._effect.setTextureArray(name, this._textureArrays[name]);
  55461. }
  55462. // Int
  55463. for (name in this._ints) {
  55464. this._effect.setInt(name, this._ints[name]);
  55465. }
  55466. // Float
  55467. for (name in this._floats) {
  55468. this._effect.setFloat(name, this._floats[name]);
  55469. }
  55470. // Floats
  55471. for (name in this._floatsArrays) {
  55472. this._effect.setArray(name, this._floatsArrays[name]);
  55473. }
  55474. // Color3
  55475. for (name in this._colors3) {
  55476. this._effect.setColor3(name, this._colors3[name]);
  55477. }
  55478. for (name in this._colors3Arrays) {
  55479. this._effect.setArray3(name, this._colors3Arrays[name]);
  55480. }
  55481. // Color4
  55482. for (name in this._colors4) {
  55483. var color = this._colors4[name];
  55484. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  55485. }
  55486. // Vector2
  55487. for (name in this._vectors2) {
  55488. this._effect.setVector2(name, this._vectors2[name]);
  55489. }
  55490. // Vector3
  55491. for (name in this._vectors3) {
  55492. this._effect.setVector3(name, this._vectors3[name]);
  55493. }
  55494. // Vector4
  55495. for (name in this._vectors4) {
  55496. this._effect.setVector4(name, this._vectors4[name]);
  55497. }
  55498. // Matrix
  55499. for (name in this._matrices) {
  55500. this._effect.setMatrix(name, this._matrices[name]);
  55501. }
  55502. // Matrix 3x3
  55503. for (name in this._matrices3x3) {
  55504. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  55505. }
  55506. // Matrix 2x2
  55507. for (name in this._matrices2x2) {
  55508. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  55509. }
  55510. // Vector2Array
  55511. for (name in this._vectors2Arrays) {
  55512. this._effect.setArray2(name, this._vectors2Arrays[name]);
  55513. }
  55514. // Vector3Array
  55515. for (name in this._vectors3Arrays) {
  55516. this._effect.setArray3(name, this._vectors3Arrays[name]);
  55517. }
  55518. }
  55519. this._afterBind(mesh);
  55520. };
  55521. ShaderMaterial.prototype.getActiveTextures = function () {
  55522. var activeTextures = _super.prototype.getActiveTextures.call(this);
  55523. for (var name in this._textures) {
  55524. activeTextures.push(this._textures[name]);
  55525. }
  55526. for (var name in this._textureArrays) {
  55527. var array = this._textureArrays[name];
  55528. for (var index = 0; index < array.length; index++) {
  55529. activeTextures.push(array[index]);
  55530. }
  55531. }
  55532. return activeTextures;
  55533. };
  55534. ShaderMaterial.prototype.hasTexture = function (texture) {
  55535. if (_super.prototype.hasTexture.call(this, texture)) {
  55536. return true;
  55537. }
  55538. for (var name in this._textures) {
  55539. if (this._textures[name] === texture) {
  55540. return true;
  55541. }
  55542. }
  55543. for (var name in this._textureArrays) {
  55544. var array = this._textureArrays[name];
  55545. for (var index = 0; index < array.length; index++) {
  55546. if (array[index] === texture) {
  55547. return true;
  55548. }
  55549. }
  55550. }
  55551. return false;
  55552. };
  55553. ShaderMaterial.prototype.clone = function (name) {
  55554. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  55555. return newShaderMaterial;
  55556. };
  55557. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  55558. if (forceDisposeTextures) {
  55559. var name;
  55560. for (name in this._textures) {
  55561. this._textures[name].dispose();
  55562. }
  55563. for (name in this._textureArrays) {
  55564. var array = this._textureArrays[name];
  55565. for (var index = 0; index < array.length; index++) {
  55566. array[index].dispose();
  55567. }
  55568. }
  55569. }
  55570. this._textures = {};
  55571. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  55572. };
  55573. ShaderMaterial.prototype.serialize = function () {
  55574. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  55575. serializationObject.customType = "BABYLON.ShaderMaterial";
  55576. serializationObject.options = this._options;
  55577. serializationObject.shaderPath = this._shaderPath;
  55578. var name;
  55579. // Texture
  55580. serializationObject.textures = {};
  55581. for (name in this._textures) {
  55582. serializationObject.textures[name] = this._textures[name].serialize();
  55583. }
  55584. // Texture arrays
  55585. serializationObject.textureArrays = {};
  55586. for (name in this._textureArrays) {
  55587. serializationObject.textureArrays[name] = [];
  55588. var array = this._textureArrays[name];
  55589. for (var index = 0; index < array.length; index++) {
  55590. serializationObject.textureArrays[name].push(array[index].serialize());
  55591. }
  55592. }
  55593. // Float
  55594. serializationObject.floats = {};
  55595. for (name in this._floats) {
  55596. serializationObject.floats[name] = this._floats[name];
  55597. }
  55598. // Float s
  55599. serializationObject.FloatArrays = {};
  55600. for (name in this._floatsArrays) {
  55601. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  55602. }
  55603. // Color3
  55604. serializationObject.colors3 = {};
  55605. for (name in this._colors3) {
  55606. serializationObject.colors3[name] = this._colors3[name].asArray();
  55607. }
  55608. // Color3 array
  55609. serializationObject.colors3Arrays = {};
  55610. for (name in this._colors3Arrays) {
  55611. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  55612. }
  55613. // Color4
  55614. serializationObject.colors4 = {};
  55615. for (name in this._colors4) {
  55616. serializationObject.colors4[name] = this._colors4[name].asArray();
  55617. }
  55618. // Vector2
  55619. serializationObject.vectors2 = {};
  55620. for (name in this._vectors2) {
  55621. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  55622. }
  55623. // Vector3
  55624. serializationObject.vectors3 = {};
  55625. for (name in this._vectors3) {
  55626. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  55627. }
  55628. // Vector4
  55629. serializationObject.vectors4 = {};
  55630. for (name in this._vectors4) {
  55631. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  55632. }
  55633. // Matrix
  55634. serializationObject.matrices = {};
  55635. for (name in this._matrices) {
  55636. serializationObject.matrices[name] = this._matrices[name].asArray();
  55637. }
  55638. // Matrix 3x3
  55639. serializationObject.matrices3x3 = {};
  55640. for (name in this._matrices3x3) {
  55641. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  55642. }
  55643. // Matrix 2x2
  55644. serializationObject.matrices2x2 = {};
  55645. for (name in this._matrices2x2) {
  55646. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  55647. }
  55648. // Vector2Array
  55649. serializationObject.vectors2Arrays = {};
  55650. for (name in this._vectors2Arrays) {
  55651. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  55652. }
  55653. // Vector3Array
  55654. serializationObject.vectors3Arrays = {};
  55655. for (name in this._vectors3Arrays) {
  55656. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  55657. }
  55658. return serializationObject;
  55659. };
  55660. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  55661. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  55662. var name;
  55663. // Texture
  55664. for (name in source.textures) {
  55665. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  55666. }
  55667. // Texture arrays
  55668. for (name in source.textureArrays) {
  55669. var array = source.textureArrays[name];
  55670. var textureArray = new Array();
  55671. for (var index = 0; index < array.length; index++) {
  55672. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  55673. }
  55674. material.setTextureArray(name, textureArray);
  55675. }
  55676. // Float
  55677. for (name in source.floats) {
  55678. material.setFloat(name, source.floats[name]);
  55679. }
  55680. // Float s
  55681. for (name in source.floatsArrays) {
  55682. material.setFloats(name, source.floatsArrays[name]);
  55683. }
  55684. // Color3
  55685. for (name in source.colors3) {
  55686. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  55687. }
  55688. // Color3 arrays
  55689. for (name in source.colors3Arrays) {
  55690. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  55691. if (i % 3 === 0) {
  55692. arr.push([num]);
  55693. }
  55694. else {
  55695. arr[arr.length - 1].push(num);
  55696. }
  55697. return arr;
  55698. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  55699. material.setColor3Array(name, colors);
  55700. }
  55701. // Color4
  55702. for (name in source.colors4) {
  55703. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  55704. }
  55705. // Vector2
  55706. for (name in source.vectors2) {
  55707. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  55708. }
  55709. // Vector3
  55710. for (name in source.vectors3) {
  55711. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  55712. }
  55713. // Vector4
  55714. for (name in source.vectors4) {
  55715. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  55716. }
  55717. // Matrix
  55718. for (name in source.matrices) {
  55719. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  55720. }
  55721. // Matrix 3x3
  55722. for (name in source.matrices3x3) {
  55723. material.setMatrix3x3(name, source.matrices3x3[name]);
  55724. }
  55725. // Matrix 2x2
  55726. for (name in source.matrices2x2) {
  55727. material.setMatrix2x2(name, source.matrices2x2[name]);
  55728. }
  55729. // Vector2Array
  55730. for (name in source.vectors2Arrays) {
  55731. material.setArray2(name, source.vectors2Arrays[name]);
  55732. }
  55733. // Vector3Array
  55734. for (name in source.vectors3Arrays) {
  55735. material.setArray3(name, source.vectors3Arrays[name]);
  55736. }
  55737. return material;
  55738. };
  55739. return ShaderMaterial;
  55740. }(BABYLON.Material));
  55741. BABYLON.ShaderMaterial = ShaderMaterial;
  55742. })(BABYLON || (BABYLON = {}));
  55743. //# sourceMappingURL=babylon.shaderMaterial.js.map
  55744. "use strict";
  55745. var BABYLON;
  55746. (function (BABYLON) {
  55747. var GroundMesh = /** @class */ (function (_super) {
  55748. __extends(GroundMesh, _super);
  55749. function GroundMesh(name, scene) {
  55750. var _this = _super.call(this, name, scene) || this;
  55751. _this.generateOctree = false;
  55752. return _this;
  55753. }
  55754. GroundMesh.prototype.getClassName = function () {
  55755. return "GroundMesh";
  55756. };
  55757. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  55758. get: function () {
  55759. return Math.min(this._subdivisionsX, this._subdivisionsY);
  55760. },
  55761. enumerable: true,
  55762. configurable: true
  55763. });
  55764. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  55765. get: function () {
  55766. return this._subdivisionsX;
  55767. },
  55768. enumerable: true,
  55769. configurable: true
  55770. });
  55771. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  55772. get: function () {
  55773. return this._subdivisionsY;
  55774. },
  55775. enumerable: true,
  55776. configurable: true
  55777. });
  55778. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  55779. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  55780. this._subdivisionsX = chunksCount;
  55781. this._subdivisionsY = chunksCount;
  55782. this.subdivide(chunksCount);
  55783. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  55784. };
  55785. /**
  55786. * Returns a height (y) value in the Worl system :
  55787. * the ground altitude at the coordinates (x, z) expressed in the World system.
  55788. * Returns the ground y position if (x, z) are outside the ground surface.
  55789. */
  55790. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  55791. var world = this.getWorldMatrix();
  55792. var invMat = BABYLON.Tmp.Matrix[5];
  55793. world.invertToRef(invMat);
  55794. var tmpVect = BABYLON.Tmp.Vector3[8];
  55795. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  55796. x = tmpVect.x;
  55797. z = tmpVect.z;
  55798. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  55799. return this.position.y;
  55800. }
  55801. if (!this._heightQuads || this._heightQuads.length == 0) {
  55802. this._initHeightQuads();
  55803. this._computeHeightQuads();
  55804. }
  55805. var facet = this._getFacetAt(x, z);
  55806. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  55807. // return y in the World system
  55808. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  55809. return tmpVect.y;
  55810. };
  55811. /**
  55812. * Returns a normalized vector (Vector3) orthogonal to the ground
  55813. * at the ground coordinates (x, z) expressed in the World system.
  55814. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  55815. */
  55816. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  55817. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  55818. this.getNormalAtCoordinatesToRef(x, z, normal);
  55819. return normal;
  55820. };
  55821. /**
  55822. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  55823. * at the ground coordinates (x, z) expressed in the World system.
  55824. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  55825. * Returns the GroundMesh.
  55826. */
  55827. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  55828. var world = this.getWorldMatrix();
  55829. var tmpMat = BABYLON.Tmp.Matrix[5];
  55830. world.invertToRef(tmpMat);
  55831. var tmpVect = BABYLON.Tmp.Vector3[8];
  55832. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  55833. x = tmpVect.x;
  55834. z = tmpVect.z;
  55835. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  55836. return this;
  55837. }
  55838. if (!this._heightQuads || this._heightQuads.length == 0) {
  55839. this._initHeightQuads();
  55840. this._computeHeightQuads();
  55841. }
  55842. var facet = this._getFacetAt(x, z);
  55843. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  55844. return this;
  55845. };
  55846. /**
  55847. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  55848. * if the ground has been updated.
  55849. * This can be used in the render loop.
  55850. * Returns the GroundMesh.
  55851. */
  55852. GroundMesh.prototype.updateCoordinateHeights = function () {
  55853. if (!this._heightQuads || this._heightQuads.length == 0) {
  55854. this._initHeightQuads();
  55855. }
  55856. this._computeHeightQuads();
  55857. return this;
  55858. };
  55859. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  55860. GroundMesh.prototype._getFacetAt = function (x, z) {
  55861. // retrieve col and row from x, z coordinates in the ground local system
  55862. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  55863. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  55864. var quad = this._heightQuads[row * this._subdivisionsX + col];
  55865. var facet;
  55866. if (z < quad.slope.x * x + quad.slope.y) {
  55867. facet = quad.facet1;
  55868. }
  55869. else {
  55870. facet = quad.facet2;
  55871. }
  55872. return facet;
  55873. };
  55874. // Creates and populates the heightMap array with "facet" elements :
  55875. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  55876. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  55877. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  55878. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  55879. // Returns the GroundMesh.
  55880. GroundMesh.prototype._initHeightQuads = function () {
  55881. var subdivisionsX = this._subdivisionsX;
  55882. var subdivisionsY = this._subdivisionsY;
  55883. this._heightQuads = new Array();
  55884. for (var row = 0; row < subdivisionsY; row++) {
  55885. for (var col = 0; col < subdivisionsX; col++) {
  55886. 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) };
  55887. this._heightQuads[row * subdivisionsX + col] = quad;
  55888. }
  55889. }
  55890. return this;
  55891. };
  55892. // Compute each quad element values and update the the heightMap array :
  55893. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  55894. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  55895. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  55896. // Returns the GroundMesh.
  55897. GroundMesh.prototype._computeHeightQuads = function () {
  55898. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55899. if (!positions) {
  55900. return this;
  55901. }
  55902. var v1 = BABYLON.Tmp.Vector3[3];
  55903. var v2 = BABYLON.Tmp.Vector3[2];
  55904. var v3 = BABYLON.Tmp.Vector3[1];
  55905. var v4 = BABYLON.Tmp.Vector3[0];
  55906. var v1v2 = BABYLON.Tmp.Vector3[4];
  55907. var v1v3 = BABYLON.Tmp.Vector3[5];
  55908. var v1v4 = BABYLON.Tmp.Vector3[6];
  55909. var norm1 = BABYLON.Tmp.Vector3[7];
  55910. var norm2 = BABYLON.Tmp.Vector3[8];
  55911. var i = 0;
  55912. var j = 0;
  55913. var k = 0;
  55914. var cd = 0; // 2D slope coefficient : z = cd * x + h
  55915. var h = 0;
  55916. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  55917. var d2 = 0;
  55918. var subdivisionsX = this._subdivisionsX;
  55919. var subdivisionsY = this._subdivisionsY;
  55920. for (var row = 0; row < subdivisionsY; row++) {
  55921. for (var col = 0; col < subdivisionsX; col++) {
  55922. i = col * 3;
  55923. j = row * (subdivisionsX + 1) * 3;
  55924. k = (row + 1) * (subdivisionsX + 1) * 3;
  55925. v1.x = positions[j + i];
  55926. v1.y = positions[j + i + 1];
  55927. v1.z = positions[j + i + 2];
  55928. v2.x = positions[j + i + 3];
  55929. v2.y = positions[j + i + 4];
  55930. v2.z = positions[j + i + 5];
  55931. v3.x = positions[k + i];
  55932. v3.y = positions[k + i + 1];
  55933. v3.z = positions[k + i + 2];
  55934. v4.x = positions[k + i + 3];
  55935. v4.y = positions[k + i + 4];
  55936. v4.z = positions[k + i + 5];
  55937. // 2D slope V1V4
  55938. cd = (v4.z - v1.z) / (v4.x - v1.x);
  55939. h = v1.z - cd * v1.x; // v1 belongs to the slope
  55940. // facet equations :
  55941. // we compute each facet normal vector
  55942. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  55943. // we compute the value d by applying the equation to v1 which belongs to the plane
  55944. // then we store the facet equation in a Vector4
  55945. v2.subtractToRef(v1, v1v2);
  55946. v3.subtractToRef(v1, v1v3);
  55947. v4.subtractToRef(v1, v1v4);
  55948. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  55949. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  55950. norm1.normalize();
  55951. norm2.normalize();
  55952. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  55953. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  55954. var quad = this._heightQuads[row * subdivisionsX + col];
  55955. quad.slope.copyFromFloats(cd, h);
  55956. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  55957. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  55958. }
  55959. }
  55960. return this;
  55961. };
  55962. GroundMesh.prototype.serialize = function (serializationObject) {
  55963. _super.prototype.serialize.call(this, serializationObject);
  55964. serializationObject.subdivisionsX = this._subdivisionsX;
  55965. serializationObject.subdivisionsY = this._subdivisionsY;
  55966. serializationObject.minX = this._minX;
  55967. serializationObject.maxX = this._maxX;
  55968. serializationObject.minZ = this._minZ;
  55969. serializationObject.maxZ = this._maxZ;
  55970. serializationObject.width = this._width;
  55971. serializationObject.height = this._height;
  55972. };
  55973. GroundMesh.Parse = function (parsedMesh, scene) {
  55974. var result = new GroundMesh(parsedMesh.name, scene);
  55975. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  55976. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  55977. result._minX = parsedMesh.minX;
  55978. result._maxX = parsedMesh.maxX;
  55979. result._minZ = parsedMesh.minZ;
  55980. result._maxZ = parsedMesh.maxZ;
  55981. result._width = parsedMesh.width;
  55982. result._height = parsedMesh.height;
  55983. return result;
  55984. };
  55985. return GroundMesh;
  55986. }(BABYLON.Mesh));
  55987. BABYLON.GroundMesh = GroundMesh;
  55988. })(BABYLON || (BABYLON = {}));
  55989. //# sourceMappingURL=babylon.groundMesh.js.map
  55990. "use strict";
  55991. var BABYLON;
  55992. (function (BABYLON) {
  55993. /**
  55994. * Creates an instance based on a source mesh.
  55995. */
  55996. var InstancedMesh = /** @class */ (function (_super) {
  55997. __extends(InstancedMesh, _super);
  55998. function InstancedMesh(name, source) {
  55999. var _this = _super.call(this, name, source.getScene()) || this;
  56000. source.instances.push(_this);
  56001. _this._sourceMesh = source;
  56002. _this.position.copyFrom(source.position);
  56003. _this.rotation.copyFrom(source.rotation);
  56004. _this.scaling.copyFrom(source.scaling);
  56005. if (source.rotationQuaternion) {
  56006. _this.rotationQuaternion = source.rotationQuaternion.clone();
  56007. }
  56008. _this.infiniteDistance = source.infiniteDistance;
  56009. _this.setPivotMatrix(source.getPivotMatrix());
  56010. _this.refreshBoundingInfo();
  56011. _this._syncSubMeshes();
  56012. return _this;
  56013. }
  56014. /**
  56015. * Returns the string "InstancedMesh".
  56016. */
  56017. InstancedMesh.prototype.getClassName = function () {
  56018. return "InstancedMesh";
  56019. };
  56020. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  56021. // Methods
  56022. get: function () {
  56023. return this._sourceMesh.receiveShadows;
  56024. },
  56025. enumerable: true,
  56026. configurable: true
  56027. });
  56028. Object.defineProperty(InstancedMesh.prototype, "material", {
  56029. get: function () {
  56030. return this._sourceMesh.material;
  56031. },
  56032. enumerable: true,
  56033. configurable: true
  56034. });
  56035. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  56036. get: function () {
  56037. return this._sourceMesh.visibility;
  56038. },
  56039. enumerable: true,
  56040. configurable: true
  56041. });
  56042. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  56043. get: function () {
  56044. return this._sourceMesh.skeleton;
  56045. },
  56046. enumerable: true,
  56047. configurable: true
  56048. });
  56049. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  56050. get: function () {
  56051. return this._sourceMesh.renderingGroupId;
  56052. },
  56053. set: function (value) {
  56054. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  56055. return;
  56056. }
  56057. //no-op with warning
  56058. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  56059. },
  56060. enumerable: true,
  56061. configurable: true
  56062. });
  56063. /**
  56064. * Returns the total number of vertices (integer).
  56065. */
  56066. InstancedMesh.prototype.getTotalVertices = function () {
  56067. return this._sourceMesh.getTotalVertices();
  56068. };
  56069. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  56070. get: function () {
  56071. return this._sourceMesh;
  56072. },
  56073. enumerable: true,
  56074. configurable: true
  56075. });
  56076. /**
  56077. * Is this node ready to be used/rendered
  56078. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  56079. * @return {boolean} is it ready
  56080. */
  56081. InstancedMesh.prototype.isReady = function (completeCheck) {
  56082. if (completeCheck === void 0) { completeCheck = false; }
  56083. return this._sourceMesh.isReady(completeCheck, true);
  56084. };
  56085. /**
  56086. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  56087. */
  56088. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  56089. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  56090. };
  56091. /**
  56092. * Sets the vertex data of the mesh geometry for the requested `kind`.
  56093. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  56094. * The `data` are either a numeric array either a Float32Array.
  56095. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  56096. * 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).
  56097. * Note that a new underlying VertexBuffer object is created each call.
  56098. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  56099. *
  56100. * Possible `kind` values :
  56101. * - BABYLON.VertexBuffer.PositionKind
  56102. * - BABYLON.VertexBuffer.UVKind
  56103. * - BABYLON.VertexBuffer.UV2Kind
  56104. * - BABYLON.VertexBuffer.UV3Kind
  56105. * - BABYLON.VertexBuffer.UV4Kind
  56106. * - BABYLON.VertexBuffer.UV5Kind
  56107. * - BABYLON.VertexBuffer.UV6Kind
  56108. * - BABYLON.VertexBuffer.ColorKind
  56109. * - BABYLON.VertexBuffer.MatricesIndicesKind
  56110. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  56111. * - BABYLON.VertexBuffer.MatricesWeightsKind
  56112. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  56113. *
  56114. * Returns the Mesh.
  56115. */
  56116. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  56117. if (this.sourceMesh) {
  56118. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  56119. }
  56120. return this.sourceMesh;
  56121. };
  56122. /**
  56123. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  56124. * If the mesh has no geometry, it is simply returned as it is.
  56125. * The `data` are either a numeric array either a Float32Array.
  56126. * No new underlying VertexBuffer object is created.
  56127. * 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.
  56128. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  56129. *
  56130. * Possible `kind` values :
  56131. * - BABYLON.VertexBuffer.PositionKind
  56132. * - BABYLON.VertexBuffer.UVKind
  56133. * - BABYLON.VertexBuffer.UV2Kind
  56134. * - BABYLON.VertexBuffer.UV3Kind
  56135. * - BABYLON.VertexBuffer.UV4Kind
  56136. * - BABYLON.VertexBuffer.UV5Kind
  56137. * - BABYLON.VertexBuffer.UV6Kind
  56138. * - BABYLON.VertexBuffer.ColorKind
  56139. * - BABYLON.VertexBuffer.MatricesIndicesKind
  56140. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  56141. * - BABYLON.VertexBuffer.MatricesWeightsKind
  56142. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  56143. *
  56144. * Returns the Mesh.
  56145. */
  56146. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  56147. if (this.sourceMesh) {
  56148. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  56149. }
  56150. return this.sourceMesh;
  56151. };
  56152. /**
  56153. * Sets the mesh indices.
  56154. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  56155. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  56156. * This method creates a new index buffer each call.
  56157. * Returns the Mesh.
  56158. */
  56159. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  56160. if (totalVertices === void 0) { totalVertices = null; }
  56161. if (this.sourceMesh) {
  56162. this.sourceMesh.setIndices(indices, totalVertices);
  56163. }
  56164. return this.sourceMesh;
  56165. };
  56166. /**
  56167. * Boolean : True if the mesh owns the requested kind of data.
  56168. */
  56169. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  56170. return this._sourceMesh.isVerticesDataPresent(kind);
  56171. };
  56172. /**
  56173. * Returns an array of indices (IndicesArray).
  56174. */
  56175. InstancedMesh.prototype.getIndices = function () {
  56176. return this._sourceMesh.getIndices();
  56177. };
  56178. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  56179. get: function () {
  56180. return this._sourceMesh._positions;
  56181. },
  56182. enumerable: true,
  56183. configurable: true
  56184. });
  56185. /**
  56186. * Sets a new updated BoundingInfo to the mesh.
  56187. * Returns the mesh.
  56188. */
  56189. InstancedMesh.prototype.refreshBoundingInfo = function () {
  56190. var meshBB = this._sourceMesh.getBoundingInfo();
  56191. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  56192. this._updateBoundingInfo();
  56193. return this;
  56194. };
  56195. InstancedMesh.prototype._preActivate = function () {
  56196. if (this._currentLOD) {
  56197. this._currentLOD._preActivate();
  56198. }
  56199. return this;
  56200. };
  56201. InstancedMesh.prototype._activate = function (renderId) {
  56202. if (this._currentLOD) {
  56203. this._currentLOD._registerInstanceForRenderId(this, renderId);
  56204. }
  56205. return this;
  56206. };
  56207. /**
  56208. * Returns the current associated LOD AbstractMesh.
  56209. */
  56210. InstancedMesh.prototype.getLOD = function (camera) {
  56211. if (!camera) {
  56212. return this;
  56213. }
  56214. var boundingInfo = this.getBoundingInfo();
  56215. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  56216. if (this._currentLOD === this.sourceMesh) {
  56217. return this;
  56218. }
  56219. return this._currentLOD;
  56220. };
  56221. InstancedMesh.prototype._syncSubMeshes = function () {
  56222. this.releaseSubMeshes();
  56223. if (this._sourceMesh.subMeshes) {
  56224. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  56225. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  56226. }
  56227. }
  56228. return this;
  56229. };
  56230. InstancedMesh.prototype._generatePointsArray = function () {
  56231. return this._sourceMesh._generatePointsArray();
  56232. };
  56233. /**
  56234. * Creates a new InstancedMesh from the current mesh.
  56235. * - name (string) : the cloned mesh name
  56236. * - newParent (optional Node) : the optional Node to parent the clone to.
  56237. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  56238. *
  56239. * Returns the clone.
  56240. */
  56241. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  56242. var result = this._sourceMesh.createInstance(name);
  56243. // Deep copy
  56244. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  56245. // Bounding info
  56246. this.refreshBoundingInfo();
  56247. // Parent
  56248. if (newParent) {
  56249. result.parent = newParent;
  56250. }
  56251. if (!doNotCloneChildren) {
  56252. // Children
  56253. for (var index = 0; index < this.getScene().meshes.length; index++) {
  56254. var mesh = this.getScene().meshes[index];
  56255. if (mesh.parent === this) {
  56256. mesh.clone(mesh.name, result);
  56257. }
  56258. }
  56259. }
  56260. result.computeWorldMatrix(true);
  56261. return result;
  56262. };
  56263. /**
  56264. * Disposes the InstancedMesh.
  56265. * Returns nothing.
  56266. */
  56267. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  56268. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  56269. // Remove from mesh
  56270. var index = this._sourceMesh.instances.indexOf(this);
  56271. this._sourceMesh.instances.splice(index, 1);
  56272. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  56273. };
  56274. return InstancedMesh;
  56275. }(BABYLON.AbstractMesh));
  56276. BABYLON.InstancedMesh = InstancedMesh;
  56277. })(BABYLON || (BABYLON = {}));
  56278. //# sourceMappingURL=babylon.instancedMesh.js.map
  56279. "use strict";
  56280. var BABYLON;
  56281. (function (BABYLON) {
  56282. var LinesMesh = /** @class */ (function (_super) {
  56283. __extends(LinesMesh, _super);
  56284. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  56285. if (scene === void 0) { scene = null; }
  56286. if (parent === void 0) { parent = null; }
  56287. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  56288. _this.useVertexColor = useVertexColor;
  56289. _this.useVertexAlpha = useVertexAlpha;
  56290. _this.color = new BABYLON.Color3(1, 1, 1);
  56291. _this.alpha = 1;
  56292. if (source) {
  56293. _this.color = source.color.clone();
  56294. _this.alpha = source.alpha;
  56295. _this.useVertexColor = source.useVertexColor;
  56296. _this.useVertexAlpha = source.useVertexAlpha;
  56297. }
  56298. _this._intersectionThreshold = 0.1;
  56299. var defines = [];
  56300. var options = {
  56301. attributes: [BABYLON.VertexBuffer.PositionKind],
  56302. uniforms: ["world", "viewProjection"],
  56303. needAlphaBlending: true,
  56304. defines: defines
  56305. };
  56306. if (useVertexAlpha === false) {
  56307. options.needAlphaBlending = false;
  56308. }
  56309. if (!useVertexColor) {
  56310. options.uniforms.push("color");
  56311. }
  56312. else {
  56313. options.defines.push("#define VERTEXCOLOR");
  56314. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  56315. }
  56316. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  56317. return _this;
  56318. }
  56319. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  56320. /**
  56321. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  56322. * This margin is expressed in world space coordinates, so its value may vary.
  56323. * Default value is 0.1
  56324. * @returns the intersection Threshold value.
  56325. */
  56326. get: function () {
  56327. return this._intersectionThreshold;
  56328. },
  56329. /**
  56330. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  56331. * This margin is expressed in world space coordinates, so its value may vary.
  56332. * @param value the new threshold to apply
  56333. */
  56334. set: function (value) {
  56335. if (this._intersectionThreshold === value) {
  56336. return;
  56337. }
  56338. this._intersectionThreshold = value;
  56339. if (this.geometry) {
  56340. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  56341. }
  56342. },
  56343. enumerable: true,
  56344. configurable: true
  56345. });
  56346. /**
  56347. * Returns the string "LineMesh"
  56348. */
  56349. LinesMesh.prototype.getClassName = function () {
  56350. return "LinesMesh";
  56351. };
  56352. Object.defineProperty(LinesMesh.prototype, "material", {
  56353. get: function () {
  56354. return this._colorShader;
  56355. },
  56356. set: function (value) {
  56357. // Do nothing
  56358. },
  56359. enumerable: true,
  56360. configurable: true
  56361. });
  56362. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  56363. get: function () {
  56364. return false;
  56365. },
  56366. enumerable: true,
  56367. configurable: true
  56368. });
  56369. LinesMesh.prototype.createInstance = function (name) {
  56370. throw new Error("LinesMeshes do not support createInstance.");
  56371. };
  56372. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  56373. if (!this._geometry) {
  56374. return this;
  56375. }
  56376. // VBOs
  56377. this._geometry._bind(this._colorShader.getEffect());
  56378. // Color
  56379. if (!this.useVertexColor) {
  56380. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  56381. }
  56382. return this;
  56383. };
  56384. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  56385. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  56386. return this;
  56387. }
  56388. var engine = this.getScene().getEngine();
  56389. // Draw order
  56390. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  56391. return this;
  56392. };
  56393. LinesMesh.prototype.dispose = function (doNotRecurse) {
  56394. this._colorShader.dispose();
  56395. _super.prototype.dispose.call(this, doNotRecurse);
  56396. };
  56397. /**
  56398. * Returns a new LineMesh object cloned from the current one.
  56399. */
  56400. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  56401. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  56402. };
  56403. return LinesMesh;
  56404. }(BABYLON.Mesh));
  56405. BABYLON.LinesMesh = LinesMesh;
  56406. })(BABYLON || (BABYLON = {}));
  56407. //# sourceMappingURL=babylon.linesMesh.js.map
  56408. "use strict";
  56409. var BABYLON;
  56410. (function (BABYLON) {
  56411. var MeshBuilder = /** @class */ (function () {
  56412. function MeshBuilder() {
  56413. }
  56414. MeshBuilder.updateSideOrientation = function (orientation) {
  56415. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  56416. return BABYLON.Mesh.DOUBLESIDE;
  56417. }
  56418. if (orientation === undefined || orientation === null) {
  56419. return BABYLON.Mesh.FRONTSIDE;
  56420. }
  56421. return orientation;
  56422. };
  56423. /**
  56424. * Creates a box mesh.
  56425. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  56426. * The parameter `size` sets the size (float) of each box side (default 1).
  56427. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  56428. * 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).
  56429. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  56430. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56431. * 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).
  56432. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56433. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56434. */
  56435. MeshBuilder.CreateBox = function (name, options, scene) {
  56436. if (scene === void 0) { scene = null; }
  56437. var box = new BABYLON.Mesh(name, scene);
  56438. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56439. box._originalBuilderSideOrientation = options.sideOrientation;
  56440. var vertexData = BABYLON.VertexData.CreateBox(options);
  56441. vertexData.applyToMesh(box, options.updatable);
  56442. return box;
  56443. };
  56444. /**
  56445. * Creates a sphere mesh.
  56446. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  56447. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  56448. * 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`).
  56449. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  56450. * 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
  56451. * 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).
  56452. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56453. * 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).
  56454. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56455. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56456. */
  56457. MeshBuilder.CreateSphere = function (name, options, scene) {
  56458. var sphere = new BABYLON.Mesh(name, scene);
  56459. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56460. sphere._originalBuilderSideOrientation = options.sideOrientation;
  56461. var vertexData = BABYLON.VertexData.CreateSphere(options);
  56462. vertexData.applyToMesh(sphere, options.updatable);
  56463. return sphere;
  56464. };
  56465. /**
  56466. * Creates a plane polygonal mesh. By default, this is a disc.
  56467. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  56468. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  56469. * 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.
  56470. * 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
  56471. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56472. * 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).
  56473. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56474. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56475. */
  56476. MeshBuilder.CreateDisc = function (name, options, scene) {
  56477. if (scene === void 0) { scene = null; }
  56478. var disc = new BABYLON.Mesh(name, scene);
  56479. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56480. disc._originalBuilderSideOrientation = options.sideOrientation;
  56481. var vertexData = BABYLON.VertexData.CreateDisc(options);
  56482. vertexData.applyToMesh(disc, options.updatable);
  56483. return disc;
  56484. };
  56485. /**
  56486. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  56487. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  56488. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  56489. * 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`).
  56490. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  56491. * 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.
  56492. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56493. * 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).
  56494. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56495. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56496. */
  56497. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  56498. var sphere = new BABYLON.Mesh(name, scene);
  56499. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56500. sphere._originalBuilderSideOrientation = options.sideOrientation;
  56501. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  56502. vertexData.applyToMesh(sphere, options.updatable);
  56503. return sphere;
  56504. };
  56505. ;
  56506. /**
  56507. * Creates a ribbon mesh.
  56508. * 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.
  56509. *
  56510. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  56511. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  56512. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  56513. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  56514. * 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.
  56515. * 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.
  56516. * 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
  56517. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56518. * 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).
  56519. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56520. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  56521. * 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.
  56522. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  56523. * 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
  56524. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  56525. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  56526. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56527. */
  56528. MeshBuilder.CreateRibbon = function (name, options, scene) {
  56529. if (scene === void 0) { scene = null; }
  56530. var pathArray = options.pathArray;
  56531. var closeArray = options.closeArray;
  56532. var closePath = options.closePath;
  56533. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56534. var instance = options.instance;
  56535. var updatable = options.updatable;
  56536. if (instance) {
  56537. // positionFunction : ribbon case
  56538. // only pathArray and sideOrientation parameters are taken into account for positions update
  56539. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  56540. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  56541. var positionFunction = function (positions) {
  56542. var minlg = pathArray[0].length;
  56543. var i = 0;
  56544. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  56545. for (var si = 1; si <= ns; si++) {
  56546. for (var p = 0; p < pathArray.length; p++) {
  56547. var path = pathArray[p];
  56548. var l = path.length;
  56549. minlg = (minlg < l) ? minlg : l;
  56550. var j = 0;
  56551. while (j < minlg) {
  56552. positions[i] = path[j].x;
  56553. positions[i + 1] = path[j].y;
  56554. positions[i + 2] = path[j].z;
  56555. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  56556. BABYLON.Tmp.Vector3[0].x = path[j].x;
  56557. }
  56558. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  56559. BABYLON.Tmp.Vector3[1].x = path[j].x;
  56560. }
  56561. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  56562. BABYLON.Tmp.Vector3[0].y = path[j].y;
  56563. }
  56564. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  56565. BABYLON.Tmp.Vector3[1].y = path[j].y;
  56566. }
  56567. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  56568. BABYLON.Tmp.Vector3[0].z = path[j].z;
  56569. }
  56570. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  56571. BABYLON.Tmp.Vector3[1].z = path[j].z;
  56572. }
  56573. j++;
  56574. i += 3;
  56575. }
  56576. if (instance._closePath) {
  56577. positions[i] = path[0].x;
  56578. positions[i + 1] = path[0].y;
  56579. positions[i + 2] = path[0].z;
  56580. i += 3;
  56581. }
  56582. }
  56583. }
  56584. };
  56585. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  56586. positionFunction(positions);
  56587. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  56588. instance._boundingInfo.update(instance._worldMatrix);
  56589. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  56590. if (options.colors) {
  56591. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  56592. for (var c = 0; c < options.colors.length; c++) {
  56593. colors[c * 4] = options.colors[c].r;
  56594. colors[c * 4 + 1] = options.colors[c].g;
  56595. colors[c * 4 + 2] = options.colors[c].b;
  56596. colors[c * 4 + 3] = options.colors[c].a;
  56597. }
  56598. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  56599. }
  56600. if (options.uvs) {
  56601. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  56602. for (var i = 0; i < options.uvs.length; i++) {
  56603. uvs[i * 2] = options.uvs[i].x;
  56604. uvs[i * 2 + 1] = options.uvs[i].y;
  56605. }
  56606. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  56607. }
  56608. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  56609. var indices = instance.getIndices();
  56610. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  56611. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  56612. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  56613. if (instance._closePath) {
  56614. var indexFirst = 0;
  56615. var indexLast = 0;
  56616. for (var p = 0; p < pathArray.length; p++) {
  56617. indexFirst = instance._idx[p] * 3;
  56618. if (p + 1 < pathArray.length) {
  56619. indexLast = (instance._idx[p + 1] - 1) * 3;
  56620. }
  56621. else {
  56622. indexLast = normals.length - 3;
  56623. }
  56624. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  56625. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  56626. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  56627. normals[indexLast] = normals[indexFirst];
  56628. normals[indexLast + 1] = normals[indexFirst + 1];
  56629. normals[indexLast + 2] = normals[indexFirst + 2];
  56630. }
  56631. }
  56632. if (!(instance.areNormalsFrozen)) {
  56633. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  56634. }
  56635. }
  56636. return instance;
  56637. }
  56638. else {
  56639. var ribbon = new BABYLON.Mesh(name, scene);
  56640. ribbon._originalBuilderSideOrientation = sideOrientation;
  56641. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  56642. if (closePath) {
  56643. ribbon._idx = vertexData._idx;
  56644. }
  56645. ribbon._closePath = closePath;
  56646. ribbon._closeArray = closeArray;
  56647. vertexData.applyToMesh(ribbon, updatable);
  56648. return ribbon;
  56649. }
  56650. };
  56651. /**
  56652. * Creates a cylinder or a cone mesh.
  56653. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  56654. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  56655. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  56656. * 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.
  56657. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  56658. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  56659. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  56660. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  56661. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  56662. * 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).
  56663. * 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
  56664. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  56665. * 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
  56666. * 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.
  56667. * If `enclose` is false, a ring surface is one element.
  56668. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  56669. * 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
  56670. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56671. * 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).
  56672. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56673. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56674. */
  56675. MeshBuilder.CreateCylinder = function (name, options, scene) {
  56676. var cylinder = new BABYLON.Mesh(name, scene);
  56677. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56678. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  56679. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  56680. vertexData.applyToMesh(cylinder, options.updatable);
  56681. return cylinder;
  56682. };
  56683. /**
  56684. * Creates a torus mesh.
  56685. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  56686. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  56687. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  56688. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  56689. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56690. * 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).
  56691. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56692. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56693. */
  56694. MeshBuilder.CreateTorus = function (name, options, scene) {
  56695. var torus = new BABYLON.Mesh(name, scene);
  56696. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56697. torus._originalBuilderSideOrientation = options.sideOrientation;
  56698. var vertexData = BABYLON.VertexData.CreateTorus(options);
  56699. vertexData.applyToMesh(torus, options.updatable);
  56700. return torus;
  56701. };
  56702. /**
  56703. * Creates a torus knot mesh.
  56704. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  56705. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  56706. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  56707. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  56708. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  56709. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56710. * 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).
  56711. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56712. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56713. */
  56714. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  56715. var torusKnot = new BABYLON.Mesh(name, scene);
  56716. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56717. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  56718. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  56719. vertexData.applyToMesh(torusKnot, options.updatable);
  56720. return torusKnot;
  56721. };
  56722. /**
  56723. * Creates a line system mesh.
  56724. * A line system is a pool of many lines gathered in a single mesh.
  56725. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  56726. * 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.
  56727. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  56728. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  56729. * 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
  56730. * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point.
  56731. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need the alpha blending (faster).
  56732. * 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
  56733. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  56734. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56735. */
  56736. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  56737. var instance = options.instance;
  56738. var lines = options.lines;
  56739. var colors = options.colors;
  56740. if (instance) {
  56741. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  56742. var vertexColor;
  56743. var lineColors;
  56744. if (colors) {
  56745. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  56746. }
  56747. var i = 0;
  56748. var c = 0;
  56749. for (var l = 0; l < lines.length; l++) {
  56750. var points = lines[l];
  56751. for (var p = 0; p < points.length; p++) {
  56752. positions[i] = points[p].x;
  56753. positions[i + 1] = points[p].y;
  56754. positions[i + 2] = points[p].z;
  56755. if (colors && vertexColor) {
  56756. lineColors = colors[l];
  56757. vertexColor[c] = lineColors[p].r;
  56758. vertexColor[c + 1] = lineColors[p].g;
  56759. vertexColor[c + 2] = lineColors[p].b;
  56760. vertexColor[c + 3] = lineColors[p].a;
  56761. c += 4;
  56762. }
  56763. i += 3;
  56764. }
  56765. }
  56766. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  56767. if (colors && vertexColor) {
  56768. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  56769. }
  56770. return instance;
  56771. }
  56772. // line system creation
  56773. var useVertexColor = (colors) ? true : false;
  56774. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  56775. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  56776. vertexData.applyToMesh(lineSystem, options.updatable);
  56777. return lineSystem;
  56778. };
  56779. /**
  56780. * Creates a line mesh.
  56781. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  56782. * 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.
  56783. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  56784. * The parameter `points` is an array successive Vector3.
  56785. * 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
  56786. * The optional parameter `colors` is an array of successive Color4, one per line point.
  56787. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need alpha blending (faster).
  56788. * When updating an instance, remember that only point positions can change, not the number of points.
  56789. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56790. */
  56791. MeshBuilder.CreateLines = function (name, options, scene) {
  56792. if (scene === void 0) { scene = null; }
  56793. var colors = (options.colors) ? [options.colors] : null;
  56794. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  56795. return lines;
  56796. };
  56797. /**
  56798. * Creates a dashed line mesh.
  56799. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  56800. * 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.
  56801. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  56802. * The parameter `points` is an array successive Vector3.
  56803. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  56804. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  56805. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  56806. * 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
  56807. * When updating an instance, remember that only point positions can change, not the number of points.
  56808. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56809. */
  56810. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  56811. if (scene === void 0) { scene = null; }
  56812. var points = options.points;
  56813. var instance = options.instance;
  56814. var gapSize = options.gapSize || 1;
  56815. var dashSize = options.dashSize || 3;
  56816. if (instance) {
  56817. var positionFunction = function (positions) {
  56818. var curvect = BABYLON.Vector3.Zero();
  56819. var nbSeg = positions.length / 6;
  56820. var lg = 0;
  56821. var nb = 0;
  56822. var shft = 0;
  56823. var dashshft = 0;
  56824. var curshft = 0;
  56825. var p = 0;
  56826. var i = 0;
  56827. var j = 0;
  56828. for (i = 0; i < points.length - 1; i++) {
  56829. points[i + 1].subtractToRef(points[i], curvect);
  56830. lg += curvect.length();
  56831. }
  56832. shft = lg / nbSeg;
  56833. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  56834. for (i = 0; i < points.length - 1; i++) {
  56835. points[i + 1].subtractToRef(points[i], curvect);
  56836. nb = Math.floor(curvect.length() / shft);
  56837. curvect.normalize();
  56838. j = 0;
  56839. while (j < nb && p < positions.length) {
  56840. curshft = shft * j;
  56841. positions[p] = points[i].x + curshft * curvect.x;
  56842. positions[p + 1] = points[i].y + curshft * curvect.y;
  56843. positions[p + 2] = points[i].z + curshft * curvect.z;
  56844. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  56845. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  56846. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  56847. p += 6;
  56848. j++;
  56849. }
  56850. }
  56851. while (p < positions.length) {
  56852. positions[p] = points[i].x;
  56853. positions[p + 1] = points[i].y;
  56854. positions[p + 2] = points[i].z;
  56855. p += 3;
  56856. }
  56857. };
  56858. instance.updateMeshPositions(positionFunction, false);
  56859. return instance;
  56860. }
  56861. // dashed lines creation
  56862. var dashedLines = new BABYLON.LinesMesh(name, scene);
  56863. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  56864. vertexData.applyToMesh(dashedLines, options.updatable);
  56865. dashedLines.dashSize = dashSize;
  56866. dashedLines.gapSize = gapSize;
  56867. return dashedLines;
  56868. };
  56869. /**
  56870. * Creates an extruded shape mesh.
  56871. * 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.
  56872. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  56873. *
  56874. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  56875. * 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
  56876. * extruded along the Z axis.
  56877. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  56878. * 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.
  56879. * The parameter `scale` (float, default 1) is the value to scale the shape.
  56880. * 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
  56881. * 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
  56882. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  56883. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56884. * 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).
  56885. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56886. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  56887. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56888. */
  56889. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  56890. if (scene === void 0) { scene = null; }
  56891. var path = options.path;
  56892. var shape = options.shape;
  56893. var scale = options.scale || 1;
  56894. var rotation = options.rotation || 0;
  56895. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  56896. var updatable = options.updatable;
  56897. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56898. var instance = options.instance || null;
  56899. var invertUV = options.invertUV || false;
  56900. 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);
  56901. };
  56902. /**
  56903. * Creates an custom extruded shape mesh.
  56904. * 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.
  56905. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  56906. *
  56907. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  56908. * 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
  56909. * extruded along the Z axis.
  56910. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  56911. * 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
  56912. * and the distance of this point from the begining of the path :
  56913. * ```javascript
  56914. * var rotationFunction = function(i, distance) {
  56915. * // do things
  56916. * return rotationValue; }
  56917. * ```
  56918. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  56919. * 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
  56920. * and the distance of this point from the begining of the path :
  56921. * ```javascript
  56922. * var scaleFunction = function(i, distance) {
  56923. * // do things
  56924. * return scaleValue;}
  56925. * ```
  56926. * It must returns a float value that will be the scale value applied to the shape on each path point.
  56927. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  56928. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  56929. * 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
  56930. * 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
  56931. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  56932. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56933. * 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).
  56934. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56935. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  56936. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56937. */
  56938. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  56939. var path = options.path;
  56940. var shape = options.shape;
  56941. var scaleFunction = options.scaleFunction || (function () { return 1; });
  56942. var rotationFunction = options.rotationFunction || (function () { return 0; });
  56943. var ribbonCloseArray = options.ribbonCloseArray || false;
  56944. var ribbonClosePath = options.ribbonClosePath || false;
  56945. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  56946. var updatable = options.updatable;
  56947. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56948. var instance = options.instance;
  56949. var invertUV = options.invertUV || false;
  56950. 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);
  56951. };
  56952. /**
  56953. * Creates lathe mesh.
  56954. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  56955. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  56956. *
  56957. * 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
  56958. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  56959. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  56960. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  56961. * 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.
  56962. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  56963. * 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
  56964. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56965. * 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).
  56966. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56967. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  56968. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56969. */
  56970. MeshBuilder.CreateLathe = function (name, options, scene) {
  56971. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  56972. var closed = (options.closed === undefined) ? true : options.closed;
  56973. var shape = options.shape;
  56974. var radius = options.radius || 1;
  56975. var tessellation = options.tessellation || 64;
  56976. var updatable = options.updatable;
  56977. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56978. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  56979. var pi2 = Math.PI * 2;
  56980. var paths = new Array();
  56981. var invertUV = options.invertUV || false;
  56982. var i = 0;
  56983. var p = 0;
  56984. var step = pi2 / tessellation * arc;
  56985. var rotated;
  56986. var path = new Array();
  56987. ;
  56988. for (i = 0; i <= tessellation; i++) {
  56989. var path = [];
  56990. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  56991. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  56992. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  56993. }
  56994. for (p = 0; p < shape.length; p++) {
  56995. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  56996. path.push(rotated);
  56997. }
  56998. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  56999. 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));
  57000. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  57001. }
  57002. paths.push(path);
  57003. }
  57004. // lathe ribbon
  57005. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  57006. return lathe;
  57007. };
  57008. /**
  57009. * Creates a plane mesh.
  57010. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  57011. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  57012. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  57013. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  57014. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  57015. * 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).
  57016. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  57017. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57018. */
  57019. MeshBuilder.CreatePlane = function (name, options, scene) {
  57020. var plane = new BABYLON.Mesh(name, scene);
  57021. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  57022. plane._originalBuilderSideOrientation = options.sideOrientation;
  57023. var vertexData = BABYLON.VertexData.CreatePlane(options);
  57024. vertexData.applyToMesh(plane, options.updatable);
  57025. if (options.sourcePlane) {
  57026. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  57027. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  57028. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  57029. plane.rotate(vectorProduct, product);
  57030. }
  57031. return plane;
  57032. };
  57033. /**
  57034. * Creates a ground mesh.
  57035. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  57036. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  57037. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  57038. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57039. */
  57040. MeshBuilder.CreateGround = function (name, options, scene) {
  57041. var ground = new BABYLON.GroundMesh(name, scene);
  57042. ground._setReady(false);
  57043. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  57044. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  57045. ground._width = options.width || 1;
  57046. ground._height = options.height || 1;
  57047. ground._maxX = ground._width / 2;
  57048. ground._maxZ = ground._height / 2;
  57049. ground._minX = -ground._maxX;
  57050. ground._minZ = -ground._maxZ;
  57051. var vertexData = BABYLON.VertexData.CreateGround(options);
  57052. vertexData.applyToMesh(ground, options.updatable);
  57053. ground._setReady(true);
  57054. return ground;
  57055. };
  57056. /**
  57057. * Creates a tiled ground mesh.
  57058. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  57059. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  57060. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  57061. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  57062. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  57063. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  57064. * numbers of subdivisions on the ground width and height of each tile.
  57065. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57066. */
  57067. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  57068. var tiledGround = new BABYLON.Mesh(name, scene);
  57069. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  57070. vertexData.applyToMesh(tiledGround, options.updatable);
  57071. return tiledGround;
  57072. };
  57073. /**
  57074. * Creates a ground mesh from a height map.
  57075. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  57076. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  57077. * The parameter `url` sets the URL of the height map image resource.
  57078. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  57079. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  57080. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  57081. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  57082. * 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.
  57083. * 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).
  57084. * This function is passed the newly built mesh :
  57085. * ```javascript
  57086. * function(mesh) { // do things
  57087. * return; }
  57088. * ```
  57089. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57090. */
  57091. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  57092. var width = options.width || 10.0;
  57093. var height = options.height || 10.0;
  57094. var subdivisions = options.subdivisions || 1 | 0;
  57095. var minHeight = options.minHeight || 0.0;
  57096. var maxHeight = options.maxHeight || 1.0;
  57097. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  57098. var updatable = options.updatable;
  57099. var onReady = options.onReady;
  57100. var ground = new BABYLON.GroundMesh(name, scene);
  57101. ground._subdivisionsX = subdivisions;
  57102. ground._subdivisionsY = subdivisions;
  57103. ground._width = width;
  57104. ground._height = height;
  57105. ground._maxX = ground._width / 2.0;
  57106. ground._maxZ = ground._height / 2.0;
  57107. ground._minX = -ground._maxX;
  57108. ground._minZ = -ground._maxZ;
  57109. ground._setReady(false);
  57110. var onload = function (img) {
  57111. // Getting height map data
  57112. var canvas = document.createElement("canvas");
  57113. var context = canvas.getContext("2d");
  57114. if (!context) {
  57115. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  57116. }
  57117. if (scene.isDisposed) {
  57118. return;
  57119. }
  57120. var bufferWidth = img.width;
  57121. var bufferHeight = img.height;
  57122. canvas.width = bufferWidth;
  57123. canvas.height = bufferHeight;
  57124. context.drawImage(img, 0, 0);
  57125. // Create VertexData from map data
  57126. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  57127. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  57128. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  57129. width: width, height: height,
  57130. subdivisions: subdivisions,
  57131. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  57132. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  57133. });
  57134. vertexData.applyToMesh(ground, updatable);
  57135. //execute ready callback, if set
  57136. if (onReady) {
  57137. onReady(ground);
  57138. }
  57139. ground._setReady(true);
  57140. };
  57141. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  57142. return ground;
  57143. };
  57144. /**
  57145. * Creates a polygon mesh.
  57146. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  57147. * 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.
  57148. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  57149. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57150. * 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).
  57151. * Remember you can only change the shape positions, not their number when updating a polygon.
  57152. */
  57153. MeshBuilder.CreatePolygon = function (name, options, scene) {
  57154. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  57155. var shape = options.shape;
  57156. var holes = options.holes || [];
  57157. var depth = options.depth || 0;
  57158. var contours = [];
  57159. var hole = [];
  57160. for (var i = 0; i < shape.length; i++) {
  57161. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  57162. }
  57163. var epsilon = 0.00000001;
  57164. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  57165. contours.pop();
  57166. }
  57167. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  57168. for (var hNb = 0; hNb < holes.length; hNb++) {
  57169. hole = [];
  57170. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  57171. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  57172. }
  57173. polygonTriangulation.addHole(hole);
  57174. }
  57175. var polygon = polygonTriangulation.build(options.updatable, depth);
  57176. polygon._originalBuilderSideOrientation = options.sideOrientation;
  57177. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  57178. vertexData.applyToMesh(polygon, options.updatable);
  57179. return polygon;
  57180. };
  57181. ;
  57182. /**
  57183. * Creates an extruded polygon mesh, with depth in the Y direction.
  57184. * 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).
  57185. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  57186. */
  57187. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  57188. return MeshBuilder.CreatePolygon(name, options, scene);
  57189. };
  57190. ;
  57191. /**
  57192. * Creates a tube mesh.
  57193. * 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.
  57194. *
  57195. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  57196. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  57197. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  57198. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  57199. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  57200. * 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.
  57201. * It must return a radius value (positive float) :
  57202. * ```javascript
  57203. * var radiusFunction = function(i, distance) {
  57204. * // do things
  57205. * return radius; }
  57206. * ```
  57207. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  57208. * 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
  57209. * 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
  57210. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  57211. * 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).
  57212. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  57213. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  57214. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57215. */
  57216. MeshBuilder.CreateTube = function (name, options, scene) {
  57217. var path = options.path;
  57218. var instance = options.instance;
  57219. var radius = 1.0;
  57220. if (instance) {
  57221. radius = instance.radius;
  57222. }
  57223. if (options.radius !== undefined) {
  57224. radius = options.radius;
  57225. }
  57226. ;
  57227. var tessellation = options.tessellation || 64 | 0;
  57228. var radiusFunction = options.radiusFunction || null;
  57229. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  57230. var invertUV = options.invertUV || false;
  57231. var updatable = options.updatable;
  57232. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  57233. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  57234. // tube geometry
  57235. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  57236. var tangents = path3D.getTangents();
  57237. var normals = path3D.getNormals();
  57238. var distances = path3D.getDistances();
  57239. var pi2 = Math.PI * 2;
  57240. var step = pi2 / tessellation * arc;
  57241. var returnRadius = function () { return radius; };
  57242. var radiusFunctionFinal = radiusFunction || returnRadius;
  57243. var circlePath;
  57244. var rad;
  57245. var normal;
  57246. var rotated;
  57247. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  57248. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  57249. for (var i = 0; i < path.length; i++) {
  57250. rad = radiusFunctionFinal(i, distances[i]); // current radius
  57251. circlePath = Array(); // current circle array
  57252. normal = normals[i]; // current normal
  57253. for (var t = 0; t < tessellation; t++) {
  57254. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  57255. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  57256. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  57257. rotated.scaleInPlace(rad).addInPlace(path[i]);
  57258. circlePath[t] = rotated;
  57259. }
  57260. circlePaths[index] = circlePath;
  57261. index++;
  57262. }
  57263. // cap
  57264. var capPath = function (nbPoints, pathIndex) {
  57265. var pointCap = Array();
  57266. for (var i = 0; i < nbPoints; i++) {
  57267. pointCap.push(path[pathIndex]);
  57268. }
  57269. return pointCap;
  57270. };
  57271. switch (cap) {
  57272. case BABYLON.Mesh.NO_CAP:
  57273. break;
  57274. case BABYLON.Mesh.CAP_START:
  57275. circlePaths[0] = capPath(tessellation, 0);
  57276. circlePaths[1] = circlePaths[2].slice(0);
  57277. break;
  57278. case BABYLON.Mesh.CAP_END:
  57279. circlePaths[index] = circlePaths[index - 1].slice(0);
  57280. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  57281. break;
  57282. case BABYLON.Mesh.CAP_ALL:
  57283. circlePaths[0] = capPath(tessellation, 0);
  57284. circlePaths[1] = circlePaths[2].slice(0);
  57285. circlePaths[index] = circlePaths[index - 1].slice(0);
  57286. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  57287. break;
  57288. default:
  57289. break;
  57290. }
  57291. return circlePaths;
  57292. };
  57293. var path3D;
  57294. var pathArray;
  57295. if (instance) {
  57296. var arc = options.arc || instance.arc;
  57297. path3D = (instance.path3D).update(path);
  57298. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  57299. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  57300. instance.path3D = path3D;
  57301. instance.pathArray = pathArray;
  57302. instance.arc = arc;
  57303. instance.radius = radius;
  57304. return instance;
  57305. }
  57306. // tube creation
  57307. path3D = new BABYLON.Path3D(path);
  57308. var newPathArray = new Array();
  57309. cap = (cap < 0 || cap > 3) ? 0 : cap;
  57310. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  57311. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  57312. tube.pathArray = pathArray;
  57313. tube.path3D = path3D;
  57314. tube.tessellation = tessellation;
  57315. tube.cap = cap;
  57316. tube.arc = options.arc;
  57317. tube.radius = radius;
  57318. return tube;
  57319. };
  57320. /**
  57321. * Creates a polyhedron mesh.
  57322. *
  57323. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  57324. * 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
  57325. * to choose the wanted type.
  57326. * The parameter `size` (positive float, default 1) sets the polygon size.
  57327. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  57328. * 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`.
  57329. * 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
  57330. * 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)`).
  57331. * 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
  57332. * 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.
  57333. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  57334. * 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).
  57335. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  57336. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57337. */
  57338. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  57339. var polyhedron = new BABYLON.Mesh(name, scene);
  57340. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  57341. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  57342. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  57343. vertexData.applyToMesh(polyhedron, options.updatable);
  57344. return polyhedron;
  57345. };
  57346. /**
  57347. * Creates a decal mesh.
  57348. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  57349. * 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.
  57350. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  57351. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  57352. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  57353. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  57354. */
  57355. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  57356. var indices = sourceMesh.getIndices();
  57357. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  57358. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  57359. var position = options.position || BABYLON.Vector3.Zero();
  57360. var normal = options.normal || BABYLON.Vector3.Up();
  57361. var size = options.size || BABYLON.Vector3.One();
  57362. var angle = options.angle || 0;
  57363. // Getting correct rotation
  57364. if (!normal) {
  57365. var target = new BABYLON.Vector3(0, 0, 1);
  57366. var camera = sourceMesh.getScene().activeCamera;
  57367. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  57368. normal = camera.globalPosition.subtract(cameraWorldTarget);
  57369. }
  57370. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  57371. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  57372. var pitch = Math.atan2(normal.y, len);
  57373. // Matrix
  57374. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  57375. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  57376. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  57377. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  57378. var vertexData = new BABYLON.VertexData();
  57379. vertexData.indices = [];
  57380. vertexData.positions = [];
  57381. vertexData.normals = [];
  57382. vertexData.uvs = [];
  57383. var currentVertexDataIndex = 0;
  57384. var extractDecalVector3 = function (indexId) {
  57385. var result = new BABYLON.PositionNormalVertex();
  57386. if (!indices || !positions || !normals) {
  57387. return result;
  57388. }
  57389. var vertexId = indices[indexId];
  57390. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  57391. // Send vector to decal local world
  57392. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  57393. // Get normal
  57394. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  57395. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  57396. return result;
  57397. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  57398. var clip = function (vertices, axis) {
  57399. if (vertices.length === 0) {
  57400. return vertices;
  57401. }
  57402. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  57403. var clipVertices = function (v0, v1) {
  57404. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  57405. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  57406. };
  57407. var result = new Array();
  57408. for (var index = 0; index < vertices.length; index += 3) {
  57409. var v1Out;
  57410. var v2Out;
  57411. var v3Out;
  57412. var total = 0;
  57413. var nV1 = null;
  57414. var nV2 = null;
  57415. var nV3 = null;
  57416. var nV4 = null;
  57417. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  57418. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  57419. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  57420. v1Out = d1 > 0;
  57421. v2Out = d2 > 0;
  57422. v3Out = d3 > 0;
  57423. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  57424. switch (total) {
  57425. case 0:
  57426. result.push(vertices[index]);
  57427. result.push(vertices[index + 1]);
  57428. result.push(vertices[index + 2]);
  57429. break;
  57430. case 1:
  57431. if (v1Out) {
  57432. nV1 = vertices[index + 1];
  57433. nV2 = vertices[index + 2];
  57434. nV3 = clipVertices(vertices[index], nV1);
  57435. nV4 = clipVertices(vertices[index], nV2);
  57436. }
  57437. if (v2Out) {
  57438. nV1 = vertices[index];
  57439. nV2 = vertices[index + 2];
  57440. nV3 = clipVertices(vertices[index + 1], nV1);
  57441. nV4 = clipVertices(vertices[index + 1], nV2);
  57442. result.push(nV3);
  57443. result.push(nV2.clone());
  57444. result.push(nV1.clone());
  57445. result.push(nV2.clone());
  57446. result.push(nV3.clone());
  57447. result.push(nV4);
  57448. break;
  57449. }
  57450. if (v3Out) {
  57451. nV1 = vertices[index];
  57452. nV2 = vertices[index + 1];
  57453. nV3 = clipVertices(vertices[index + 2], nV1);
  57454. nV4 = clipVertices(vertices[index + 2], nV2);
  57455. }
  57456. if (nV1 && nV2 && nV3 && nV4) {
  57457. result.push(nV1.clone());
  57458. result.push(nV2.clone());
  57459. result.push(nV3);
  57460. result.push(nV4);
  57461. result.push(nV3.clone());
  57462. result.push(nV2.clone());
  57463. }
  57464. break;
  57465. case 2:
  57466. if (!v1Out) {
  57467. nV1 = vertices[index].clone();
  57468. nV2 = clipVertices(nV1, vertices[index + 1]);
  57469. nV3 = clipVertices(nV1, vertices[index + 2]);
  57470. result.push(nV1);
  57471. result.push(nV2);
  57472. result.push(nV3);
  57473. }
  57474. if (!v2Out) {
  57475. nV1 = vertices[index + 1].clone();
  57476. nV2 = clipVertices(nV1, vertices[index + 2]);
  57477. nV3 = clipVertices(nV1, vertices[index]);
  57478. result.push(nV1);
  57479. result.push(nV2);
  57480. result.push(nV3);
  57481. }
  57482. if (!v3Out) {
  57483. nV1 = vertices[index + 2].clone();
  57484. nV2 = clipVertices(nV1, vertices[index]);
  57485. nV3 = clipVertices(nV1, vertices[index + 1]);
  57486. result.push(nV1);
  57487. result.push(nV2);
  57488. result.push(nV3);
  57489. }
  57490. break;
  57491. case 3:
  57492. break;
  57493. }
  57494. }
  57495. return result;
  57496. };
  57497. for (var index = 0; index < indices.length; index += 3) {
  57498. var faceVertices = new Array();
  57499. faceVertices.push(extractDecalVector3(index));
  57500. faceVertices.push(extractDecalVector3(index + 1));
  57501. faceVertices.push(extractDecalVector3(index + 2));
  57502. // Clip
  57503. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  57504. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  57505. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  57506. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  57507. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  57508. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  57509. if (faceVertices.length === 0) {
  57510. continue;
  57511. }
  57512. // Add UVs and get back to world
  57513. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  57514. var vertex = faceVertices[vIndex];
  57515. //TODO check for Int32Array | Uint32Array | Uint16Array
  57516. vertexData.indices.push(currentVertexDataIndex);
  57517. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  57518. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  57519. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  57520. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  57521. currentVertexDataIndex++;
  57522. }
  57523. }
  57524. // Return mesh
  57525. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  57526. vertexData.applyToMesh(decal);
  57527. decal.position = position.clone();
  57528. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  57529. return decal;
  57530. };
  57531. // Privates
  57532. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  57533. // extrusion geometry
  57534. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  57535. var tangents = path3D.getTangents();
  57536. var normals = path3D.getNormals();
  57537. var binormals = path3D.getBinormals();
  57538. var distances = path3D.getDistances();
  57539. var angle = 0;
  57540. var returnScale = function () { return scale !== null ? scale : 1; };
  57541. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  57542. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  57543. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  57544. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  57545. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  57546. for (var i = 0; i < curve.length; i++) {
  57547. var shapePath = new Array();
  57548. var angleStep = rotate(i, distances[i]);
  57549. var scaleRatio = scl(i, distances[i]);
  57550. for (var p = 0; p < shape.length; p++) {
  57551. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  57552. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  57553. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  57554. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  57555. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  57556. shapePath[p] = rotated;
  57557. }
  57558. shapePaths[index] = shapePath;
  57559. angle += angleStep;
  57560. index++;
  57561. }
  57562. // cap
  57563. var capPath = function (shapePath) {
  57564. var pointCap = Array();
  57565. var barycenter = BABYLON.Vector3.Zero();
  57566. var i;
  57567. for (i = 0; i < shapePath.length; i++) {
  57568. barycenter.addInPlace(shapePath[i]);
  57569. }
  57570. barycenter.scaleInPlace(1.0 / shapePath.length);
  57571. for (i = 0; i < shapePath.length; i++) {
  57572. pointCap.push(barycenter);
  57573. }
  57574. return pointCap;
  57575. };
  57576. switch (cap) {
  57577. case BABYLON.Mesh.NO_CAP:
  57578. break;
  57579. case BABYLON.Mesh.CAP_START:
  57580. shapePaths[0] = capPath(shapePaths[2]);
  57581. shapePaths[1] = shapePaths[2];
  57582. break;
  57583. case BABYLON.Mesh.CAP_END:
  57584. shapePaths[index] = shapePaths[index - 1];
  57585. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  57586. break;
  57587. case BABYLON.Mesh.CAP_ALL:
  57588. shapePaths[0] = capPath(shapePaths[2]);
  57589. shapePaths[1] = shapePaths[2];
  57590. shapePaths[index] = shapePaths[index - 1];
  57591. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  57592. break;
  57593. default:
  57594. break;
  57595. }
  57596. return shapePaths;
  57597. };
  57598. var path3D;
  57599. var pathArray;
  57600. if (instance) {
  57601. path3D = (instance.path3D).update(curve);
  57602. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  57603. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  57604. return instance;
  57605. }
  57606. // extruded shape creation
  57607. path3D = new BABYLON.Path3D(curve);
  57608. var newShapePaths = new Array();
  57609. cap = (cap < 0 || cap > 3) ? 0 : cap;
  57610. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  57611. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  57612. extrudedGeneric.pathArray = pathArray;
  57613. extrudedGeneric.path3D = path3D;
  57614. extrudedGeneric.cap = cap;
  57615. return extrudedGeneric;
  57616. };
  57617. return MeshBuilder;
  57618. }());
  57619. BABYLON.MeshBuilder = MeshBuilder;
  57620. })(BABYLON || (BABYLON = {}));
  57621. //# sourceMappingURL=babylon.meshBuilder.js.map
  57622. "use strict";
  57623. var BABYLON;
  57624. (function (BABYLON) {
  57625. /**
  57626. * Draco compression (https://google.github.io/draco/)
  57627. */
  57628. var DracoCompression = /** @class */ (function () {
  57629. /**
  57630. * Constructor
  57631. * @param numWorkers The number of workers for async operations
  57632. */
  57633. function DracoCompression(numWorkers) {
  57634. if (numWorkers === void 0) { numWorkers = (navigator.hardwareConcurrency || 4); }
  57635. var workerBlobUrl = URL && URL.createObjectURL && URL.createObjectURL(new Blob(["(" + DracoCompression._Worker.toString() + ")()"], { type: "application/javascript" }));
  57636. if (!workerBlobUrl || !Worker) {
  57637. BABYLON.Tools.Error("Draco Compression disabled. The current context doesn't support worker creation or URL.createObjectURL");
  57638. return;
  57639. }
  57640. var workers = new Array(numWorkers);
  57641. for (var i = 0; i < workers.length; i++) {
  57642. var worker = new Worker(workerBlobUrl);
  57643. worker.postMessage({ id: "initDecoder", url: DracoCompression.DecoderUrl });
  57644. workers[i] = worker;
  57645. }
  57646. this._workerPool = new BABYLON.WorkerPool(workers);
  57647. }
  57648. /**
  57649. * Stop all async operations and release resources.
  57650. */
  57651. DracoCompression.prototype.dispose = function () {
  57652. this._workerPool.dispose();
  57653. delete this._workerPool;
  57654. };
  57655. /**
  57656. * Decode Draco compressed mesh data to vertex data.
  57657. * @param data The array buffer view for the Draco compression data
  57658. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  57659. * @returns A promise that resolves with the decoded vertex data
  57660. */
  57661. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  57662. var _this = this;
  57663. return new Promise(function (resolve, reject) {
  57664. _this._workerPool.push(function (worker, onComplete) {
  57665. var vertexData = new BABYLON.VertexData();
  57666. var onError = function (error) {
  57667. worker.removeEventListener("error", onError);
  57668. worker.removeEventListener("message", onMessage);
  57669. reject(error);
  57670. onComplete();
  57671. };
  57672. var onMessage = function (message) {
  57673. if (message.data === "done") {
  57674. worker.removeEventListener("error", onError);
  57675. worker.removeEventListener("message", onMessage);
  57676. resolve(vertexData);
  57677. onComplete();
  57678. }
  57679. else if (message.data.id === "indices") {
  57680. vertexData.indices = message.data.value;
  57681. }
  57682. else {
  57683. vertexData.set(message.data.value, message.data.id);
  57684. }
  57685. };
  57686. worker.addEventListener("error", onError);
  57687. worker.addEventListener("message", onMessage);
  57688. var dataCopy = new Uint8Array(data.byteLength);
  57689. dataCopy.set(new Uint8Array(data.buffer, data.byteOffset, data.byteLength));
  57690. worker.postMessage({ id: "decodeMesh", data: dataCopy, attributes: attributes }, [dataCopy.buffer]);
  57691. });
  57692. });
  57693. };
  57694. /**
  57695. * The worker function that gets converted to a blob url to pass into a worker.
  57696. */
  57697. DracoCompression._Worker = function () {
  57698. // self is actually a DedicatedWorkerGlobalScope
  57699. var _self = self;
  57700. var decodeMesh = function (data, attributes) {
  57701. var dracoModule = new DracoDecoderModule();
  57702. var buffer = new dracoModule.DecoderBuffer();
  57703. buffer.Init(data, data.byteLength);
  57704. var decoder = new dracoModule.Decoder();
  57705. var geometry;
  57706. var status;
  57707. try {
  57708. var type = decoder.GetEncodedGeometryType(buffer);
  57709. switch (type) {
  57710. case dracoModule.TRIANGULAR_MESH:
  57711. geometry = new dracoModule.Mesh();
  57712. status = decoder.DecodeBufferToMesh(buffer, geometry);
  57713. break;
  57714. case dracoModule.POINT_CLOUD:
  57715. geometry = new dracoModule.PointCloud();
  57716. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  57717. break;
  57718. default:
  57719. throw new Error("Invalid geometry type " + type);
  57720. }
  57721. if (!status.ok() || !geometry.ptr) {
  57722. throw new Error(status.error_msg());
  57723. }
  57724. var numPoints = geometry.num_points();
  57725. if (type === dracoModule.TRIANGULAR_MESH) {
  57726. var numFaces = geometry.num_faces();
  57727. var faceIndices = new dracoModule.DracoInt32Array();
  57728. try {
  57729. var indices = new Uint32Array(numFaces * 3);
  57730. for (var i = 0; i < numFaces; i++) {
  57731. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  57732. var offset = i * 3;
  57733. indices[offset + 0] = faceIndices.GetValue(0);
  57734. indices[offset + 1] = faceIndices.GetValue(1);
  57735. indices[offset + 2] = faceIndices.GetValue(2);
  57736. }
  57737. _self.postMessage({ id: "indices", value: indices }, [indices.buffer]);
  57738. }
  57739. finally {
  57740. dracoModule.destroy(faceIndices);
  57741. }
  57742. }
  57743. for (var kind in attributes) {
  57744. var uniqueId = attributes[kind];
  57745. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  57746. var dracoData = new dracoModule.DracoFloat32Array();
  57747. try {
  57748. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  57749. var babylonData = new Float32Array(numPoints * attribute.num_components());
  57750. for (var i = 0; i < babylonData.length; i++) {
  57751. babylonData[i] = dracoData.GetValue(i);
  57752. }
  57753. _self.postMessage({ id: kind, value: babylonData }, [babylonData.buffer]);
  57754. }
  57755. finally {
  57756. dracoModule.destroy(dracoData);
  57757. }
  57758. }
  57759. }
  57760. finally {
  57761. if (geometry) {
  57762. dracoModule.destroy(geometry);
  57763. }
  57764. dracoModule.destroy(decoder);
  57765. dracoModule.destroy(buffer);
  57766. }
  57767. _self.postMessage("done");
  57768. };
  57769. _self.onmessage = function (event) {
  57770. switch (event.data.id) {
  57771. case "initDecoder": {
  57772. importScripts(event.data.url);
  57773. break;
  57774. }
  57775. case "decodeMesh": {
  57776. decodeMesh(event.data.data, event.data.attributes);
  57777. break;
  57778. }
  57779. }
  57780. };
  57781. };
  57782. DracoCompression._GetDefaultDecoderUrl = function () {
  57783. if (!BABYLON.Tools.IsWindowObjectExist()) {
  57784. return null;
  57785. }
  57786. for (var i = 0; i < document.scripts.length; i++) {
  57787. if (document.scripts[i].type === "text/x-draco-decoder") {
  57788. return document.scripts[i].src;
  57789. }
  57790. }
  57791. return null;
  57792. };
  57793. /**
  57794. * Gets the url to the draco decoder if available.
  57795. */
  57796. DracoCompression.DecoderUrl = DracoCompression._GetDefaultDecoderUrl();
  57797. return DracoCompression;
  57798. }());
  57799. BABYLON.DracoCompression = DracoCompression;
  57800. })(BABYLON || (BABYLON = {}));
  57801. //# sourceMappingURL=babylon.dracoCompression.js.map
  57802. "use strict";
  57803. var BABYLON;
  57804. (function (BABYLON) {
  57805. var AudioEngine = /** @class */ (function () {
  57806. function AudioEngine() {
  57807. this._audioContext = null;
  57808. this._audioContextInitialized = false;
  57809. this.canUseWebAudio = false;
  57810. this.WarnedWebAudioUnsupported = false;
  57811. this.unlocked = false;
  57812. this.isMP3supported = false;
  57813. this.isOGGsupported = false;
  57814. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  57815. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  57816. this.canUseWebAudio = true;
  57817. }
  57818. var audioElem = document.createElement('audio');
  57819. try {
  57820. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  57821. this.isMP3supported = true;
  57822. }
  57823. }
  57824. catch (e) {
  57825. // protect error during capability check.
  57826. }
  57827. try {
  57828. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  57829. this.isOGGsupported = true;
  57830. }
  57831. }
  57832. catch (e) {
  57833. // protect error during capability check.
  57834. }
  57835. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  57836. this._unlockiOSaudio();
  57837. }
  57838. else {
  57839. this.unlocked = true;
  57840. }
  57841. }
  57842. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  57843. get: function () {
  57844. if (!this._audioContextInitialized) {
  57845. this._initializeAudioContext();
  57846. }
  57847. return this._audioContext;
  57848. },
  57849. enumerable: true,
  57850. configurable: true
  57851. });
  57852. AudioEngine.prototype._unlockiOSaudio = function () {
  57853. var _this = this;
  57854. var unlockaudio = function () {
  57855. if (!_this.audioContext) {
  57856. return;
  57857. }
  57858. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  57859. var source = _this.audioContext.createBufferSource();
  57860. source.buffer = buffer;
  57861. source.connect(_this.audioContext.destination);
  57862. source.start(0);
  57863. setTimeout(function () {
  57864. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  57865. _this.unlocked = true;
  57866. window.removeEventListener('touchend', unlockaudio, false);
  57867. if (_this.onAudioUnlocked) {
  57868. _this.onAudioUnlocked();
  57869. }
  57870. }
  57871. }, 0);
  57872. };
  57873. window.addEventListener('touchend', unlockaudio, false);
  57874. };
  57875. AudioEngine.prototype._initializeAudioContext = function () {
  57876. try {
  57877. if (this.canUseWebAudio) {
  57878. this._audioContext = new AudioContext();
  57879. // create a global volume gain node
  57880. this.masterGain = this._audioContext.createGain();
  57881. this.masterGain.gain.value = 1;
  57882. this.masterGain.connect(this._audioContext.destination);
  57883. this._audioContextInitialized = true;
  57884. }
  57885. }
  57886. catch (e) {
  57887. this.canUseWebAudio = false;
  57888. BABYLON.Tools.Error("Web Audio: " + e.message);
  57889. }
  57890. };
  57891. AudioEngine.prototype.dispose = function () {
  57892. if (this.canUseWebAudio && this._audioContextInitialized) {
  57893. if (this._connectedAnalyser && this._audioContext) {
  57894. this._connectedAnalyser.stopDebugCanvas();
  57895. this._connectedAnalyser.dispose();
  57896. this.masterGain.disconnect();
  57897. this.masterGain.connect(this._audioContext.destination);
  57898. this._connectedAnalyser = null;
  57899. }
  57900. this.masterGain.gain.value = 1;
  57901. }
  57902. this.WarnedWebAudioUnsupported = false;
  57903. };
  57904. AudioEngine.prototype.getGlobalVolume = function () {
  57905. if (this.canUseWebAudio && this._audioContextInitialized) {
  57906. return this.masterGain.gain.value;
  57907. }
  57908. else {
  57909. return -1;
  57910. }
  57911. };
  57912. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  57913. if (this.canUseWebAudio && this._audioContextInitialized) {
  57914. this.masterGain.gain.value = newVolume;
  57915. }
  57916. };
  57917. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  57918. if (this._connectedAnalyser) {
  57919. this._connectedAnalyser.stopDebugCanvas();
  57920. }
  57921. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  57922. this._connectedAnalyser = analyser;
  57923. this.masterGain.disconnect();
  57924. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  57925. }
  57926. };
  57927. return AudioEngine;
  57928. }());
  57929. BABYLON.AudioEngine = AudioEngine;
  57930. })(BABYLON || (BABYLON = {}));
  57931. //# sourceMappingURL=babylon.audioEngine.js.map
  57932. "use strict";
  57933. var BABYLON;
  57934. (function (BABYLON) {
  57935. var Sound = /** @class */ (function () {
  57936. /**
  57937. * Create a sound and attach it to a scene
  57938. * @param name Name of your sound
  57939. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  57940. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  57941. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  57942. */
  57943. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  57944. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  57945. var _this = this;
  57946. this.autoplay = false;
  57947. this.loop = false;
  57948. this.useCustomAttenuation = false;
  57949. this.spatialSound = false;
  57950. this.refDistance = 1;
  57951. this.rolloffFactor = 1;
  57952. this.maxDistance = 100;
  57953. this.distanceModel = "linear";
  57954. this._panningModel = "equalpower";
  57955. this._playbackRate = 1;
  57956. this._streaming = false;
  57957. this._startTime = 0;
  57958. this._startOffset = 0;
  57959. this._position = BABYLON.Vector3.Zero();
  57960. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  57961. this._volume = 1;
  57962. this._isReadyToPlay = false;
  57963. this.isPlaying = false;
  57964. this.isPaused = false;
  57965. this._isDirectional = false;
  57966. // Used if you'd like to create a directional sound.
  57967. // If not set, the sound will be omnidirectional
  57968. this._coneInnerAngle = 360;
  57969. this._coneOuterAngle = 360;
  57970. this._coneOuterGain = 0;
  57971. this._isOutputConnected = false;
  57972. this._urlType = "Unknown";
  57973. this.name = name;
  57974. this._scene = scene;
  57975. this._readyToPlayCallback = readyToPlayCallback;
  57976. // Default custom attenuation function is a linear attenuation
  57977. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  57978. if (currentDistance < maxDistance) {
  57979. return currentVolume * (1 - currentDistance / maxDistance);
  57980. }
  57981. else {
  57982. return 0;
  57983. }
  57984. };
  57985. if (options) {
  57986. this.autoplay = options.autoplay || false;
  57987. this.loop = options.loop || false;
  57988. // if volume === 0, we need another way to check this option
  57989. if (options.volume !== undefined) {
  57990. this._volume = options.volume;
  57991. }
  57992. this.spatialSound = options.spatialSound || false;
  57993. this.maxDistance = options.maxDistance || 100;
  57994. this.useCustomAttenuation = options.useCustomAttenuation || false;
  57995. this.rolloffFactor = options.rolloffFactor || 1;
  57996. this.refDistance = options.refDistance || 1;
  57997. this.distanceModel = options.distanceModel || "linear";
  57998. this._playbackRate = options.playbackRate || 1;
  57999. this._streaming = options.streaming || false;
  58000. }
  58001. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  58002. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  58003. this._soundGain.gain.value = this._volume;
  58004. this._inputAudioNode = this._soundGain;
  58005. this._ouputAudioNode = this._soundGain;
  58006. if (this.spatialSound) {
  58007. this._createSpatialParameters();
  58008. }
  58009. this._scene.mainSoundTrack.AddSound(this);
  58010. var validParameter = true;
  58011. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  58012. if (urlOrArrayBuffer) {
  58013. try {
  58014. if (typeof (urlOrArrayBuffer) === "string")
  58015. this._urlType = "String";
  58016. if (Array.isArray(urlOrArrayBuffer))
  58017. this._urlType = "Array";
  58018. if (urlOrArrayBuffer instanceof ArrayBuffer)
  58019. this._urlType = "ArrayBuffer";
  58020. var urls = [];
  58021. var codecSupportedFound = false;
  58022. switch (this._urlType) {
  58023. case "ArrayBuffer":
  58024. if (urlOrArrayBuffer.byteLength > 0) {
  58025. codecSupportedFound = true;
  58026. this._soundLoaded(urlOrArrayBuffer);
  58027. }
  58028. break;
  58029. case "String":
  58030. urls.push(urlOrArrayBuffer);
  58031. case "Array":
  58032. if (urls.length === 0)
  58033. urls = urlOrArrayBuffer;
  58034. // If we found a supported format, we load it immediately and stop the loop
  58035. for (var i = 0; i < urls.length; i++) {
  58036. var url = urls[i];
  58037. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  58038. codecSupportedFound = true;
  58039. }
  58040. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  58041. codecSupportedFound = true;
  58042. }
  58043. if (url.indexOf(".wav", url.length - 4) !== -1) {
  58044. codecSupportedFound = true;
  58045. }
  58046. if (url.indexOf("blob:") !== -1) {
  58047. codecSupportedFound = true;
  58048. }
  58049. if (codecSupportedFound) {
  58050. // Loading sound using XHR2
  58051. if (!this._streaming) {
  58052. this._scene._loadFile(url, function (data) {
  58053. _this._soundLoaded(data);
  58054. }, undefined, true, true, function (exception) {
  58055. if (exception) {
  58056. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  58057. }
  58058. BABYLON.Tools.Error("Sound creation aborted.");
  58059. _this._scene.mainSoundTrack.RemoveSound(_this);
  58060. });
  58061. }
  58062. else {
  58063. this._htmlAudioElement = new Audio(url);
  58064. this._htmlAudioElement.controls = false;
  58065. this._htmlAudioElement.loop = this.loop;
  58066. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  58067. this._htmlAudioElement.preload = "auto";
  58068. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  58069. _this._isReadyToPlay = true;
  58070. if (_this.autoplay) {
  58071. _this.play();
  58072. }
  58073. if (_this._readyToPlayCallback) {
  58074. _this._readyToPlayCallback();
  58075. }
  58076. });
  58077. document.body.appendChild(this._htmlAudioElement);
  58078. }
  58079. break;
  58080. }
  58081. }
  58082. break;
  58083. default:
  58084. validParameter = false;
  58085. break;
  58086. }
  58087. if (!validParameter) {
  58088. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  58089. }
  58090. else {
  58091. if (!codecSupportedFound) {
  58092. this._isReadyToPlay = true;
  58093. // Simulating a ready to play event to avoid breaking code path
  58094. if (this._readyToPlayCallback) {
  58095. window.setTimeout(function () {
  58096. if (_this._readyToPlayCallback) {
  58097. _this._readyToPlayCallback();
  58098. }
  58099. }, 1000);
  58100. }
  58101. }
  58102. }
  58103. }
  58104. catch (ex) {
  58105. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  58106. this._scene.mainSoundTrack.RemoveSound(this);
  58107. }
  58108. }
  58109. }
  58110. else {
  58111. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  58112. this._scene.mainSoundTrack.AddSound(this);
  58113. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  58114. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  58115. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  58116. }
  58117. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  58118. if (this._readyToPlayCallback) {
  58119. window.setTimeout(function () {
  58120. if (_this._readyToPlayCallback) {
  58121. _this._readyToPlayCallback();
  58122. }
  58123. }, 1000);
  58124. }
  58125. }
  58126. }
  58127. Sound.prototype.dispose = function () {
  58128. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  58129. if (this.isPlaying) {
  58130. this.stop();
  58131. }
  58132. this._isReadyToPlay = false;
  58133. if (this.soundTrackId === -1) {
  58134. this._scene.mainSoundTrack.RemoveSound(this);
  58135. }
  58136. else {
  58137. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  58138. }
  58139. if (this._soundGain) {
  58140. this._soundGain.disconnect();
  58141. this._soundGain = null;
  58142. }
  58143. if (this._soundPanner) {
  58144. this._soundPanner.disconnect();
  58145. this._soundPanner = null;
  58146. }
  58147. if (this._soundSource) {
  58148. this._soundSource.disconnect();
  58149. this._soundSource = null;
  58150. }
  58151. this._audioBuffer = null;
  58152. if (this._htmlAudioElement) {
  58153. this._htmlAudioElement.pause();
  58154. this._htmlAudioElement.src = "";
  58155. document.body.removeChild(this._htmlAudioElement);
  58156. }
  58157. if (this._connectedMesh && this._registerFunc) {
  58158. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  58159. this._connectedMesh = null;
  58160. }
  58161. }
  58162. };
  58163. Sound.prototype.isReady = function () {
  58164. return this._isReadyToPlay;
  58165. };
  58166. Sound.prototype._soundLoaded = function (audioData) {
  58167. var _this = this;
  58168. if (!BABYLON.Engine.audioEngine.audioContext) {
  58169. return;
  58170. }
  58171. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  58172. _this._audioBuffer = buffer;
  58173. _this._isReadyToPlay = true;
  58174. if (_this.autoplay) {
  58175. _this.play();
  58176. }
  58177. if (_this._readyToPlayCallback) {
  58178. _this._readyToPlayCallback();
  58179. }
  58180. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  58181. };
  58182. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  58183. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  58184. this._audioBuffer = audioBuffer;
  58185. this._isReadyToPlay = true;
  58186. }
  58187. };
  58188. Sound.prototype.updateOptions = function (options) {
  58189. if (options) {
  58190. this.loop = options.loop || this.loop;
  58191. this.maxDistance = options.maxDistance || this.maxDistance;
  58192. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  58193. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  58194. this.refDistance = options.refDistance || this.refDistance;
  58195. this.distanceModel = options.distanceModel || this.distanceModel;
  58196. this._playbackRate = options.playbackRate || this._playbackRate;
  58197. this._updateSpatialParameters();
  58198. if (this.isPlaying) {
  58199. if (this._streaming) {
  58200. this._htmlAudioElement.playbackRate = this._playbackRate;
  58201. }
  58202. else {
  58203. if (this._soundSource) {
  58204. this._soundSource.playbackRate.value = this._playbackRate;
  58205. }
  58206. }
  58207. }
  58208. }
  58209. };
  58210. Sound.prototype._createSpatialParameters = function () {
  58211. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  58212. if (this._scene.headphone) {
  58213. this._panningModel = "HRTF";
  58214. }
  58215. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  58216. this._updateSpatialParameters();
  58217. this._soundPanner.connect(this._ouputAudioNode);
  58218. this._inputAudioNode = this._soundPanner;
  58219. }
  58220. };
  58221. Sound.prototype._updateSpatialParameters = function () {
  58222. if (this.spatialSound && this._soundPanner) {
  58223. if (this.useCustomAttenuation) {
  58224. // Tricks to disable in a way embedded Web Audio attenuation
  58225. this._soundPanner.distanceModel = "linear";
  58226. this._soundPanner.maxDistance = Number.MAX_VALUE;
  58227. this._soundPanner.refDistance = 1;
  58228. this._soundPanner.rolloffFactor = 1;
  58229. this._soundPanner.panningModel = this._panningModel;
  58230. }
  58231. else {
  58232. this._soundPanner.distanceModel = this.distanceModel;
  58233. this._soundPanner.maxDistance = this.maxDistance;
  58234. this._soundPanner.refDistance = this.refDistance;
  58235. this._soundPanner.rolloffFactor = this.rolloffFactor;
  58236. this._soundPanner.panningModel = this._panningModel;
  58237. }
  58238. }
  58239. };
  58240. Sound.prototype.switchPanningModelToHRTF = function () {
  58241. this._panningModel = "HRTF";
  58242. this._switchPanningModel();
  58243. };
  58244. Sound.prototype.switchPanningModelToEqualPower = function () {
  58245. this._panningModel = "equalpower";
  58246. this._switchPanningModel();
  58247. };
  58248. Sound.prototype._switchPanningModel = function () {
  58249. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  58250. this._soundPanner.panningModel = this._panningModel;
  58251. }
  58252. };
  58253. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  58254. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  58255. if (this._isOutputConnected) {
  58256. this._ouputAudioNode.disconnect();
  58257. }
  58258. this._ouputAudioNode.connect(soundTrackAudioNode);
  58259. this._isOutputConnected = true;
  58260. }
  58261. };
  58262. /**
  58263. * Transform this sound into a directional source
  58264. * @param coneInnerAngle Size of the inner cone in degree
  58265. * @param coneOuterAngle Size of the outer cone in degree
  58266. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  58267. */
  58268. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  58269. if (coneOuterAngle < coneInnerAngle) {
  58270. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  58271. return;
  58272. }
  58273. this._coneInnerAngle = coneInnerAngle;
  58274. this._coneOuterAngle = coneOuterAngle;
  58275. this._coneOuterGain = coneOuterGain;
  58276. this._isDirectional = true;
  58277. if (this.isPlaying && this.loop) {
  58278. this.stop();
  58279. this.play();
  58280. }
  58281. };
  58282. Sound.prototype.setPosition = function (newPosition) {
  58283. this._position = newPosition;
  58284. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  58285. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  58286. }
  58287. };
  58288. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  58289. this._localDirection = newLocalDirection;
  58290. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  58291. this._updateDirection();
  58292. }
  58293. };
  58294. Sound.prototype._updateDirection = function () {
  58295. if (!this._connectedMesh || !this._soundPanner) {
  58296. return;
  58297. }
  58298. var mat = this._connectedMesh.getWorldMatrix();
  58299. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  58300. direction.normalize();
  58301. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  58302. };
  58303. Sound.prototype.updateDistanceFromListener = function () {
  58304. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  58305. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  58306. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  58307. }
  58308. };
  58309. Sound.prototype.setAttenuationFunction = function (callback) {
  58310. this._customAttenuationFunction = callback;
  58311. };
  58312. /**
  58313. * Play the sound
  58314. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  58315. * @param offset (optional) Start the sound setting it at a specific time
  58316. */
  58317. Sound.prototype.play = function (time, offset) {
  58318. var _this = this;
  58319. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  58320. try {
  58321. if (this._startOffset < 0) {
  58322. time = -this._startOffset;
  58323. this._startOffset = 0;
  58324. }
  58325. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  58326. if (!this._soundSource || !this._streamingSource) {
  58327. if (this.spatialSound && this._soundPanner) {
  58328. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  58329. if (this._isDirectional) {
  58330. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  58331. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  58332. this._soundPanner.coneOuterGain = this._coneOuterGain;
  58333. if (this._connectedMesh) {
  58334. this._updateDirection();
  58335. }
  58336. else {
  58337. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  58338. }
  58339. }
  58340. }
  58341. }
  58342. if (this._streaming) {
  58343. if (!this._streamingSource) {
  58344. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  58345. this._htmlAudioElement.onended = function () { _this._onended(); };
  58346. this._htmlAudioElement.playbackRate = this._playbackRate;
  58347. }
  58348. this._streamingSource.disconnect();
  58349. this._streamingSource.connect(this._inputAudioNode);
  58350. this._htmlAudioElement.play();
  58351. }
  58352. else {
  58353. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  58354. this._soundSource.buffer = this._audioBuffer;
  58355. this._soundSource.connect(this._inputAudioNode);
  58356. this._soundSource.loop = this.loop;
  58357. this._soundSource.playbackRate.value = this._playbackRate;
  58358. this._soundSource.onended = function () { _this._onended(); };
  58359. if (this._soundSource.buffer) {
  58360. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  58361. }
  58362. }
  58363. this._startTime = startTime;
  58364. this.isPlaying = true;
  58365. this.isPaused = false;
  58366. }
  58367. catch (ex) {
  58368. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  58369. }
  58370. }
  58371. };
  58372. Sound.prototype._onended = function () {
  58373. this.isPlaying = false;
  58374. if (this.onended) {
  58375. this.onended();
  58376. }
  58377. };
  58378. /**
  58379. * Stop the sound
  58380. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  58381. */
  58382. Sound.prototype.stop = function (time) {
  58383. if (this.isPlaying) {
  58384. if (this._streaming) {
  58385. this._htmlAudioElement.pause();
  58386. // Test needed for Firefox or it will generate an Invalid State Error
  58387. if (this._htmlAudioElement.currentTime > 0) {
  58388. this._htmlAudioElement.currentTime = 0;
  58389. }
  58390. }
  58391. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  58392. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  58393. this._soundSource.stop(stopTime);
  58394. this._soundSource.onended = function () { };
  58395. if (!this.isPaused) {
  58396. this._startOffset = 0;
  58397. }
  58398. }
  58399. this.isPlaying = false;
  58400. }
  58401. };
  58402. Sound.prototype.pause = function () {
  58403. if (this.isPlaying) {
  58404. this.isPaused = true;
  58405. if (this._streaming) {
  58406. this._htmlAudioElement.pause();
  58407. }
  58408. else if (BABYLON.Engine.audioEngine.audioContext) {
  58409. this.stop(0);
  58410. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  58411. }
  58412. }
  58413. };
  58414. Sound.prototype.setVolume = function (newVolume, time) {
  58415. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  58416. if (time && BABYLON.Engine.audioEngine.audioContext) {
  58417. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  58418. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  58419. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  58420. }
  58421. else {
  58422. this._soundGain.gain.value = newVolume;
  58423. }
  58424. }
  58425. this._volume = newVolume;
  58426. };
  58427. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  58428. this._playbackRate = newPlaybackRate;
  58429. if (this.isPlaying) {
  58430. if (this._streaming) {
  58431. this._htmlAudioElement.playbackRate = this._playbackRate;
  58432. }
  58433. else if (this._soundSource) {
  58434. this._soundSource.playbackRate.value = this._playbackRate;
  58435. }
  58436. }
  58437. };
  58438. Sound.prototype.getVolume = function () {
  58439. return this._volume;
  58440. };
  58441. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  58442. var _this = this;
  58443. if (this._connectedMesh && this._registerFunc) {
  58444. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  58445. this._registerFunc = null;
  58446. }
  58447. this._connectedMesh = meshToConnectTo;
  58448. if (!this.spatialSound) {
  58449. this.spatialSound = true;
  58450. this._createSpatialParameters();
  58451. if (this.isPlaying && this.loop) {
  58452. this.stop();
  58453. this.play();
  58454. }
  58455. }
  58456. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  58457. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  58458. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  58459. };
  58460. Sound.prototype.detachFromMesh = function () {
  58461. if (this._connectedMesh && this._registerFunc) {
  58462. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  58463. this._registerFunc = null;
  58464. this._connectedMesh = null;
  58465. }
  58466. };
  58467. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  58468. if (!node.getBoundingInfo) {
  58469. return;
  58470. }
  58471. var mesh = node;
  58472. var boundingInfo = mesh.getBoundingInfo();
  58473. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  58474. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  58475. this._updateDirection();
  58476. }
  58477. };
  58478. Sound.prototype.clone = function () {
  58479. var _this = this;
  58480. if (!this._streaming) {
  58481. var setBufferAndRun = function () {
  58482. if (_this._isReadyToPlay) {
  58483. clonedSound._audioBuffer = _this.getAudioBuffer();
  58484. clonedSound._isReadyToPlay = true;
  58485. if (clonedSound.autoplay) {
  58486. clonedSound.play();
  58487. }
  58488. }
  58489. else {
  58490. window.setTimeout(setBufferAndRun, 300);
  58491. }
  58492. };
  58493. var currentOptions = {
  58494. autoplay: this.autoplay, loop: this.loop,
  58495. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  58496. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  58497. refDistance: this.refDistance, distanceModel: this.distanceModel
  58498. };
  58499. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  58500. if (this.useCustomAttenuation) {
  58501. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  58502. }
  58503. clonedSound.setPosition(this._position);
  58504. clonedSound.setPlaybackRate(this._playbackRate);
  58505. setBufferAndRun();
  58506. return clonedSound;
  58507. }
  58508. else {
  58509. return null;
  58510. }
  58511. };
  58512. Sound.prototype.getAudioBuffer = function () {
  58513. return this._audioBuffer;
  58514. };
  58515. Sound.prototype.serialize = function () {
  58516. var serializationObject = {
  58517. name: this.name,
  58518. url: this.name,
  58519. autoplay: this.autoplay,
  58520. loop: this.loop,
  58521. volume: this._volume,
  58522. spatialSound: this.spatialSound,
  58523. maxDistance: this.maxDistance,
  58524. rolloffFactor: this.rolloffFactor,
  58525. refDistance: this.refDistance,
  58526. distanceModel: this.distanceModel,
  58527. playbackRate: this._playbackRate,
  58528. panningModel: this._panningModel,
  58529. soundTrackId: this.soundTrackId
  58530. };
  58531. if (this.spatialSound) {
  58532. if (this._connectedMesh)
  58533. serializationObject.connectedMeshId = this._connectedMesh.id;
  58534. serializationObject.position = this._position.asArray();
  58535. serializationObject.refDistance = this.refDistance;
  58536. serializationObject.distanceModel = this.distanceModel;
  58537. serializationObject.isDirectional = this._isDirectional;
  58538. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  58539. serializationObject.coneInnerAngle = this._coneInnerAngle;
  58540. serializationObject.coneOuterAngle = this._coneOuterAngle;
  58541. serializationObject.coneOuterGain = this._coneOuterGain;
  58542. }
  58543. return serializationObject;
  58544. };
  58545. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  58546. var soundName = parsedSound.name;
  58547. var soundUrl;
  58548. if (parsedSound.url) {
  58549. soundUrl = rootUrl + parsedSound.url;
  58550. }
  58551. else {
  58552. soundUrl = rootUrl + soundName;
  58553. }
  58554. var options = {
  58555. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  58556. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  58557. rolloffFactor: parsedSound.rolloffFactor,
  58558. refDistance: parsedSound.refDistance,
  58559. distanceModel: parsedSound.distanceModel,
  58560. playbackRate: parsedSound.playbackRate
  58561. };
  58562. var newSound;
  58563. if (!sourceSound) {
  58564. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  58565. scene._addPendingData(newSound);
  58566. }
  58567. else {
  58568. var setBufferAndRun = function () {
  58569. if (sourceSound._isReadyToPlay) {
  58570. newSound._audioBuffer = sourceSound.getAudioBuffer();
  58571. newSound._isReadyToPlay = true;
  58572. if (newSound.autoplay) {
  58573. newSound.play();
  58574. }
  58575. }
  58576. else {
  58577. window.setTimeout(setBufferAndRun, 300);
  58578. }
  58579. };
  58580. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  58581. setBufferAndRun();
  58582. }
  58583. if (parsedSound.position) {
  58584. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  58585. newSound.setPosition(soundPosition);
  58586. }
  58587. if (parsedSound.isDirectional) {
  58588. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  58589. if (parsedSound.localDirectionToMesh) {
  58590. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  58591. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  58592. }
  58593. }
  58594. if (parsedSound.connectedMeshId) {
  58595. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  58596. if (connectedMesh) {
  58597. newSound.attachToMesh(connectedMesh);
  58598. }
  58599. }
  58600. return newSound;
  58601. };
  58602. return Sound;
  58603. }());
  58604. BABYLON.Sound = Sound;
  58605. })(BABYLON || (BABYLON = {}));
  58606. //# sourceMappingURL=babylon.sound.js.map
  58607. "use strict";
  58608. var BABYLON;
  58609. (function (BABYLON) {
  58610. var SoundTrack = /** @class */ (function () {
  58611. function SoundTrack(scene, options) {
  58612. this.id = -1;
  58613. this._isMainTrack = false;
  58614. this._isInitialized = false;
  58615. this._scene = scene;
  58616. this.soundCollection = new Array();
  58617. this._options = options;
  58618. if (!this._isMainTrack) {
  58619. this._scene.soundTracks.push(this);
  58620. this.id = this._scene.soundTracks.length - 1;
  58621. }
  58622. }
  58623. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  58624. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  58625. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  58626. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  58627. if (this._options) {
  58628. if (this._options.volume) {
  58629. this._outputAudioNode.gain.value = this._options.volume;
  58630. }
  58631. if (this._options.mainTrack) {
  58632. this._isMainTrack = this._options.mainTrack;
  58633. }
  58634. }
  58635. this._isInitialized = true;
  58636. }
  58637. };
  58638. SoundTrack.prototype.dispose = function () {
  58639. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  58640. if (this._connectedAnalyser) {
  58641. this._connectedAnalyser.stopDebugCanvas();
  58642. }
  58643. while (this.soundCollection.length) {
  58644. this.soundCollection[0].dispose();
  58645. }
  58646. if (this._outputAudioNode) {
  58647. this._outputAudioNode.disconnect();
  58648. }
  58649. this._outputAudioNode = null;
  58650. }
  58651. };
  58652. SoundTrack.prototype.AddSound = function (sound) {
  58653. if (!this._isInitialized) {
  58654. this._initializeSoundTrackAudioGraph();
  58655. }
  58656. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  58657. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  58658. }
  58659. if (sound.soundTrackId) {
  58660. if (sound.soundTrackId === -1) {
  58661. this._scene.mainSoundTrack.RemoveSound(sound);
  58662. }
  58663. else {
  58664. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  58665. }
  58666. }
  58667. this.soundCollection.push(sound);
  58668. sound.soundTrackId = this.id;
  58669. };
  58670. SoundTrack.prototype.RemoveSound = function (sound) {
  58671. var index = this.soundCollection.indexOf(sound);
  58672. if (index !== -1) {
  58673. this.soundCollection.splice(index, 1);
  58674. }
  58675. };
  58676. SoundTrack.prototype.setVolume = function (newVolume) {
  58677. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  58678. this._outputAudioNode.gain.value = newVolume;
  58679. }
  58680. };
  58681. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  58682. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  58683. for (var i = 0; i < this.soundCollection.length; i++) {
  58684. this.soundCollection[i].switchPanningModelToHRTF();
  58685. }
  58686. }
  58687. };
  58688. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  58689. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  58690. for (var i = 0; i < this.soundCollection.length; i++) {
  58691. this.soundCollection[i].switchPanningModelToEqualPower();
  58692. }
  58693. }
  58694. };
  58695. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  58696. if (this._connectedAnalyser) {
  58697. this._connectedAnalyser.stopDebugCanvas();
  58698. }
  58699. this._connectedAnalyser = analyser;
  58700. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  58701. this._outputAudioNode.disconnect();
  58702. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  58703. }
  58704. };
  58705. return SoundTrack;
  58706. }());
  58707. BABYLON.SoundTrack = SoundTrack;
  58708. })(BABYLON || (BABYLON = {}));
  58709. //# sourceMappingURL=babylon.soundtrack.js.map
  58710. "use strict";
  58711. var BABYLON;
  58712. (function (BABYLON) {
  58713. var Analyser = /** @class */ (function () {
  58714. function Analyser(scene) {
  58715. this.SMOOTHING = 0.75;
  58716. this.FFT_SIZE = 512;
  58717. this.BARGRAPHAMPLITUDE = 256;
  58718. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  58719. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  58720. this._scene = scene;
  58721. this._audioEngine = BABYLON.Engine.audioEngine;
  58722. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  58723. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  58724. this._webAudioAnalyser.minDecibels = -140;
  58725. this._webAudioAnalyser.maxDecibels = 0;
  58726. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  58727. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  58728. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  58729. }
  58730. }
  58731. Analyser.prototype.getFrequencyBinCount = function () {
  58732. if (this._audioEngine.canUseWebAudio) {
  58733. return this._webAudioAnalyser.frequencyBinCount;
  58734. }
  58735. else {
  58736. return 0;
  58737. }
  58738. };
  58739. Analyser.prototype.getByteFrequencyData = function () {
  58740. if (this._audioEngine.canUseWebAudio) {
  58741. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  58742. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  58743. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  58744. }
  58745. return this._byteFreqs;
  58746. };
  58747. Analyser.prototype.getByteTimeDomainData = function () {
  58748. if (this._audioEngine.canUseWebAudio) {
  58749. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  58750. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  58751. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  58752. }
  58753. return this._byteTime;
  58754. };
  58755. Analyser.prototype.getFloatFrequencyData = function () {
  58756. if (this._audioEngine.canUseWebAudio) {
  58757. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  58758. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  58759. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  58760. }
  58761. return this._floatFreqs;
  58762. };
  58763. Analyser.prototype.drawDebugCanvas = function () {
  58764. var _this = this;
  58765. if (this._audioEngine.canUseWebAudio) {
  58766. if (!this._debugCanvas) {
  58767. this._debugCanvas = document.createElement("canvas");
  58768. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  58769. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  58770. this._debugCanvas.style.position = "absolute";
  58771. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  58772. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  58773. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  58774. document.body.appendChild(this._debugCanvas);
  58775. this._registerFunc = function () {
  58776. _this.drawDebugCanvas();
  58777. };
  58778. this._scene.registerBeforeRender(this._registerFunc);
  58779. }
  58780. if (this._registerFunc && this._debugCanvasContext) {
  58781. var workingArray = this.getByteFrequencyData();
  58782. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  58783. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  58784. // Draw the frequency domain chart.
  58785. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  58786. var value = workingArray[i];
  58787. var percent = value / this.BARGRAPHAMPLITUDE;
  58788. var height = this.DEBUGCANVASSIZE.height * percent;
  58789. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  58790. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  58791. var hue = i / this.getFrequencyBinCount() * 360;
  58792. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  58793. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  58794. }
  58795. }
  58796. }
  58797. };
  58798. Analyser.prototype.stopDebugCanvas = function () {
  58799. if (this._debugCanvas) {
  58800. if (this._registerFunc) {
  58801. this._scene.unregisterBeforeRender(this._registerFunc);
  58802. this._registerFunc = null;
  58803. }
  58804. document.body.removeChild(this._debugCanvas);
  58805. this._debugCanvas = null;
  58806. this._debugCanvasContext = null;
  58807. }
  58808. };
  58809. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  58810. if (this._audioEngine.canUseWebAudio) {
  58811. inputAudioNode.connect(this._webAudioAnalyser);
  58812. this._webAudioAnalyser.connect(outputAudioNode);
  58813. }
  58814. };
  58815. Analyser.prototype.dispose = function () {
  58816. if (this._audioEngine.canUseWebAudio) {
  58817. this._webAudioAnalyser.disconnect();
  58818. }
  58819. };
  58820. return Analyser;
  58821. }());
  58822. BABYLON.Analyser = Analyser;
  58823. })(BABYLON || (BABYLON = {}));
  58824. //# sourceMappingURL=babylon.analyser.js.map
  58825. "use strict";
  58826. var BABYLON;
  58827. (function (BABYLON) {
  58828. var CubeTexture = /** @class */ (function (_super) {
  58829. __extends(CubeTexture, _super);
  58830. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  58831. if (extensions === void 0) { extensions = null; }
  58832. if (noMipmap === void 0) { noMipmap = false; }
  58833. if (files === void 0) { files = null; }
  58834. if (onLoad === void 0) { onLoad = null; }
  58835. if (onError === void 0) { onError = null; }
  58836. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  58837. if (prefiltered === void 0) { prefiltered = false; }
  58838. if (forcedExtension === void 0) { forcedExtension = null; }
  58839. var _this = _super.call(this, scene) || this;
  58840. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  58841. /**
  58842. * Gets or sets the center of the bounding box associated with the cube texture
  58843. * It must define where the camera used to render the texture was set
  58844. */
  58845. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  58846. _this.name = rootUrl;
  58847. _this.url = rootUrl;
  58848. _this._noMipmap = noMipmap;
  58849. _this.hasAlpha = false;
  58850. _this._format = format;
  58851. _this._prefiltered = prefiltered;
  58852. _this.isCube = true;
  58853. _this._textureMatrix = BABYLON.Matrix.Identity();
  58854. if (prefiltered) {
  58855. _this.gammaSpace = false;
  58856. }
  58857. if (!rootUrl && !files) {
  58858. return _this;
  58859. }
  58860. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  58861. var lastDot = rootUrl.lastIndexOf(".");
  58862. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  58863. var isDDS = (extension === ".dds");
  58864. if (!files) {
  58865. if (!isDDS && !extensions) {
  58866. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  58867. }
  58868. files = [];
  58869. if (extensions) {
  58870. for (var index = 0; index < extensions.length; index++) {
  58871. files.push(rootUrl + extensions[index]);
  58872. }
  58873. }
  58874. }
  58875. _this._files = files;
  58876. if (!_this._texture) {
  58877. if (!scene.useDelayedTextureLoading) {
  58878. if (prefiltered) {
  58879. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  58880. }
  58881. else {
  58882. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  58883. }
  58884. }
  58885. else {
  58886. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  58887. }
  58888. }
  58889. else if (onLoad) {
  58890. if (_this._texture.isReady) {
  58891. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  58892. }
  58893. else {
  58894. _this._texture.onLoadedObservable.add(onLoad);
  58895. }
  58896. }
  58897. return _this;
  58898. }
  58899. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  58900. get: function () {
  58901. return this._boundingBoxSize;
  58902. },
  58903. /**
  58904. * Gets or sets the size of the bounding box associated with the cube texture
  58905. * When defined, the cubemap will switch to local mode
  58906. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  58907. * @example https://www.babylonjs-playground.com/#RNASML
  58908. */
  58909. set: function (value) {
  58910. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  58911. return;
  58912. }
  58913. this._boundingBoxSize = value;
  58914. var scene = this.getScene();
  58915. if (scene) {
  58916. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  58917. }
  58918. },
  58919. enumerable: true,
  58920. configurable: true
  58921. });
  58922. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  58923. var rootUrlKey = "";
  58924. files.forEach(function (url) { return rootUrlKey += url; });
  58925. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  58926. };
  58927. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  58928. if (forcedExtension === void 0) { forcedExtension = null; }
  58929. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  58930. };
  58931. // Methods
  58932. CubeTexture.prototype.delayLoad = function () {
  58933. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  58934. return;
  58935. }
  58936. var scene = this.getScene();
  58937. if (!scene) {
  58938. return;
  58939. }
  58940. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  58941. this._texture = this._getFromCache(this.url, this._noMipmap);
  58942. if (!this._texture) {
  58943. if (this._prefiltered) {
  58944. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  58945. }
  58946. else {
  58947. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  58948. }
  58949. }
  58950. };
  58951. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  58952. return this._textureMatrix;
  58953. };
  58954. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  58955. this._textureMatrix = value;
  58956. };
  58957. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  58958. var texture = BABYLON.SerializationHelper.Parse(function () {
  58959. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  58960. }, parsedTexture, scene);
  58961. // Local Cubemaps
  58962. if (parsedTexture.boundingBoxPosition) {
  58963. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  58964. }
  58965. if (parsedTexture.boundingBoxSize) {
  58966. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  58967. }
  58968. // Animations
  58969. if (parsedTexture.animations) {
  58970. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  58971. var parsedAnimation = parsedTexture.animations[animationIndex];
  58972. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  58973. }
  58974. }
  58975. return texture;
  58976. };
  58977. CubeTexture.prototype.clone = function () {
  58978. var _this = this;
  58979. return BABYLON.SerializationHelper.Clone(function () {
  58980. var scene = _this.getScene();
  58981. if (!scene) {
  58982. return _this;
  58983. }
  58984. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  58985. }, this);
  58986. };
  58987. return CubeTexture;
  58988. }(BABYLON.BaseTexture));
  58989. BABYLON.CubeTexture = CubeTexture;
  58990. })(BABYLON || (BABYLON = {}));
  58991. //# sourceMappingURL=babylon.cubeTexture.js.map
  58992. "use strict";
  58993. var BABYLON;
  58994. (function (BABYLON) {
  58995. var RenderTargetTexture = /** @class */ (function (_super) {
  58996. __extends(RenderTargetTexture, _super);
  58997. /**
  58998. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  58999. * or used a shadow, depth texture...
  59000. * @param name The friendly name of the texture
  59001. * @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)
  59002. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  59003. * @param generateMipMaps True if mip maps need to be generated after render.
  59004. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  59005. * @param type The type of the buffer in the RTT (int, half float, float...)
  59006. * @param isCube True if a cube texture needs to be created
  59007. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  59008. * @param generateDepthBuffer True to generate a depth buffer
  59009. * @param generateStencilBuffer True to generate a stencil buffer
  59010. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  59011. */
  59012. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  59013. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  59014. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59015. if (isCube === void 0) { isCube = false; }
  59016. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59017. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  59018. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  59019. if (isMulti === void 0) { isMulti = false; }
  59020. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  59021. _this.isCube = isCube;
  59022. /**
  59023. * Use this list to define the list of mesh you want to render.
  59024. */
  59025. _this.renderList = new Array();
  59026. _this.renderParticles = true;
  59027. _this.renderSprites = false;
  59028. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  59029. _this.ignoreCameraViewport = false;
  59030. // Events
  59031. /**
  59032. * An event triggered when the texture is unbind.
  59033. * @type {BABYLON.Observable}
  59034. */
  59035. _this.onBeforeBindObservable = new BABYLON.Observable();
  59036. /**
  59037. * An event triggered when the texture is unbind.
  59038. * @type {BABYLON.Observable}
  59039. */
  59040. _this.onAfterUnbindObservable = new BABYLON.Observable();
  59041. /**
  59042. * An event triggered before rendering the texture
  59043. * @type {BABYLON.Observable}
  59044. */
  59045. _this.onBeforeRenderObservable = new BABYLON.Observable();
  59046. /**
  59047. * An event triggered after rendering the texture
  59048. * @type {BABYLON.Observable}
  59049. */
  59050. _this.onAfterRenderObservable = new BABYLON.Observable();
  59051. /**
  59052. * An event triggered after the texture clear
  59053. * @type {BABYLON.Observable}
  59054. */
  59055. _this.onClearObservable = new BABYLON.Observable();
  59056. _this._currentRefreshId = -1;
  59057. _this._refreshRate = 1;
  59058. _this._samples = 1;
  59059. /**
  59060. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  59061. * It must define where the camera used to render the texture is set
  59062. */
  59063. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  59064. scene = _this.getScene();
  59065. if (!scene) {
  59066. return _this;
  59067. }
  59068. _this._engine = scene.getEngine();
  59069. _this.name = name;
  59070. _this.isRenderTarget = true;
  59071. _this._initialSizeParameter = size;
  59072. _this._processSizeParameter(size);
  59073. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  59074. });
  59075. _this._generateMipMaps = generateMipMaps ? true : false;
  59076. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  59077. // Rendering groups
  59078. _this._renderingManager = new BABYLON.RenderingManager(scene);
  59079. if (isMulti) {
  59080. return _this;
  59081. }
  59082. _this._renderTargetOptions = {
  59083. generateMipMaps: generateMipMaps,
  59084. type: type,
  59085. samplingMode: samplingMode,
  59086. generateDepthBuffer: generateDepthBuffer,
  59087. generateStencilBuffer: generateStencilBuffer
  59088. };
  59089. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  59090. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59091. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59092. }
  59093. if (isCube) {
  59094. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  59095. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  59096. _this._textureMatrix = BABYLON.Matrix.Identity();
  59097. }
  59098. else {
  59099. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  59100. }
  59101. return _this;
  59102. }
  59103. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  59104. get: function () {
  59105. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  59106. },
  59107. enumerable: true,
  59108. configurable: true
  59109. });
  59110. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  59111. get: function () {
  59112. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  59113. },
  59114. enumerable: true,
  59115. configurable: true
  59116. });
  59117. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  59118. get: function () {
  59119. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  59120. },
  59121. enumerable: true,
  59122. configurable: true
  59123. });
  59124. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  59125. set: function (callback) {
  59126. if (this._onAfterUnbindObserver) {
  59127. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  59128. }
  59129. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  59130. },
  59131. enumerable: true,
  59132. configurable: true
  59133. });
  59134. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  59135. set: function (callback) {
  59136. if (this._onBeforeRenderObserver) {
  59137. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  59138. }
  59139. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  59140. },
  59141. enumerable: true,
  59142. configurable: true
  59143. });
  59144. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  59145. set: function (callback) {
  59146. if (this._onAfterRenderObserver) {
  59147. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  59148. }
  59149. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  59150. },
  59151. enumerable: true,
  59152. configurable: true
  59153. });
  59154. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  59155. set: function (callback) {
  59156. if (this._onClearObserver) {
  59157. this.onClearObservable.remove(this._onClearObserver);
  59158. }
  59159. this._onClearObserver = this.onClearObservable.add(callback);
  59160. },
  59161. enumerable: true,
  59162. configurable: true
  59163. });
  59164. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  59165. get: function () {
  59166. return this._renderTargetOptions;
  59167. },
  59168. enumerable: true,
  59169. configurable: true
  59170. });
  59171. RenderTargetTexture.prototype._onRatioRescale = function () {
  59172. if (this._sizeRatio) {
  59173. this.resize(this._initialSizeParameter);
  59174. }
  59175. };
  59176. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  59177. get: function () {
  59178. return this._boundingBoxSize;
  59179. },
  59180. /**
  59181. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  59182. * When defined, the cubemap will switch to local mode
  59183. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  59184. * @example https://www.babylonjs-playground.com/#RNASML
  59185. */
  59186. set: function (value) {
  59187. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  59188. return;
  59189. }
  59190. this._boundingBoxSize = value;
  59191. var scene = this.getScene();
  59192. if (scene) {
  59193. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  59194. }
  59195. },
  59196. enumerable: true,
  59197. configurable: true
  59198. });
  59199. /**
  59200. * Creates a depth stencil texture.
  59201. * This is only available in WebGL 2 or with the depth texture extension available.
  59202. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  59203. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  59204. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  59205. */
  59206. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  59207. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  59208. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  59209. if (generateStencil === void 0) { generateStencil = false; }
  59210. if (!this.getScene()) {
  59211. return;
  59212. }
  59213. var engine = this.getScene().getEngine();
  59214. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  59215. bilinearFiltering: bilinearFiltering,
  59216. comparisonFunction: comparisonFunction,
  59217. generateStencil: generateStencil,
  59218. isCube: this.isCube
  59219. });
  59220. engine.setFrameBufferDepthStencilTexture(this);
  59221. };
  59222. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  59223. if (size.ratio) {
  59224. this._sizeRatio = size.ratio;
  59225. this._size = {
  59226. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  59227. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  59228. };
  59229. }
  59230. else {
  59231. this._size = size;
  59232. }
  59233. };
  59234. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  59235. get: function () {
  59236. return this._samples;
  59237. },
  59238. set: function (value) {
  59239. if (this._samples === value) {
  59240. return;
  59241. }
  59242. var scene = this.getScene();
  59243. if (!scene) {
  59244. return;
  59245. }
  59246. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  59247. },
  59248. enumerable: true,
  59249. configurable: true
  59250. });
  59251. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  59252. this._currentRefreshId = -1;
  59253. };
  59254. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  59255. get: function () {
  59256. return this._refreshRate;
  59257. },
  59258. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  59259. set: function (value) {
  59260. this._refreshRate = value;
  59261. this.resetRefreshCounter();
  59262. },
  59263. enumerable: true,
  59264. configurable: true
  59265. });
  59266. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  59267. if (!this._postProcessManager) {
  59268. var scene = this.getScene();
  59269. if (!scene) {
  59270. return;
  59271. }
  59272. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  59273. this._postProcesses = new Array();
  59274. }
  59275. this._postProcesses.push(postProcess);
  59276. this._postProcesses[0].autoClear = false;
  59277. };
  59278. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  59279. if (!this._postProcesses) {
  59280. return;
  59281. }
  59282. if (dispose) {
  59283. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  59284. var postProcess = _a[_i];
  59285. postProcess.dispose();
  59286. }
  59287. }
  59288. this._postProcesses = [];
  59289. };
  59290. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  59291. if (!this._postProcesses) {
  59292. return;
  59293. }
  59294. var index = this._postProcesses.indexOf(postProcess);
  59295. if (index === -1) {
  59296. return;
  59297. }
  59298. this._postProcesses.splice(index, 1);
  59299. if (this._postProcesses.length > 0) {
  59300. this._postProcesses[0].autoClear = false;
  59301. }
  59302. };
  59303. RenderTargetTexture.prototype._shouldRender = function () {
  59304. if (this._currentRefreshId === -1) {
  59305. this._currentRefreshId = 1;
  59306. return true;
  59307. }
  59308. if (this.refreshRate === this._currentRefreshId) {
  59309. this._currentRefreshId = 1;
  59310. return true;
  59311. }
  59312. this._currentRefreshId++;
  59313. return false;
  59314. };
  59315. RenderTargetTexture.prototype.getRenderSize = function () {
  59316. if (this._size.width) {
  59317. return this._size.width;
  59318. }
  59319. return this._size;
  59320. };
  59321. RenderTargetTexture.prototype.getRenderWidth = function () {
  59322. if (this._size.width) {
  59323. return this._size.width;
  59324. }
  59325. return this._size;
  59326. };
  59327. RenderTargetTexture.prototype.getRenderHeight = function () {
  59328. if (this._size.width) {
  59329. return this._size.height;
  59330. }
  59331. return this._size;
  59332. };
  59333. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  59334. get: function () {
  59335. return true;
  59336. },
  59337. enumerable: true,
  59338. configurable: true
  59339. });
  59340. RenderTargetTexture.prototype.scale = function (ratio) {
  59341. var newSize = this.getRenderSize() * ratio;
  59342. this.resize(newSize);
  59343. };
  59344. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  59345. if (this.isCube) {
  59346. return this._textureMatrix;
  59347. }
  59348. return _super.prototype.getReflectionTextureMatrix.call(this);
  59349. };
  59350. RenderTargetTexture.prototype.resize = function (size) {
  59351. this.releaseInternalTexture();
  59352. var scene = this.getScene();
  59353. if (!scene) {
  59354. return;
  59355. }
  59356. this._processSizeParameter(size);
  59357. if (this.isCube) {
  59358. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  59359. }
  59360. else {
  59361. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  59362. }
  59363. };
  59364. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  59365. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  59366. if (dumpForDebug === void 0) { dumpForDebug = false; }
  59367. var scene = this.getScene();
  59368. if (!scene) {
  59369. return;
  59370. }
  59371. var engine = scene.getEngine();
  59372. if (this.useCameraPostProcesses !== undefined) {
  59373. useCameraPostProcess = this.useCameraPostProcesses;
  59374. }
  59375. if (this._waitingRenderList) {
  59376. this.renderList = [];
  59377. for (var index = 0; index < this._waitingRenderList.length; index++) {
  59378. var id = this._waitingRenderList[index];
  59379. var mesh_1 = scene.getMeshByID(id);
  59380. if (mesh_1) {
  59381. this.renderList.push(mesh_1);
  59382. }
  59383. }
  59384. delete this._waitingRenderList;
  59385. }
  59386. // Is predicate defined?
  59387. if (this.renderListPredicate) {
  59388. if (this.renderList) {
  59389. this.renderList.splice(0); // Clear previous renderList
  59390. }
  59391. else {
  59392. this.renderList = [];
  59393. }
  59394. var scene = this.getScene();
  59395. if (!scene) {
  59396. return;
  59397. }
  59398. var sceneMeshes = scene.meshes;
  59399. for (var index = 0; index < sceneMeshes.length; index++) {
  59400. var mesh = sceneMeshes[index];
  59401. if (this.renderListPredicate(mesh)) {
  59402. this.renderList.push(mesh);
  59403. }
  59404. }
  59405. }
  59406. this.onBeforeBindObservable.notifyObservers(this);
  59407. // Set custom projection.
  59408. // Needs to be before binding to prevent changing the aspect ratio.
  59409. var camera;
  59410. if (this.activeCamera) {
  59411. camera = this.activeCamera;
  59412. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  59413. if (this.activeCamera !== scene.activeCamera) {
  59414. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  59415. }
  59416. }
  59417. else {
  59418. camera = scene.activeCamera;
  59419. if (camera) {
  59420. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  59421. }
  59422. }
  59423. // Prepare renderingManager
  59424. this._renderingManager.reset();
  59425. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  59426. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  59427. var sceneRenderId = scene.getRenderId();
  59428. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  59429. var mesh = currentRenderList[meshIndex];
  59430. if (mesh) {
  59431. if (!mesh.isReady(this.refreshRate === 0)) {
  59432. this.resetRefreshCounter();
  59433. continue;
  59434. }
  59435. mesh._preActivateForIntermediateRendering(sceneRenderId);
  59436. var isMasked = void 0;
  59437. if (!this.renderList && camera) {
  59438. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  59439. }
  59440. else {
  59441. isMasked = false;
  59442. }
  59443. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  59444. mesh._activate(sceneRenderId);
  59445. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  59446. var subMesh = mesh.subMeshes[subIndex];
  59447. scene._activeIndices.addCount(subMesh.indexCount, false);
  59448. this._renderingManager.dispatch(subMesh, mesh);
  59449. }
  59450. }
  59451. }
  59452. }
  59453. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  59454. var particleSystem = scene.particleSystems[particleIndex];
  59455. var emitter = particleSystem.emitter;
  59456. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  59457. continue;
  59458. }
  59459. if (currentRenderList.indexOf(emitter) >= 0) {
  59460. this._renderingManager.dispatchParticles(particleSystem);
  59461. }
  59462. }
  59463. if (this.isCube) {
  59464. for (var face = 0; face < 6; face++) {
  59465. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  59466. scene.incrementRenderId();
  59467. scene.resetCachedMaterial();
  59468. }
  59469. }
  59470. else {
  59471. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  59472. }
  59473. this.onAfterUnbindObservable.notifyObservers(this);
  59474. if (scene.activeCamera) {
  59475. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  59476. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  59477. }
  59478. engine.setViewport(scene.activeCamera.viewport);
  59479. }
  59480. scene.resetCachedMaterial();
  59481. };
  59482. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  59483. var minimum = 128;
  59484. var x = renderDimension * scale;
  59485. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  59486. // Ensure we don't exceed the render dimension (while staying POT)
  59487. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  59488. };
  59489. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  59490. var _this = this;
  59491. if (!this._texture) {
  59492. return;
  59493. }
  59494. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  59495. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  59496. });
  59497. };
  59498. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  59499. var scene = this.getScene();
  59500. if (!scene) {
  59501. return;
  59502. }
  59503. var engine = scene.getEngine();
  59504. if (!this._texture) {
  59505. return;
  59506. }
  59507. // Bind
  59508. if (this._postProcessManager) {
  59509. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  59510. }
  59511. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  59512. if (this._texture) {
  59513. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  59514. }
  59515. }
  59516. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  59517. // Clear
  59518. if (this.onClearObservable.hasObservers()) {
  59519. this.onClearObservable.notifyObservers(engine);
  59520. }
  59521. else {
  59522. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  59523. }
  59524. if (!this._doNotChangeAspectRatio) {
  59525. scene.updateTransformMatrix(true);
  59526. }
  59527. // Render
  59528. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  59529. if (this._postProcessManager) {
  59530. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  59531. }
  59532. else if (useCameraPostProcess) {
  59533. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  59534. }
  59535. if (!this._doNotChangeAspectRatio) {
  59536. scene.updateTransformMatrix(true);
  59537. }
  59538. // Dump ?
  59539. if (dumpForDebug) {
  59540. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  59541. }
  59542. // Unbind
  59543. if (!this.isCube || faceIndex === 5) {
  59544. if (this.isCube) {
  59545. if (faceIndex === 5) {
  59546. engine.generateMipMapsForCubemap(this._texture);
  59547. }
  59548. }
  59549. this.unbindFrameBuffer(engine, faceIndex);
  59550. }
  59551. else {
  59552. this.onAfterRenderObservable.notifyObservers(faceIndex);
  59553. }
  59554. };
  59555. /**
  59556. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  59557. * This allowed control for front to back rendering or reversly depending of the special needs.
  59558. *
  59559. * @param renderingGroupId The rendering group id corresponding to its index
  59560. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  59561. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  59562. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  59563. */
  59564. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  59565. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  59566. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  59567. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  59568. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  59569. };
  59570. /**
  59571. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  59572. *
  59573. * @param renderingGroupId The rendering group id corresponding to its index
  59574. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  59575. */
  59576. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  59577. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  59578. };
  59579. RenderTargetTexture.prototype.clone = function () {
  59580. var textureSize = this.getSize();
  59581. 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);
  59582. // Base texture
  59583. newTexture.hasAlpha = this.hasAlpha;
  59584. newTexture.level = this.level;
  59585. // RenderTarget Texture
  59586. newTexture.coordinatesMode = this.coordinatesMode;
  59587. if (this.renderList) {
  59588. newTexture.renderList = this.renderList.slice(0);
  59589. }
  59590. return newTexture;
  59591. };
  59592. RenderTargetTexture.prototype.serialize = function () {
  59593. if (!this.name) {
  59594. return null;
  59595. }
  59596. var serializationObject = _super.prototype.serialize.call(this);
  59597. serializationObject.renderTargetSize = this.getRenderSize();
  59598. serializationObject.renderList = [];
  59599. if (this.renderList) {
  59600. for (var index = 0; index < this.renderList.length; index++) {
  59601. serializationObject.renderList.push(this.renderList[index].id);
  59602. }
  59603. }
  59604. return serializationObject;
  59605. };
  59606. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  59607. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  59608. var objBuffer = this.getInternalTexture();
  59609. var scene = this.getScene();
  59610. if (objBuffer && scene) {
  59611. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  59612. }
  59613. };
  59614. RenderTargetTexture.prototype.dispose = function () {
  59615. if (this._postProcessManager) {
  59616. this._postProcessManager.dispose();
  59617. this._postProcessManager = null;
  59618. }
  59619. this.clearPostProcesses(true);
  59620. if (this._resizeObserver) {
  59621. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  59622. this._resizeObserver = null;
  59623. }
  59624. this.renderList = null;
  59625. // Remove from custom render targets
  59626. var scene = this.getScene();
  59627. if (!scene) {
  59628. return;
  59629. }
  59630. var index = scene.customRenderTargets.indexOf(this);
  59631. if (index >= 0) {
  59632. scene.customRenderTargets.splice(index, 1);
  59633. }
  59634. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  59635. var camera = _a[_i];
  59636. index = camera.customRenderTargets.indexOf(this);
  59637. if (index >= 0) {
  59638. camera.customRenderTargets.splice(index, 1);
  59639. }
  59640. }
  59641. _super.prototype.dispose.call(this);
  59642. };
  59643. RenderTargetTexture.prototype._rebuild = function () {
  59644. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  59645. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  59646. }
  59647. if (this._postProcessManager) {
  59648. this._postProcessManager._rebuild();
  59649. }
  59650. };
  59651. /**
  59652. * Clear the info related to rendering groups preventing retention point in material dispose.
  59653. */
  59654. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  59655. if (this._renderingManager) {
  59656. this._renderingManager.freeRenderingGroups();
  59657. }
  59658. };
  59659. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  59660. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  59661. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  59662. return RenderTargetTexture;
  59663. }(BABYLON.Texture));
  59664. BABYLON.RenderTargetTexture = RenderTargetTexture;
  59665. })(BABYLON || (BABYLON = {}));
  59666. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  59667. "use strict";
  59668. var BABYLON;
  59669. (function (BABYLON) {
  59670. ;
  59671. var MultiRenderTarget = /** @class */ (function (_super) {
  59672. __extends(MultiRenderTarget, _super);
  59673. function MultiRenderTarget(name, size, count, scene, options) {
  59674. var _this = this;
  59675. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  59676. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  59677. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  59678. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  59679. _this._engine = scene.getEngine();
  59680. if (!_this.isSupported) {
  59681. _this.dispose();
  59682. return;
  59683. }
  59684. var types = [];
  59685. var samplingModes = [];
  59686. for (var i = 0; i < count; i++) {
  59687. if (options && options.types && options.types[i] !== undefined) {
  59688. types.push(options.types[i]);
  59689. }
  59690. else {
  59691. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  59692. }
  59693. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  59694. samplingModes.push(options.samplingModes[i]);
  59695. }
  59696. else {
  59697. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  59698. }
  59699. }
  59700. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  59701. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  59702. _this._size = size;
  59703. _this._multiRenderTargetOptions = {
  59704. samplingModes: samplingModes,
  59705. generateMipMaps: generateMipMaps,
  59706. generateDepthBuffer: generateDepthBuffer,
  59707. generateStencilBuffer: generateStencilBuffer,
  59708. generateDepthTexture: generateDepthTexture,
  59709. types: types,
  59710. textureCount: count
  59711. };
  59712. _this._createInternalTextures();
  59713. _this._createTextures();
  59714. return _this;
  59715. }
  59716. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  59717. get: function () {
  59718. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  59719. },
  59720. enumerable: true,
  59721. configurable: true
  59722. });
  59723. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  59724. get: function () {
  59725. return this._textures;
  59726. },
  59727. enumerable: true,
  59728. configurable: true
  59729. });
  59730. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  59731. get: function () {
  59732. return this._textures[this._textures.length - 1];
  59733. },
  59734. enumerable: true,
  59735. configurable: true
  59736. });
  59737. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  59738. set: function (wrap) {
  59739. if (this._textures) {
  59740. for (var i = 0; i < this._textures.length; i++) {
  59741. this._textures[i].wrapU = wrap;
  59742. }
  59743. }
  59744. },
  59745. enumerable: true,
  59746. configurable: true
  59747. });
  59748. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  59749. set: function (wrap) {
  59750. if (this._textures) {
  59751. for (var i = 0; i < this._textures.length; i++) {
  59752. this._textures[i].wrapV = wrap;
  59753. }
  59754. }
  59755. },
  59756. enumerable: true,
  59757. configurable: true
  59758. });
  59759. MultiRenderTarget.prototype._rebuild = function () {
  59760. this.releaseInternalTextures();
  59761. this._createInternalTextures();
  59762. for (var i = 0; i < this._internalTextures.length; i++) {
  59763. var texture = this._textures[i];
  59764. texture._texture = this._internalTextures[i];
  59765. }
  59766. // Keeps references to frame buffer and stencil/depth buffer
  59767. this._texture = this._internalTextures[0];
  59768. };
  59769. MultiRenderTarget.prototype._createInternalTextures = function () {
  59770. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  59771. };
  59772. MultiRenderTarget.prototype._createTextures = function () {
  59773. this._textures = [];
  59774. for (var i = 0; i < this._internalTextures.length; i++) {
  59775. var texture = new BABYLON.Texture(null, this.getScene());
  59776. texture._texture = this._internalTextures[i];
  59777. this._textures.push(texture);
  59778. }
  59779. // Keeps references to frame buffer and stencil/depth buffer
  59780. this._texture = this._internalTextures[0];
  59781. };
  59782. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  59783. get: function () {
  59784. return this._samples;
  59785. },
  59786. set: function (value) {
  59787. if (this._samples === value) {
  59788. return;
  59789. }
  59790. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  59791. },
  59792. enumerable: true,
  59793. configurable: true
  59794. });
  59795. MultiRenderTarget.prototype.resize = function (size) {
  59796. this.releaseInternalTextures();
  59797. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  59798. this._createInternalTextures();
  59799. };
  59800. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  59801. var _this = this;
  59802. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  59803. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  59804. });
  59805. };
  59806. MultiRenderTarget.prototype.dispose = function () {
  59807. this.releaseInternalTextures();
  59808. _super.prototype.dispose.call(this);
  59809. };
  59810. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  59811. if (!this._internalTextures) {
  59812. return;
  59813. }
  59814. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  59815. if (this._internalTextures[i] !== undefined) {
  59816. this._internalTextures[i].dispose();
  59817. this._internalTextures.splice(i, 1);
  59818. }
  59819. }
  59820. };
  59821. return MultiRenderTarget;
  59822. }(BABYLON.RenderTargetTexture));
  59823. BABYLON.MultiRenderTarget = MultiRenderTarget;
  59824. })(BABYLON || (BABYLON = {}));
  59825. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  59826. "use strict";
  59827. var BABYLON;
  59828. (function (BABYLON) {
  59829. var MirrorTexture = /** @class */ (function (_super) {
  59830. __extends(MirrorTexture, _super);
  59831. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  59832. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59833. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  59834. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  59835. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  59836. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  59837. _this._transformMatrix = BABYLON.Matrix.Zero();
  59838. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  59839. _this._adaptiveBlurKernel = 0;
  59840. _this._blurKernelX = 0;
  59841. _this._blurKernelY = 0;
  59842. _this._blurRatio = 1.0;
  59843. _this.ignoreCameraViewport = true;
  59844. _this.onBeforeRenderObservable.add(function () {
  59845. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  59846. _this._savedViewMatrix = scene.getViewMatrix();
  59847. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  59848. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  59849. scene.clipPlane = _this.mirrorPlane;
  59850. scene.getEngine().cullBackFaces = false;
  59851. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  59852. });
  59853. _this.onAfterRenderObservable.add(function () {
  59854. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  59855. scene.getEngine().cullBackFaces = true;
  59856. scene._mirroredCameraPosition = null;
  59857. delete scene.clipPlane;
  59858. });
  59859. return _this;
  59860. }
  59861. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  59862. get: function () {
  59863. return this._blurRatio;
  59864. },
  59865. set: function (value) {
  59866. if (this._blurRatio === value) {
  59867. return;
  59868. }
  59869. this._blurRatio = value;
  59870. this._preparePostProcesses();
  59871. },
  59872. enumerable: true,
  59873. configurable: true
  59874. });
  59875. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  59876. set: function (value) {
  59877. this._adaptiveBlurKernel = value;
  59878. this._autoComputeBlurKernel();
  59879. },
  59880. enumerable: true,
  59881. configurable: true
  59882. });
  59883. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  59884. set: function (value) {
  59885. this.blurKernelX = value;
  59886. this.blurKernelY = value;
  59887. },
  59888. enumerable: true,
  59889. configurable: true
  59890. });
  59891. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  59892. get: function () {
  59893. return this._blurKernelX;
  59894. },
  59895. set: function (value) {
  59896. if (this._blurKernelX === value) {
  59897. return;
  59898. }
  59899. this._blurKernelX = value;
  59900. this._preparePostProcesses();
  59901. },
  59902. enumerable: true,
  59903. configurable: true
  59904. });
  59905. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  59906. get: function () {
  59907. return this._blurKernelY;
  59908. },
  59909. set: function (value) {
  59910. if (this._blurKernelY === value) {
  59911. return;
  59912. }
  59913. this._blurKernelY = value;
  59914. this._preparePostProcesses();
  59915. },
  59916. enumerable: true,
  59917. configurable: true
  59918. });
  59919. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  59920. var engine = this.getScene().getEngine();
  59921. var dw = this.getRenderWidth() / engine.getRenderWidth();
  59922. var dh = this.getRenderHeight() / engine.getRenderHeight();
  59923. this.blurKernelX = this._adaptiveBlurKernel * dw;
  59924. this.blurKernelY = this._adaptiveBlurKernel * dh;
  59925. };
  59926. MirrorTexture.prototype._onRatioRescale = function () {
  59927. if (this._sizeRatio) {
  59928. this.resize(this._initialSizeParameter);
  59929. if (!this._adaptiveBlurKernel) {
  59930. this._preparePostProcesses();
  59931. }
  59932. }
  59933. if (this._adaptiveBlurKernel) {
  59934. this._autoComputeBlurKernel();
  59935. }
  59936. };
  59937. MirrorTexture.prototype._preparePostProcesses = function () {
  59938. this.clearPostProcesses(true);
  59939. if (this._blurKernelX && this._blurKernelY) {
  59940. var engine = this.getScene().getEngine();
  59941. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  59942. 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);
  59943. this._blurX.autoClear = false;
  59944. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  59945. this._blurX.inputTexture = this._texture;
  59946. }
  59947. else {
  59948. this._blurX.alwaysForcePOT = true;
  59949. }
  59950. 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);
  59951. this._blurY.autoClear = false;
  59952. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  59953. this.addPostProcess(this._blurX);
  59954. this.addPostProcess(this._blurY);
  59955. }
  59956. else {
  59957. if (this._blurY) {
  59958. this.removePostProcess(this._blurY);
  59959. this._blurY.dispose();
  59960. this._blurY = null;
  59961. }
  59962. if (this._blurX) {
  59963. this.removePostProcess(this._blurX);
  59964. this._blurX.dispose();
  59965. this._blurX = null;
  59966. }
  59967. }
  59968. };
  59969. MirrorTexture.prototype.clone = function () {
  59970. var scene = this.getScene();
  59971. if (!scene) {
  59972. return this;
  59973. }
  59974. var textureSize = this.getSize();
  59975. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  59976. // Base texture
  59977. newTexture.hasAlpha = this.hasAlpha;
  59978. newTexture.level = this.level;
  59979. // Mirror Texture
  59980. newTexture.mirrorPlane = this.mirrorPlane.clone();
  59981. if (this.renderList) {
  59982. newTexture.renderList = this.renderList.slice(0);
  59983. }
  59984. return newTexture;
  59985. };
  59986. MirrorTexture.prototype.serialize = function () {
  59987. if (!this.name) {
  59988. return null;
  59989. }
  59990. var serializationObject = _super.prototype.serialize.call(this);
  59991. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  59992. return serializationObject;
  59993. };
  59994. return MirrorTexture;
  59995. }(BABYLON.RenderTargetTexture));
  59996. BABYLON.MirrorTexture = MirrorTexture;
  59997. })(BABYLON || (BABYLON = {}));
  59998. //# sourceMappingURL=babylon.mirrorTexture.js.map
  59999. "use strict";
  60000. var BABYLON;
  60001. (function (BABYLON) {
  60002. /**
  60003. * Creates a refraction texture used by refraction channel of the standard material.
  60004. * @param name the texture name
  60005. * @param size size of the underlying texture
  60006. * @param scene root scene
  60007. */
  60008. var RefractionTexture = /** @class */ (function (_super) {
  60009. __extends(RefractionTexture, _super);
  60010. function RefractionTexture(name, size, scene, generateMipMaps) {
  60011. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  60012. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  60013. _this.depth = 2.0;
  60014. _this.onBeforeRenderObservable.add(function () {
  60015. scene.clipPlane = _this.refractionPlane;
  60016. });
  60017. _this.onAfterRenderObservable.add(function () {
  60018. delete scene.clipPlane;
  60019. });
  60020. return _this;
  60021. }
  60022. RefractionTexture.prototype.clone = function () {
  60023. var scene = this.getScene();
  60024. if (!scene) {
  60025. return this;
  60026. }
  60027. var textureSize = this.getSize();
  60028. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  60029. // Base texture
  60030. newTexture.hasAlpha = this.hasAlpha;
  60031. newTexture.level = this.level;
  60032. // Refraction Texture
  60033. newTexture.refractionPlane = this.refractionPlane.clone();
  60034. if (this.renderList) {
  60035. newTexture.renderList = this.renderList.slice(0);
  60036. }
  60037. newTexture.depth = this.depth;
  60038. return newTexture;
  60039. };
  60040. RefractionTexture.prototype.serialize = function () {
  60041. if (!this.name) {
  60042. return null;
  60043. }
  60044. var serializationObject = _super.prototype.serialize.call(this);
  60045. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  60046. serializationObject.depth = this.depth;
  60047. return serializationObject;
  60048. };
  60049. return RefractionTexture;
  60050. }(BABYLON.RenderTargetTexture));
  60051. BABYLON.RefractionTexture = RefractionTexture;
  60052. })(BABYLON || (BABYLON = {}));
  60053. //# sourceMappingURL=babylon.refractionTexture.js.map
  60054. "use strict";
  60055. var BABYLON;
  60056. (function (BABYLON) {
  60057. var DynamicTexture = /** @class */ (function (_super) {
  60058. __extends(DynamicTexture, _super);
  60059. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  60060. if (scene === void 0) { scene = null; }
  60061. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60062. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  60063. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  60064. _this.name = name;
  60065. _this._engine = _this.getScene().getEngine();
  60066. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60067. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60068. _this._generateMipMaps = generateMipMaps;
  60069. if (options.getContext) {
  60070. _this._canvas = options;
  60071. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  60072. }
  60073. else {
  60074. _this._canvas = document.createElement("canvas");
  60075. if (options.width) {
  60076. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  60077. }
  60078. else {
  60079. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  60080. }
  60081. }
  60082. var textureSize = _this.getSize();
  60083. _this._canvas.width = textureSize.width;
  60084. _this._canvas.height = textureSize.height;
  60085. _this._context = _this._canvas.getContext("2d");
  60086. return _this;
  60087. }
  60088. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  60089. get: function () {
  60090. return true;
  60091. },
  60092. enumerable: true,
  60093. configurable: true
  60094. });
  60095. DynamicTexture.prototype._recreate = function (textureSize) {
  60096. this._canvas.width = textureSize.width;
  60097. this._canvas.height = textureSize.height;
  60098. this.releaseInternalTexture();
  60099. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  60100. };
  60101. DynamicTexture.prototype.scale = function (ratio) {
  60102. var textureSize = this.getSize();
  60103. textureSize.width *= ratio;
  60104. textureSize.height *= ratio;
  60105. this._recreate(textureSize);
  60106. };
  60107. DynamicTexture.prototype.scaleTo = function (width, height) {
  60108. var textureSize = this.getSize();
  60109. textureSize.width = width;
  60110. textureSize.height = height;
  60111. this._recreate(textureSize);
  60112. };
  60113. DynamicTexture.prototype.getContext = function () {
  60114. return this._context;
  60115. };
  60116. DynamicTexture.prototype.clear = function () {
  60117. var size = this.getSize();
  60118. this._context.fillRect(0, 0, size.width, size.height);
  60119. };
  60120. DynamicTexture.prototype.update = function (invertY) {
  60121. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  60122. };
  60123. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  60124. if (update === void 0) { update = true; }
  60125. var size = this.getSize();
  60126. if (clearColor) {
  60127. this._context.fillStyle = clearColor;
  60128. this._context.fillRect(0, 0, size.width, size.height);
  60129. }
  60130. this._context.font = font;
  60131. if (x === null || x === undefined) {
  60132. var textSize = this._context.measureText(text);
  60133. x = (size.width - textSize.width) / 2;
  60134. }
  60135. if (y === null || y === undefined) {
  60136. var fontSize = parseInt((font.replace(/\D/g, '')));
  60137. ;
  60138. y = (size.height / 2) + (fontSize / 3.65);
  60139. }
  60140. this._context.fillStyle = color;
  60141. this._context.fillText(text, x, y);
  60142. if (update) {
  60143. this.update(invertY);
  60144. }
  60145. };
  60146. DynamicTexture.prototype.clone = function () {
  60147. var scene = this.getScene();
  60148. if (!scene) {
  60149. return this;
  60150. }
  60151. var textureSize = this.getSize();
  60152. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  60153. // Base texture
  60154. newTexture.hasAlpha = this.hasAlpha;
  60155. newTexture.level = this.level;
  60156. // Dynamic Texture
  60157. newTexture.wrapU = this.wrapU;
  60158. newTexture.wrapV = this.wrapV;
  60159. return newTexture;
  60160. };
  60161. DynamicTexture.prototype._rebuild = function () {
  60162. this.update();
  60163. };
  60164. return DynamicTexture;
  60165. }(BABYLON.Texture));
  60166. BABYLON.DynamicTexture = DynamicTexture;
  60167. })(BABYLON || (BABYLON = {}));
  60168. //# sourceMappingURL=babylon.dynamicTexture.js.map
  60169. "use strict";
  60170. var BABYLON;
  60171. (function (BABYLON) {
  60172. var VideoTexture = /** @class */ (function (_super) {
  60173. __extends(VideoTexture, _super);
  60174. /**
  60175. * Creates a video texture.
  60176. * Sample : https://doc.babylonjs.com/how_to/video_texture
  60177. * @param {string | null} name optional name, will detect from video source, if not defined
  60178. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  60179. * @param {BABYLON.Scene} scene is obviously the current scene.
  60180. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  60181. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  60182. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  60183. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  60184. */
  60185. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  60186. if (generateMipMaps === void 0) { generateMipMaps = false; }
  60187. if (invertY === void 0) { invertY = false; }
  60188. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60189. if (settings === void 0) { settings = {
  60190. autoPlay: true,
  60191. loop: true,
  60192. autoUpdateTexture: true,
  60193. }; }
  60194. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  60195. _this._createInternalTexture = function () {
  60196. if (_this._texture != null) {
  60197. return;
  60198. }
  60199. if (!_this._engine.needPOTTextures ||
  60200. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  60201. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  60202. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  60203. }
  60204. else {
  60205. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60206. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60207. _this._generateMipMaps = false;
  60208. }
  60209. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  60210. _this._texture.isReady = true;
  60211. _this._updateInternalTexture();
  60212. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  60213. _this.onLoadObservable.notifyObservers(_this);
  60214. }
  60215. };
  60216. _this.reset = function () {
  60217. if (_this._texture == null) {
  60218. return;
  60219. }
  60220. _this._texture.dispose();
  60221. _this._texture = null;
  60222. };
  60223. _this._updateInternalTexture = function (e) {
  60224. if (_this._texture == null || !_this._texture.isReady) {
  60225. return;
  60226. }
  60227. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  60228. return;
  60229. }
  60230. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  60231. };
  60232. _this._engine = _this.getScene().getEngine();
  60233. _this._generateMipMaps = generateMipMaps;
  60234. _this._samplingMode = samplingMode;
  60235. _this.autoUpdateTexture = settings.autoUpdateTexture;
  60236. _this.name = name || _this._getName(src);
  60237. _this.video = _this._getVideo(src);
  60238. if (settings.autoPlay !== undefined) {
  60239. _this.video.autoplay = settings.autoPlay;
  60240. }
  60241. if (settings.loop !== undefined) {
  60242. _this.video.loop = settings.loop;
  60243. }
  60244. _this.video.addEventListener("canplay", _this._createInternalTexture);
  60245. _this.video.addEventListener("paused", _this._updateInternalTexture);
  60246. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  60247. _this.video.addEventListener("emptied", _this.reset);
  60248. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  60249. _this._createInternalTexture();
  60250. }
  60251. return _this;
  60252. }
  60253. VideoTexture.prototype._getName = function (src) {
  60254. if (src instanceof HTMLVideoElement) {
  60255. return src.currentSrc;
  60256. }
  60257. if (typeof src === "object") {
  60258. return src.toString();
  60259. }
  60260. return src;
  60261. };
  60262. ;
  60263. VideoTexture.prototype._getVideo = function (src) {
  60264. if (src instanceof HTMLVideoElement) {
  60265. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  60266. return src;
  60267. }
  60268. var video = document.createElement("video");
  60269. if (typeof src === "string") {
  60270. BABYLON.Tools.SetCorsBehavior(src, video);
  60271. video.src = src;
  60272. }
  60273. else {
  60274. BABYLON.Tools.SetCorsBehavior(src[0], video);
  60275. src.forEach(function (url) {
  60276. var source = document.createElement("source");
  60277. source.src = url;
  60278. video.appendChild(source);
  60279. });
  60280. }
  60281. return video;
  60282. };
  60283. ;
  60284. /**
  60285. * Internal method to initiate `update`.
  60286. */
  60287. VideoTexture.prototype._rebuild = function () {
  60288. this.update();
  60289. };
  60290. /**
  60291. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  60292. */
  60293. VideoTexture.prototype.update = function () {
  60294. if (!this.autoUpdateTexture) {
  60295. // Expecting user to call `updateTexture` manually
  60296. return;
  60297. }
  60298. this.updateTexture(true);
  60299. };
  60300. /**
  60301. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  60302. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  60303. */
  60304. VideoTexture.prototype.updateTexture = function (isVisible) {
  60305. if (!isVisible) {
  60306. return;
  60307. }
  60308. if (this.video.paused) {
  60309. return;
  60310. }
  60311. this._updateInternalTexture();
  60312. };
  60313. /**
  60314. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  60315. * @param url New url.
  60316. */
  60317. VideoTexture.prototype.updateURL = function (url) {
  60318. this.video.src = url;
  60319. };
  60320. VideoTexture.prototype.dispose = function () {
  60321. _super.prototype.dispose.call(this);
  60322. this.video.removeEventListener("canplay", this._createInternalTexture);
  60323. this.video.removeEventListener("paused", this._updateInternalTexture);
  60324. this.video.removeEventListener("seeked", this._updateInternalTexture);
  60325. this.video.removeEventListener("emptied", this.reset);
  60326. this.video.pause();
  60327. };
  60328. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  60329. var video = document.createElement("video");
  60330. var constraintsDeviceId;
  60331. if (constraints && constraints.deviceId) {
  60332. constraintsDeviceId = {
  60333. exact: constraints.deviceId,
  60334. };
  60335. }
  60336. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  60337. if (navigator.mediaDevices) {
  60338. navigator.mediaDevices.getUserMedia({ video: constraints })
  60339. .then(function (stream) {
  60340. if (video.mozSrcObject !== undefined) {
  60341. // hack for Firefox < 19
  60342. video.mozSrcObject = stream;
  60343. }
  60344. else {
  60345. video.srcObject = stream;
  60346. }
  60347. var onPlaying = function () {
  60348. if (onReady) {
  60349. onReady(new VideoTexture("video", video, scene, true, true));
  60350. }
  60351. video.removeEventListener("playing", onPlaying);
  60352. };
  60353. video.addEventListener("playing", onPlaying);
  60354. video.play();
  60355. })
  60356. .catch(function (err) {
  60357. BABYLON.Tools.Error(err.name);
  60358. });
  60359. }
  60360. else {
  60361. navigator.getUserMedia =
  60362. navigator.getUserMedia ||
  60363. navigator.webkitGetUserMedia ||
  60364. navigator.mozGetUserMedia ||
  60365. navigator.msGetUserMedia;
  60366. if (navigator.getUserMedia) {
  60367. navigator.getUserMedia({
  60368. video: {
  60369. deviceId: constraintsDeviceId,
  60370. width: {
  60371. min: (constraints && constraints.minWidth) || 256,
  60372. max: (constraints && constraints.maxWidth) || 640,
  60373. },
  60374. height: {
  60375. min: (constraints && constraints.minHeight) || 256,
  60376. max: (constraints && constraints.maxHeight) || 480,
  60377. },
  60378. },
  60379. }, function (stream) {
  60380. if (video.mozSrcObject !== undefined) {
  60381. // hack for Firefox < 19
  60382. video.mozSrcObject = stream;
  60383. }
  60384. else {
  60385. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  60386. }
  60387. video.play();
  60388. if (onReady) {
  60389. onReady(new VideoTexture("video", video, scene, true, true));
  60390. }
  60391. }, function (e) {
  60392. BABYLON.Tools.Error(e.name);
  60393. });
  60394. }
  60395. }
  60396. };
  60397. return VideoTexture;
  60398. }(BABYLON.Texture));
  60399. BABYLON.VideoTexture = VideoTexture;
  60400. })(BABYLON || (BABYLON = {}));
  60401. //# sourceMappingURL=babylon.videoTexture.js.map
  60402. "use strict";
  60403. var BABYLON;
  60404. (function (BABYLON) {
  60405. var RawTexture = /** @class */ (function (_super) {
  60406. __extends(RawTexture, _super);
  60407. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  60408. if (generateMipMaps === void 0) { generateMipMaps = true; }
  60409. if (invertY === void 0) { invertY = false; }
  60410. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60411. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60412. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  60413. _this.format = format;
  60414. _this._engine = scene.getEngine();
  60415. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  60416. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60417. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60418. return _this;
  60419. }
  60420. RawTexture.prototype.update = function (data) {
  60421. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  60422. };
  60423. // Statics
  60424. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  60425. if (generateMipMaps === void 0) { generateMipMaps = true; }
  60426. if (invertY === void 0) { invertY = false; }
  60427. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60428. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  60429. };
  60430. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  60431. if (generateMipMaps === void 0) { generateMipMaps = true; }
  60432. if (invertY === void 0) { invertY = false; }
  60433. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60434. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  60435. };
  60436. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  60437. if (generateMipMaps === void 0) { generateMipMaps = true; }
  60438. if (invertY === void 0) { invertY = false; }
  60439. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60440. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  60441. };
  60442. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  60443. if (generateMipMaps === void 0) { generateMipMaps = true; }
  60444. if (invertY === void 0) { invertY = false; }
  60445. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60446. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60447. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  60448. };
  60449. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  60450. if (generateMipMaps === void 0) { generateMipMaps = true; }
  60451. if (invertY === void 0) { invertY = false; }
  60452. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60453. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60454. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  60455. };
  60456. return RawTexture;
  60457. }(BABYLON.Texture));
  60458. BABYLON.RawTexture = RawTexture;
  60459. })(BABYLON || (BABYLON = {}));
  60460. //# sourceMappingURL=babylon.rawTexture.js.map
  60461. "use strict";
  60462. var BABYLON;
  60463. (function (BABYLON) {
  60464. /**
  60465. * PostProcess can be used to apply a shader to a texture after it has been rendered
  60466. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  60467. */
  60468. var PostProcess = /** @class */ (function () {
  60469. /**
  60470. * Creates a new instance of @see PostProcess
  60471. * @param name The name of the PostProcess.
  60472. * @param fragmentUrl The url of the fragment shader to be used.
  60473. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  60474. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  60475. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  60476. * @param camera The camera to apply the render pass to.
  60477. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  60478. * @param engine The engine which the post process will be applied. (default: current engine)
  60479. * @param reusable If the post process can be reused on the same frame. (default: false)
  60480. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  60481. * @param textureType Type of textures used when performing the post process. (default: 0)
  60482. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  60483. * @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
  60484. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  60485. */
  60486. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  60487. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  60488. if (defines === void 0) { defines = null; }
  60489. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60490. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  60491. if (blockCompilation === void 0) { blockCompilation = false; }
  60492. this.name = name;
  60493. /**
  60494. * Width of the texture to apply the post process on
  60495. */
  60496. this.width = -1;
  60497. /**
  60498. * Height of the texture to apply the post process on
  60499. */
  60500. this.height = -1;
  60501. /**
  60502. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  60503. */
  60504. this._outputTexture = null;
  60505. /**
  60506. * If the buffer needs to be cleared before applying the post process. (default: true)
  60507. * Should be set to false if shader will overwrite all previous pixels.
  60508. */
  60509. this.autoClear = true;
  60510. /**
  60511. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  60512. */
  60513. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  60514. /**
  60515. * Animations to be used for the post processing
  60516. */
  60517. this.animations = new Array();
  60518. /**
  60519. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  60520. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  60521. */
  60522. this.enablePixelPerfectMode = false;
  60523. /**
  60524. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  60525. */
  60526. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  60527. /**
  60528. * Force textures to be a power of two (default: false)
  60529. */
  60530. this.alwaysForcePOT = false;
  60531. /**
  60532. * Number of sample textures (default: 1)
  60533. */
  60534. this.samples = 1;
  60535. /**
  60536. * Modify the scale of the post process to be the same as the viewport (default: false)
  60537. */
  60538. this.adaptScaleToCurrentViewport = false;
  60539. this._reusable = false;
  60540. /**
  60541. * Smart array of input and output textures for the post process.
  60542. */
  60543. this._textures = new BABYLON.SmartArray(2);
  60544. /**
  60545. * The index in _textures that corresponds to the output texture.
  60546. */
  60547. this._currentRenderTextureInd = 0;
  60548. this._scaleRatio = new BABYLON.Vector2(1, 1);
  60549. this._texelSize = BABYLON.Vector2.Zero();
  60550. // Events
  60551. /**
  60552. * An event triggered when the postprocess is activated.
  60553. * @type {BABYLON.Observable}
  60554. */
  60555. this.onActivateObservable = new BABYLON.Observable();
  60556. /**
  60557. * An event triggered when the postprocess changes its size.
  60558. * @type {BABYLON.Observable}
  60559. */
  60560. this.onSizeChangedObservable = new BABYLON.Observable();
  60561. /**
  60562. * An event triggered when the postprocess applies its effect.
  60563. * @type {BABYLON.Observable}
  60564. */
  60565. this.onApplyObservable = new BABYLON.Observable();
  60566. /**
  60567. * An event triggered before rendering the postprocess
  60568. * @type {BABYLON.Observable}
  60569. */
  60570. this.onBeforeRenderObservable = new BABYLON.Observable();
  60571. /**
  60572. * An event triggered after rendering the postprocess
  60573. * @type {BABYLON.Observable}
  60574. */
  60575. this.onAfterRenderObservable = new BABYLON.Observable();
  60576. if (camera != null) {
  60577. this._camera = camera;
  60578. this._scene = camera.getScene();
  60579. camera.attachPostProcess(this);
  60580. this._engine = this._scene.getEngine();
  60581. this._scene.postProcesses.push(this);
  60582. }
  60583. else if (engine) {
  60584. this._engine = engine;
  60585. this._engine.postProcesses.push(this);
  60586. }
  60587. this._options = options;
  60588. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  60589. this._reusable = reusable || false;
  60590. this._textureType = textureType;
  60591. this._samplers = samplers || [];
  60592. this._samplers.push("textureSampler");
  60593. this._fragmentUrl = fragmentUrl;
  60594. this._vertexUrl = vertexUrl;
  60595. this._parameters = parameters || [];
  60596. this._parameters.push("scale");
  60597. this._indexParameters = indexParameters;
  60598. if (!blockCompilation) {
  60599. this.updateEffect(defines);
  60600. }
  60601. }
  60602. Object.defineProperty(PostProcess.prototype, "onActivate", {
  60603. /**
  60604. * A function that is added to the onActivateObservable
  60605. */
  60606. set: function (callback) {
  60607. if (this._onActivateObserver) {
  60608. this.onActivateObservable.remove(this._onActivateObserver);
  60609. }
  60610. if (callback) {
  60611. this._onActivateObserver = this.onActivateObservable.add(callback);
  60612. }
  60613. },
  60614. enumerable: true,
  60615. configurable: true
  60616. });
  60617. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  60618. /**
  60619. * A function that is added to the onSizeChangedObservable
  60620. */
  60621. set: function (callback) {
  60622. if (this._onSizeChangedObserver) {
  60623. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  60624. }
  60625. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  60626. },
  60627. enumerable: true,
  60628. configurable: true
  60629. });
  60630. Object.defineProperty(PostProcess.prototype, "onApply", {
  60631. /**
  60632. * A function that is added to the onApplyObservable
  60633. */
  60634. set: function (callback) {
  60635. if (this._onApplyObserver) {
  60636. this.onApplyObservable.remove(this._onApplyObserver);
  60637. }
  60638. this._onApplyObserver = this.onApplyObservable.add(callback);
  60639. },
  60640. enumerable: true,
  60641. configurable: true
  60642. });
  60643. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  60644. /**
  60645. * A function that is added to the onBeforeRenderObservable
  60646. */
  60647. set: function (callback) {
  60648. if (this._onBeforeRenderObserver) {
  60649. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  60650. }
  60651. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  60652. },
  60653. enumerable: true,
  60654. configurable: true
  60655. });
  60656. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  60657. /**
  60658. * A function that is added to the onAfterRenderObservable
  60659. */
  60660. set: function (callback) {
  60661. if (this._onAfterRenderObserver) {
  60662. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  60663. }
  60664. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  60665. },
  60666. enumerable: true,
  60667. configurable: true
  60668. });
  60669. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  60670. /**
  60671. * 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
  60672. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  60673. */
  60674. get: function () {
  60675. return this._textures.data[this._currentRenderTextureInd];
  60676. },
  60677. set: function (value) {
  60678. this._forcedOutputTexture = value;
  60679. },
  60680. enumerable: true,
  60681. configurable: true
  60682. });
  60683. /**
  60684. * Gets the camera which post process is applied to.
  60685. * @returns The camera the post process is applied to.
  60686. */
  60687. PostProcess.prototype.getCamera = function () {
  60688. return this._camera;
  60689. };
  60690. Object.defineProperty(PostProcess.prototype, "texelSize", {
  60691. /**
  60692. * Gets the texel size of the postprocess.
  60693. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  60694. */
  60695. get: function () {
  60696. if (this._shareOutputWithPostProcess) {
  60697. return this._shareOutputWithPostProcess.texelSize;
  60698. }
  60699. if (this._forcedOutputTexture) {
  60700. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  60701. }
  60702. return this._texelSize;
  60703. },
  60704. enumerable: true,
  60705. configurable: true
  60706. });
  60707. /**
  60708. * Gets the engine which this post process belongs to.
  60709. * @returns The engine the post process was enabled with.
  60710. */
  60711. PostProcess.prototype.getEngine = function () {
  60712. return this._engine;
  60713. };
  60714. /**
  60715. * The effect that is created when initializing the post process.
  60716. * @returns The created effect corrisponding the the postprocess.
  60717. */
  60718. PostProcess.prototype.getEffect = function () {
  60719. return this._effect;
  60720. };
  60721. /**
  60722. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  60723. * @param postProcess The post process to share the output with.
  60724. * @returns This post process.
  60725. */
  60726. PostProcess.prototype.shareOutputWith = function (postProcess) {
  60727. this._disposeTextures();
  60728. this._shareOutputWithPostProcess = postProcess;
  60729. return this;
  60730. };
  60731. /**
  60732. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  60733. * This should be called if the post process that shares output with this post process is disabled/disposed.
  60734. */
  60735. PostProcess.prototype.useOwnOutput = function () {
  60736. if (this._textures.length == 0) {
  60737. this._textures = new BABYLON.SmartArray(2);
  60738. }
  60739. this._shareOutputWithPostProcess = null;
  60740. };
  60741. /**
  60742. * Updates the effect with the current post process compile time values and recompiles the shader.
  60743. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  60744. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  60745. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  60746. * @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
  60747. * @param onCompiled Called when the shader has been compiled.
  60748. * @param onError Called if there is an error when compiling a shader.
  60749. */
  60750. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  60751. if (defines === void 0) { defines = null; }
  60752. if (uniforms === void 0) { uniforms = null; }
  60753. if (samplers === void 0) { samplers = null; }
  60754. 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);
  60755. };
  60756. /**
  60757. * The post process is reusable if it can be used multiple times within one frame.
  60758. * @returns If the post process is reusable
  60759. */
  60760. PostProcess.prototype.isReusable = function () {
  60761. return this._reusable;
  60762. };
  60763. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  60764. PostProcess.prototype.markTextureDirty = function () {
  60765. this.width = -1;
  60766. };
  60767. /**
  60768. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  60769. * 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.
  60770. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  60771. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  60772. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  60773. * @returns The target texture that was bound to be written to.
  60774. */
  60775. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  60776. var _this = this;
  60777. if (sourceTexture === void 0) { sourceTexture = null; }
  60778. camera = camera || this._camera;
  60779. var scene = camera.getScene();
  60780. var engine = scene.getEngine();
  60781. var maxSize = engine.getCaps().maxTextureSize;
  60782. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  60783. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  60784. // 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
  60785. var webVRCamera = camera.parent;
  60786. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  60787. requiredWidth /= 2;
  60788. }
  60789. var desiredWidth = (this._options.width || requiredWidth);
  60790. var desiredHeight = this._options.height || requiredHeight;
  60791. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  60792. if (this.adaptScaleToCurrentViewport) {
  60793. var currentViewport = engine.currentViewport;
  60794. if (currentViewport) {
  60795. desiredWidth *= currentViewport.width;
  60796. desiredHeight *= currentViewport.height;
  60797. }
  60798. }
  60799. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  60800. if (!this._options.width) {
  60801. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  60802. }
  60803. if (!this._options.height) {
  60804. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  60805. }
  60806. }
  60807. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  60808. if (this._textures.length > 0) {
  60809. for (var i = 0; i < this._textures.length; i++) {
  60810. this._engine._releaseTexture(this._textures.data[i]);
  60811. }
  60812. this._textures.reset();
  60813. }
  60814. this.width = desiredWidth;
  60815. this.height = desiredHeight;
  60816. var textureSize = { width: this.width, height: this.height };
  60817. var textureOptions = {
  60818. generateMipMaps: false,
  60819. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  60820. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  60821. samplingMode: this.renderTargetSamplingMode,
  60822. type: this._textureType
  60823. };
  60824. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  60825. if (this._reusable) {
  60826. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  60827. }
  60828. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  60829. this.onSizeChangedObservable.notifyObservers(this);
  60830. }
  60831. this._textures.forEach(function (texture) {
  60832. if (texture.samples !== _this.samples) {
  60833. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  60834. }
  60835. });
  60836. }
  60837. var target;
  60838. if (this._shareOutputWithPostProcess) {
  60839. target = this._shareOutputWithPostProcess.inputTexture;
  60840. }
  60841. else if (this._forcedOutputTexture) {
  60842. target = this._forcedOutputTexture;
  60843. this.width = this._forcedOutputTexture.width;
  60844. this.height = this._forcedOutputTexture.height;
  60845. }
  60846. else {
  60847. target = this.inputTexture;
  60848. }
  60849. // Bind the input of this post process to be used as the output of the previous post process.
  60850. if (this.enablePixelPerfectMode) {
  60851. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  60852. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  60853. }
  60854. else {
  60855. this._scaleRatio.copyFromFloats(1, 1);
  60856. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  60857. }
  60858. this.onActivateObservable.notifyObservers(camera);
  60859. // Clear
  60860. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  60861. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  60862. }
  60863. if (this._reusable) {
  60864. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  60865. }
  60866. return target;
  60867. };
  60868. Object.defineProperty(PostProcess.prototype, "isSupported", {
  60869. /**
  60870. * If the post process is supported.
  60871. */
  60872. get: function () {
  60873. return this._effect.isSupported;
  60874. },
  60875. enumerable: true,
  60876. configurable: true
  60877. });
  60878. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  60879. /**
  60880. * The aspect ratio of the output texture.
  60881. */
  60882. get: function () {
  60883. if (this._shareOutputWithPostProcess) {
  60884. return this._shareOutputWithPostProcess.aspectRatio;
  60885. }
  60886. if (this._forcedOutputTexture) {
  60887. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  60888. }
  60889. return this.width / this.height;
  60890. },
  60891. enumerable: true,
  60892. configurable: true
  60893. });
  60894. /**
  60895. * Get a value indicating if the post-process is ready to be used
  60896. * @returns true if the post-process is ready (shader is compiled)
  60897. */
  60898. PostProcess.prototype.isReady = function () {
  60899. return this._effect && this._effect.isReady();
  60900. };
  60901. /**
  60902. * Binds all textures and uniforms to the shader, this will be run on every pass.
  60903. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  60904. */
  60905. PostProcess.prototype.apply = function () {
  60906. // Check
  60907. if (!this._effect || !this._effect.isReady())
  60908. return null;
  60909. // States
  60910. this._engine.enableEffect(this._effect);
  60911. this._engine.setState(false);
  60912. this._engine.setDepthBuffer(false);
  60913. this._engine.setDepthWrite(false);
  60914. // Alpha
  60915. this._engine.setAlphaMode(this.alphaMode);
  60916. if (this.alphaConstants) {
  60917. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  60918. }
  60919. // Bind the output texture of the preivous post process as the input to this post process.
  60920. var source;
  60921. if (this._shareOutputWithPostProcess) {
  60922. source = this._shareOutputWithPostProcess.inputTexture;
  60923. }
  60924. else if (this._forcedOutputTexture) {
  60925. source = this._forcedOutputTexture;
  60926. }
  60927. else {
  60928. source = this.inputTexture;
  60929. }
  60930. this._effect._bindTexture("textureSampler", source);
  60931. // Parameters
  60932. this._effect.setVector2("scale", this._scaleRatio);
  60933. this.onApplyObservable.notifyObservers(this._effect);
  60934. return this._effect;
  60935. };
  60936. PostProcess.prototype._disposeTextures = function () {
  60937. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  60938. return;
  60939. }
  60940. if (this._textures.length > 0) {
  60941. for (var i = 0; i < this._textures.length; i++) {
  60942. this._engine._releaseTexture(this._textures.data[i]);
  60943. }
  60944. }
  60945. this._textures.dispose();
  60946. };
  60947. /**
  60948. * Disposes the post process.
  60949. * @param camera The camera to dispose the post process on.
  60950. */
  60951. PostProcess.prototype.dispose = function (camera) {
  60952. camera = camera || this._camera;
  60953. this._disposeTextures();
  60954. if (this._scene) {
  60955. var index_1 = this._scene.postProcesses.indexOf(this);
  60956. if (index_1 !== -1) {
  60957. this._scene.postProcesses.splice(index_1, 1);
  60958. }
  60959. }
  60960. else {
  60961. var index_2 = this._engine.postProcesses.indexOf(this);
  60962. if (index_2 !== -1) {
  60963. this._engine.postProcesses.splice(index_2, 1);
  60964. }
  60965. }
  60966. if (!camera) {
  60967. return;
  60968. }
  60969. camera.detachPostProcess(this);
  60970. var index = camera._postProcesses.indexOf(this);
  60971. if (index === 0 && camera._postProcesses.length > 0) {
  60972. var firstPostProcess = this._camera._getFirstPostProcess();
  60973. if (firstPostProcess) {
  60974. firstPostProcess.markTextureDirty();
  60975. }
  60976. }
  60977. this.onActivateObservable.clear();
  60978. this.onAfterRenderObservable.clear();
  60979. this.onApplyObservable.clear();
  60980. this.onBeforeRenderObservable.clear();
  60981. this.onSizeChangedObservable.clear();
  60982. };
  60983. return PostProcess;
  60984. }());
  60985. BABYLON.PostProcess = PostProcess;
  60986. })(BABYLON || (BABYLON = {}));
  60987. //# sourceMappingURL=babylon.postProcess.js.map
  60988. "use strict";
  60989. var BABYLON;
  60990. (function (BABYLON) {
  60991. var PassPostProcess = /** @class */ (function (_super) {
  60992. __extends(PassPostProcess, _super);
  60993. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  60994. if (camera === void 0) { camera = null; }
  60995. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60996. if (blockCompilation === void 0) { blockCompilation = false; }
  60997. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  60998. }
  60999. return PassPostProcess;
  61000. }(BABYLON.PostProcess));
  61001. BABYLON.PassPostProcess = PassPostProcess;
  61002. })(BABYLON || (BABYLON = {}));
  61003. //# sourceMappingURL=babylon.passPostProcess.js.map
  61004. "use strict";
  61005. var __assign = (this && this.__assign) || Object.assign || function(t) {
  61006. for (var s, i = 1, n = arguments.length; i < n; i++) {
  61007. s = arguments[i];
  61008. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  61009. t[p] = s[p];
  61010. }
  61011. return t;
  61012. };
  61013. var BABYLON;
  61014. (function (BABYLON) {
  61015. /**
  61016. * Default implementation of @see IShadowGenerator.
  61017. * This is the main object responsible of generating shadows in the framework.
  61018. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  61019. */
  61020. var ShadowGenerator = /** @class */ (function () {
  61021. /**
  61022. * Creates a ShadowGenerator object.
  61023. * A ShadowGenerator is the required tool to use the shadows.
  61024. * Each light casting shadows needs to use its own ShadowGenerator.
  61025. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  61026. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  61027. * @param light The light object generating the shadows.
  61028. * @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.
  61029. */
  61030. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  61031. this._bias = 0.00005;
  61032. this._normalBias = 0;
  61033. this._blurBoxOffset = 1;
  61034. this._blurScale = 2;
  61035. this._blurKernel = 1;
  61036. this._useKernelBlur = false;
  61037. this._filter = ShadowGenerator.FILTER_NONE;
  61038. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  61039. this._contactHardeningLightSizeUVRatio = 0.1;
  61040. this._darkness = 0;
  61041. this._transparencyShadow = false;
  61042. /**
  61043. * Controls the extent to which the shadows fade out at the edge of the frustum
  61044. * Used only by directionals and spots
  61045. */
  61046. this.frustumEdgeFalloff = 0;
  61047. /**
  61048. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  61049. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  61050. * It might on the other hand introduce peter panning.
  61051. */
  61052. this.forceBackFacesOnly = false;
  61053. this._lightDirection = BABYLON.Vector3.Zero();
  61054. this._viewMatrix = BABYLON.Matrix.Zero();
  61055. this._projectionMatrix = BABYLON.Matrix.Zero();
  61056. this._transformMatrix = BABYLON.Matrix.Zero();
  61057. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  61058. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  61059. this._currentFaceIndex = 0;
  61060. this._currentFaceIndexCache = 0;
  61061. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  61062. this._mapSize = mapSize;
  61063. this._light = light;
  61064. this._scene = light.getScene();
  61065. light._shadowGenerator = this;
  61066. // Texture type fallback from float to int if not supported.
  61067. var caps = this._scene.getEngine().getCaps();
  61068. if (!useFullFloatFirst) {
  61069. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  61070. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  61071. }
  61072. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  61073. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  61074. }
  61075. else {
  61076. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  61077. }
  61078. }
  61079. else {
  61080. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  61081. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  61082. }
  61083. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  61084. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  61085. }
  61086. else {
  61087. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  61088. }
  61089. }
  61090. this._initializeGenerator();
  61091. this._applyFilterValues();
  61092. }
  61093. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  61094. /**
  61095. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  61096. */
  61097. get: function () {
  61098. return this._bias;
  61099. },
  61100. /**
  61101. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  61102. */
  61103. set: function (bias) {
  61104. this._bias = bias;
  61105. },
  61106. enumerable: true,
  61107. configurable: true
  61108. });
  61109. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  61110. /**
  61111. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  61112. */
  61113. get: function () {
  61114. return this._normalBias;
  61115. },
  61116. /**
  61117. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  61118. */
  61119. set: function (normalBias) {
  61120. this._normalBias = normalBias;
  61121. },
  61122. enumerable: true,
  61123. configurable: true
  61124. });
  61125. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  61126. /**
  61127. * Gets the blur box offset: offset applied during the blur pass.
  61128. * Only usefull if useKernelBlur = false
  61129. */
  61130. get: function () {
  61131. return this._blurBoxOffset;
  61132. },
  61133. /**
  61134. * Sets the blur box offset: offset applied during the blur pass.
  61135. * Only usefull if useKernelBlur = false
  61136. */
  61137. set: function (value) {
  61138. if (this._blurBoxOffset === value) {
  61139. return;
  61140. }
  61141. this._blurBoxOffset = value;
  61142. this._disposeBlurPostProcesses();
  61143. },
  61144. enumerable: true,
  61145. configurable: true
  61146. });
  61147. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  61148. /**
  61149. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  61150. * 2 means half of the size.
  61151. */
  61152. get: function () {
  61153. return this._blurScale;
  61154. },
  61155. /**
  61156. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  61157. * 2 means half of the size.
  61158. */
  61159. set: function (value) {
  61160. if (this._blurScale === value) {
  61161. return;
  61162. }
  61163. this._blurScale = value;
  61164. this._disposeBlurPostProcesses();
  61165. },
  61166. enumerable: true,
  61167. configurable: true
  61168. });
  61169. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  61170. /**
  61171. * Gets the blur kernel: kernel size of the blur pass.
  61172. * Only usefull if useKernelBlur = true
  61173. */
  61174. get: function () {
  61175. return this._blurKernel;
  61176. },
  61177. /**
  61178. * Sets the blur kernel: kernel size of the blur pass.
  61179. * Only usefull if useKernelBlur = true
  61180. */
  61181. set: function (value) {
  61182. if (this._blurKernel === value) {
  61183. return;
  61184. }
  61185. this._blurKernel = value;
  61186. this._disposeBlurPostProcesses();
  61187. },
  61188. enumerable: true,
  61189. configurable: true
  61190. });
  61191. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  61192. /**
  61193. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  61194. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  61195. */
  61196. get: function () {
  61197. return this._useKernelBlur;
  61198. },
  61199. /**
  61200. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  61201. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  61202. */
  61203. set: function (value) {
  61204. if (this._useKernelBlur === value) {
  61205. return;
  61206. }
  61207. this._useKernelBlur = value;
  61208. this._disposeBlurPostProcesses();
  61209. },
  61210. enumerable: true,
  61211. configurable: true
  61212. });
  61213. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  61214. /**
  61215. * Gets the depth scale used in ESM mode.
  61216. */
  61217. get: function () {
  61218. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  61219. },
  61220. /**
  61221. * Sets the depth scale used in ESM mode.
  61222. * This can override the scale stored on the light.
  61223. */
  61224. set: function (value) {
  61225. this._depthScale = value;
  61226. },
  61227. enumerable: true,
  61228. configurable: true
  61229. });
  61230. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  61231. /**
  61232. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  61233. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  61234. */
  61235. get: function () {
  61236. return this._filter;
  61237. },
  61238. /**
  61239. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  61240. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  61241. */
  61242. set: function (value) {
  61243. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  61244. if (this._light.needCube()) {
  61245. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  61246. this.useExponentialShadowMap = true;
  61247. return;
  61248. }
  61249. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  61250. this.useCloseExponentialShadowMap = true;
  61251. return;
  61252. }
  61253. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  61254. this.usePoissonSampling = true;
  61255. return;
  61256. }
  61257. }
  61258. // Weblg1 fallback for PCF.
  61259. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  61260. if (this._scene.getEngine().webGLVersion === 1) {
  61261. this.usePoissonSampling = true;
  61262. return;
  61263. }
  61264. }
  61265. if (this._filter === value) {
  61266. return;
  61267. }
  61268. this._filter = value;
  61269. this._disposeBlurPostProcesses();
  61270. this._applyFilterValues();
  61271. this._light._markMeshesAsLightDirty();
  61272. },
  61273. enumerable: true,
  61274. configurable: true
  61275. });
  61276. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  61277. /**
  61278. * Gets if the current filter is set to Poisson Sampling.
  61279. */
  61280. get: function () {
  61281. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  61282. },
  61283. /**
  61284. * Sets the current filter to Poisson Sampling.
  61285. */
  61286. set: function (value) {
  61287. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  61288. return;
  61289. }
  61290. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  61291. },
  61292. enumerable: true,
  61293. configurable: true
  61294. });
  61295. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  61296. /**
  61297. * Gets if the current filter is set to VSM.
  61298. * DEPRECATED. Should use useExponentialShadowMap instead.
  61299. */
  61300. get: function () {
  61301. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  61302. return this.useExponentialShadowMap;
  61303. },
  61304. /**
  61305. * Sets the current filter is to VSM.
  61306. * DEPRECATED. Should use useExponentialShadowMap instead.
  61307. */
  61308. set: function (value) {
  61309. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  61310. this.useExponentialShadowMap = value;
  61311. },
  61312. enumerable: true,
  61313. configurable: true
  61314. });
  61315. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  61316. /**
  61317. * Gets if the current filter is set to blurred VSM.
  61318. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  61319. */
  61320. get: function () {
  61321. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  61322. return this.useBlurExponentialShadowMap;
  61323. },
  61324. /**
  61325. * Sets the current filter is to blurred VSM.
  61326. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  61327. */
  61328. set: function (value) {
  61329. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  61330. this.useBlurExponentialShadowMap = value;
  61331. },
  61332. enumerable: true,
  61333. configurable: true
  61334. });
  61335. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  61336. /**
  61337. * Gets if the current filter is set to ESM.
  61338. */
  61339. get: function () {
  61340. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  61341. },
  61342. /**
  61343. * Sets the current filter is to ESM.
  61344. */
  61345. set: function (value) {
  61346. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  61347. return;
  61348. }
  61349. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  61350. },
  61351. enumerable: true,
  61352. configurable: true
  61353. });
  61354. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  61355. /**
  61356. * Gets if the current filter is set to filtered ESM.
  61357. */
  61358. get: function () {
  61359. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  61360. },
  61361. /**
  61362. * Gets if the current filter is set to filtered ESM.
  61363. */
  61364. set: function (value) {
  61365. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  61366. return;
  61367. }
  61368. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  61369. },
  61370. enumerable: true,
  61371. configurable: true
  61372. });
  61373. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  61374. /**
  61375. * Gets if the current filter is set to "close ESM" (using the inverse of the
  61376. * exponential to prevent steep falloff artifacts).
  61377. */
  61378. get: function () {
  61379. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  61380. },
  61381. /**
  61382. * Sets the current filter to "close ESM" (using the inverse of the
  61383. * exponential to prevent steep falloff artifacts).
  61384. */
  61385. set: function (value) {
  61386. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  61387. return;
  61388. }
  61389. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  61390. },
  61391. enumerable: true,
  61392. configurable: true
  61393. });
  61394. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  61395. /**
  61396. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  61397. * exponential to prevent steep falloff artifacts).
  61398. */
  61399. get: function () {
  61400. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  61401. },
  61402. /**
  61403. * Sets the current filter to filtered "close ESM" (using the inverse of the
  61404. * exponential to prevent steep falloff artifacts).
  61405. */
  61406. set: function (value) {
  61407. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  61408. return;
  61409. }
  61410. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  61411. },
  61412. enumerable: true,
  61413. configurable: true
  61414. });
  61415. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  61416. /**
  61417. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  61418. */
  61419. get: function () {
  61420. return this.filter === ShadowGenerator.FILTER_PCF;
  61421. },
  61422. /**
  61423. * Sets the current filter to "PCF" (percentage closer filtering).
  61424. */
  61425. set: function (value) {
  61426. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  61427. return;
  61428. }
  61429. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  61430. },
  61431. enumerable: true,
  61432. configurable: true
  61433. });
  61434. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  61435. /**
  61436. * Gets the PCF or PCSS Quality.
  61437. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  61438. */
  61439. get: function () {
  61440. return this._filteringQuality;
  61441. },
  61442. /**
  61443. * Sets the PCF or PCSS Quality.
  61444. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  61445. */
  61446. set: function (filteringQuality) {
  61447. this._filteringQuality = filteringQuality;
  61448. },
  61449. enumerable: true,
  61450. configurable: true
  61451. });
  61452. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  61453. /**
  61454. * Gets if the current filter is set to "PCSS" (contact hardening).
  61455. */
  61456. get: function () {
  61457. return this.filter === ShadowGenerator.FILTER_PCSS;
  61458. },
  61459. /**
  61460. * Sets the current filter to "PCSS" (contact hardening).
  61461. */
  61462. set: function (value) {
  61463. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  61464. return;
  61465. }
  61466. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  61467. },
  61468. enumerable: true,
  61469. configurable: true
  61470. });
  61471. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  61472. /**
  61473. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  61474. * Using a ratio helps keeping shape stability independently of the map size.
  61475. *
  61476. * It does not account for the light projection as it was having too much
  61477. * instability during the light setup or during light position changes.
  61478. *
  61479. * Only valid if useContactHardeningShadow is true.
  61480. */
  61481. get: function () {
  61482. return this._contactHardeningLightSizeUVRatio;
  61483. },
  61484. /**
  61485. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  61486. * Using a ratio helps keeping shape stability independently of the map size.
  61487. *
  61488. * It does not account for the light projection as it was having too much
  61489. * instability during the light setup or during light position changes.
  61490. *
  61491. * Only valid if useContactHardeningShadow is true.
  61492. */
  61493. set: function (contactHardeningLightSizeUVRatio) {
  61494. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  61495. },
  61496. enumerable: true,
  61497. configurable: true
  61498. });
  61499. /**
  61500. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  61501. * 0 means strongest and 1 would means no shadow.
  61502. * @returns the darkness.
  61503. */
  61504. ShadowGenerator.prototype.getDarkness = function () {
  61505. return this._darkness;
  61506. };
  61507. /**
  61508. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  61509. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  61510. * @returns the shadow generator allowing fluent coding.
  61511. */
  61512. ShadowGenerator.prototype.setDarkness = function (darkness) {
  61513. if (darkness >= 1.0)
  61514. this._darkness = 1.0;
  61515. else if (darkness <= 0.0)
  61516. this._darkness = 0.0;
  61517. else
  61518. this._darkness = darkness;
  61519. return this;
  61520. };
  61521. /**
  61522. * Sets the ability to have transparent shadow (boolean).
  61523. * @param transparent True if transparent else False
  61524. * @returns the shadow generator allowing fluent coding
  61525. */
  61526. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  61527. this._transparencyShadow = transparent;
  61528. return this;
  61529. };
  61530. /**
  61531. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  61532. * @returns The render target texture if present otherwise, null
  61533. */
  61534. ShadowGenerator.prototype.getShadowMap = function () {
  61535. return this._shadowMap;
  61536. };
  61537. /**
  61538. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  61539. * @returns The render target texture if the shadow map is present otherwise, null
  61540. */
  61541. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  61542. if (this._shadowMap2) {
  61543. return this._shadowMap2;
  61544. }
  61545. return this._shadowMap;
  61546. };
  61547. /**
  61548. * Helper function to add a mesh and its descendants to the list of shadow casters.
  61549. * @param mesh Mesh to add
  61550. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  61551. * @returns the Shadow Generator itself
  61552. */
  61553. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  61554. if (includeDescendants === void 0) { includeDescendants = true; }
  61555. if (!this._shadowMap) {
  61556. return this;
  61557. }
  61558. if (!this._shadowMap.renderList) {
  61559. this._shadowMap.renderList = [];
  61560. }
  61561. this._shadowMap.renderList.push(mesh);
  61562. if (includeDescendants) {
  61563. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  61564. }
  61565. return this;
  61566. var _a;
  61567. };
  61568. /**
  61569. * Helper function to remove a mesh and its descendants from the list of shadow casters
  61570. * @param mesh Mesh to remove
  61571. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  61572. * @returns the Shadow Generator itself
  61573. */
  61574. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  61575. if (includeDescendants === void 0) { includeDescendants = true; }
  61576. if (!this._shadowMap || !this._shadowMap.renderList) {
  61577. return this;
  61578. }
  61579. var index = this._shadowMap.renderList.indexOf(mesh);
  61580. if (index !== -1) {
  61581. this._shadowMap.renderList.splice(index, 1);
  61582. }
  61583. if (includeDescendants) {
  61584. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  61585. var child = _a[_i];
  61586. this.removeShadowCaster(child);
  61587. }
  61588. }
  61589. return this;
  61590. };
  61591. /**
  61592. * Returns the associated light object.
  61593. * @returns the light generating the shadow
  61594. */
  61595. ShadowGenerator.prototype.getLight = function () {
  61596. return this._light;
  61597. };
  61598. ShadowGenerator.prototype._initializeGenerator = function () {
  61599. this._light._markMeshesAsLightDirty();
  61600. this._initializeShadowMap();
  61601. };
  61602. ShadowGenerator.prototype._initializeShadowMap = function () {
  61603. var _this = this;
  61604. // Render target
  61605. var engine = this._scene.getEngine();
  61606. if (engine.webGLVersion > 1) {
  61607. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  61608. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  61609. }
  61610. else {
  61611. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  61612. }
  61613. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61614. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61615. this._shadowMap.anisotropicFilteringLevel = 1;
  61616. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  61617. this._shadowMap.renderParticles = false;
  61618. this._shadowMap.ignoreCameraViewport = true;
  61619. // Record Face Index before render.
  61620. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  61621. _this._currentFaceIndex = faceIndex;
  61622. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  61623. engine.setColorWrite(false);
  61624. }
  61625. });
  61626. // Custom render function.
  61627. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  61628. // Blur if required afer render.
  61629. this._shadowMap.onAfterUnbindObservable.add(function () {
  61630. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  61631. engine.setColorWrite(true);
  61632. }
  61633. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  61634. return;
  61635. }
  61636. var shadowMap = _this.getShadowMapForRendering();
  61637. if (shadowMap) {
  61638. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  61639. }
  61640. });
  61641. // Clear according to the chosen filter.
  61642. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  61643. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  61644. this._shadowMap.onClearObservable.add(function (engine) {
  61645. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  61646. engine.clear(clearOne, false, true, false);
  61647. }
  61648. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  61649. engine.clear(clearZero, true, true, false);
  61650. }
  61651. else {
  61652. engine.clear(clearOne, true, true, false);
  61653. }
  61654. });
  61655. };
  61656. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  61657. var _this = this;
  61658. var engine = this._scene.getEngine();
  61659. var targetSize = this._mapSize / this.blurScale;
  61660. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  61661. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  61662. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61663. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61664. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  61665. }
  61666. if (this.useKernelBlur) {
  61667. 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);
  61668. this._kernelBlurXPostprocess.width = targetSize;
  61669. this._kernelBlurXPostprocess.height = targetSize;
  61670. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  61671. effect.setTexture("textureSampler", _this._shadowMap);
  61672. });
  61673. 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);
  61674. this._kernelBlurXPostprocess.autoClear = false;
  61675. this._kernelBlurYPostprocess.autoClear = false;
  61676. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  61677. this._kernelBlurXPostprocess.packedFloat = true;
  61678. this._kernelBlurYPostprocess.packedFloat = true;
  61679. }
  61680. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  61681. }
  61682. else {
  61683. 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);
  61684. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  61685. effect.setFloat2("screenSize", targetSize, targetSize);
  61686. effect.setTexture("textureSampler", _this._shadowMap);
  61687. });
  61688. this._boxBlurPostprocess.autoClear = false;
  61689. this._blurPostProcesses = [this._boxBlurPostprocess];
  61690. }
  61691. };
  61692. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  61693. var index;
  61694. var engine = this._scene.getEngine();
  61695. if (depthOnlySubMeshes.length) {
  61696. engine.setColorWrite(false);
  61697. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  61698. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  61699. }
  61700. engine.setColorWrite(true);
  61701. }
  61702. for (index = 0; index < opaqueSubMeshes.length; index++) {
  61703. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  61704. }
  61705. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  61706. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  61707. }
  61708. if (this._transparencyShadow) {
  61709. for (index = 0; index < transparentSubMeshes.length; index++) {
  61710. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  61711. }
  61712. }
  61713. };
  61714. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  61715. var _this = this;
  61716. var mesh = subMesh.getRenderingMesh();
  61717. var scene = this._scene;
  61718. var engine = scene.getEngine();
  61719. var material = subMesh.getMaterial();
  61720. if (!material) {
  61721. return;
  61722. }
  61723. // Culling
  61724. engine.setState(material.backFaceCulling);
  61725. // Managing instances
  61726. var batch = mesh._getInstancesRenderList(subMesh._id);
  61727. if (batch.mustReturn) {
  61728. return;
  61729. }
  61730. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  61731. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  61732. engine.enableEffect(this._effect);
  61733. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  61734. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  61735. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  61736. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  61737. this._effect.setVector3("lightData", this._cachedDirection);
  61738. }
  61739. else {
  61740. this._effect.setVector3("lightData", this._cachedPosition);
  61741. }
  61742. if (scene.activeCamera) {
  61743. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  61744. }
  61745. // Alpha test
  61746. if (material && material.needAlphaTesting()) {
  61747. var alphaTexture = material.getAlphaTestTexture();
  61748. if (alphaTexture) {
  61749. this._effect.setTexture("diffuseSampler", alphaTexture);
  61750. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  61751. }
  61752. }
  61753. // Bones
  61754. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  61755. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  61756. }
  61757. // Morph targets
  61758. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  61759. if (this.forceBackFacesOnly) {
  61760. engine.setState(true, 0, false, true);
  61761. }
  61762. // Draw
  61763. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  61764. if (this.forceBackFacesOnly) {
  61765. engine.setState(true, 0, false, false);
  61766. }
  61767. }
  61768. else {
  61769. // Need to reset refresh rate of the shadowMap
  61770. if (this._shadowMap) {
  61771. this._shadowMap.resetRefreshCounter();
  61772. }
  61773. }
  61774. };
  61775. ShadowGenerator.prototype._applyFilterValues = function () {
  61776. if (!this._shadowMap) {
  61777. return;
  61778. }
  61779. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  61780. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  61781. }
  61782. else {
  61783. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  61784. }
  61785. };
  61786. /**
  61787. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  61788. * @param onCompiled Callback triggered at the and of the effects compilation
  61789. * @param options Sets of optional options forcing the compilation with different modes
  61790. */
  61791. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  61792. var _this = this;
  61793. var localOptions = __assign({ useInstances: false }, options);
  61794. var shadowMap = this.getShadowMap();
  61795. if (!shadowMap) {
  61796. if (onCompiled) {
  61797. onCompiled(this);
  61798. }
  61799. return;
  61800. }
  61801. var renderList = shadowMap.renderList;
  61802. if (!renderList) {
  61803. if (onCompiled) {
  61804. onCompiled(this);
  61805. }
  61806. return;
  61807. }
  61808. var subMeshes = new Array();
  61809. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  61810. var mesh = renderList_1[_i];
  61811. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  61812. }
  61813. if (subMeshes.length === 0) {
  61814. if (onCompiled) {
  61815. onCompiled(this);
  61816. }
  61817. return;
  61818. }
  61819. var currentIndex = 0;
  61820. var checkReady = function () {
  61821. if (!_this._scene || !_this._scene.getEngine()) {
  61822. return;
  61823. }
  61824. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  61825. currentIndex++;
  61826. if (currentIndex >= subMeshes.length) {
  61827. if (onCompiled) {
  61828. onCompiled(_this);
  61829. }
  61830. return;
  61831. }
  61832. }
  61833. setTimeout(checkReady, 16);
  61834. };
  61835. checkReady();
  61836. };
  61837. /**
  61838. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  61839. * @param options Sets of optional options forcing the compilation with different modes
  61840. * @returns A promise that resolves when the compilation completes
  61841. */
  61842. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  61843. var _this = this;
  61844. return new Promise(function (resolve) {
  61845. _this.forceCompilation(function () {
  61846. resolve();
  61847. }, options);
  61848. });
  61849. };
  61850. /**
  61851. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  61852. * @param subMesh The submesh we want to render in the shadow map
  61853. * @param useInstances Defines wether will draw in the map using instances
  61854. * @returns true if ready otherwise, false
  61855. */
  61856. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  61857. var defines = [];
  61858. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  61859. defines.push("#define FLOAT");
  61860. }
  61861. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  61862. defines.push("#define ESM");
  61863. }
  61864. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  61865. defines.push("#define DEPTHTEXTURE");
  61866. }
  61867. var attribs = [BABYLON.VertexBuffer.PositionKind];
  61868. var mesh = subMesh.getMesh();
  61869. var material = subMesh.getMaterial();
  61870. // Normal bias.
  61871. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  61872. attribs.push(BABYLON.VertexBuffer.NormalKind);
  61873. defines.push("#define NORMAL");
  61874. if (mesh.nonUniformScaling) {
  61875. defines.push("#define NONUNIFORMSCALING");
  61876. }
  61877. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  61878. defines.push("#define DIRECTIONINLIGHTDATA");
  61879. }
  61880. }
  61881. // Alpha test
  61882. if (material && material.needAlphaTesting()) {
  61883. var alphaTexture = material.getAlphaTestTexture();
  61884. if (alphaTexture) {
  61885. defines.push("#define ALPHATEST");
  61886. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  61887. attribs.push(BABYLON.VertexBuffer.UVKind);
  61888. defines.push("#define UV1");
  61889. }
  61890. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  61891. if (alphaTexture.coordinatesIndex === 1) {
  61892. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  61893. defines.push("#define UV2");
  61894. }
  61895. }
  61896. }
  61897. }
  61898. // Bones
  61899. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  61900. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  61901. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  61902. if (mesh.numBoneInfluencers > 4) {
  61903. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  61904. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  61905. }
  61906. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  61907. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  61908. }
  61909. else {
  61910. defines.push("#define NUM_BONE_INFLUENCERS 0");
  61911. }
  61912. // Morph targets
  61913. var manager = mesh.morphTargetManager;
  61914. var morphInfluencers = 0;
  61915. if (manager) {
  61916. if (manager.numInfluencers > 0) {
  61917. defines.push("#define MORPHTARGETS");
  61918. morphInfluencers = manager.numInfluencers;
  61919. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  61920. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  61921. }
  61922. }
  61923. // Instances
  61924. if (useInstances) {
  61925. defines.push("#define INSTANCES");
  61926. attribs.push("world0");
  61927. attribs.push("world1");
  61928. attribs.push("world2");
  61929. attribs.push("world3");
  61930. }
  61931. // Get correct effect
  61932. var join = defines.join("\n");
  61933. if (this._cachedDefines !== join) {
  61934. this._cachedDefines = join;
  61935. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  61936. }
  61937. if (!this._effect.isReady()) {
  61938. return false;
  61939. }
  61940. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  61941. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  61942. this._initializeBlurRTTAndPostProcesses();
  61943. }
  61944. }
  61945. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  61946. return false;
  61947. }
  61948. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  61949. return false;
  61950. }
  61951. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  61952. return false;
  61953. }
  61954. return true;
  61955. };
  61956. /**
  61957. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  61958. * @param defines Defines of the material we want to update
  61959. * @param lightIndex Index of the light in the enabled light list of the material
  61960. */
  61961. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  61962. var scene = this._scene;
  61963. var light = this._light;
  61964. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  61965. return;
  61966. }
  61967. defines["SHADOW" + lightIndex] = true;
  61968. if (this.useContactHardeningShadow) {
  61969. defines["SHADOWPCSS" + lightIndex] = true;
  61970. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  61971. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  61972. }
  61973. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  61974. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  61975. }
  61976. // else default to high.
  61977. }
  61978. if (this.usePercentageCloserFiltering) {
  61979. defines["SHADOWPCF" + lightIndex] = true;
  61980. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  61981. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  61982. }
  61983. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  61984. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  61985. }
  61986. // else default to high.
  61987. }
  61988. else if (this.usePoissonSampling) {
  61989. defines["SHADOWPOISSON" + lightIndex] = true;
  61990. }
  61991. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  61992. defines["SHADOWESM" + lightIndex] = true;
  61993. }
  61994. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  61995. defines["SHADOWCLOSEESM" + lightIndex] = true;
  61996. }
  61997. if (light.needCube()) {
  61998. defines["SHADOWCUBE" + lightIndex] = true;
  61999. }
  62000. };
  62001. /**
  62002. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  62003. * defined in the generator but impacting the effect).
  62004. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  62005. * @param effect The effect we are binfing the information for
  62006. */
  62007. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  62008. var light = this._light;
  62009. var scene = this._scene;
  62010. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  62011. return;
  62012. }
  62013. var camera = scene.activeCamera;
  62014. if (!camera) {
  62015. return;
  62016. }
  62017. var shadowMap = this.getShadowMap();
  62018. if (!shadowMap) {
  62019. return;
  62020. }
  62021. if (!light.needCube()) {
  62022. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  62023. }
  62024. // Only PCF uses depth stencil texture.
  62025. if (this._filter === ShadowGenerator.FILTER_PCF) {
  62026. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  62027. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  62028. }
  62029. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  62030. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  62031. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  62032. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  62033. }
  62034. else {
  62035. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  62036. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  62037. }
  62038. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  62039. };
  62040. /**
  62041. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  62042. * (eq to shadow prjection matrix * light transform matrix)
  62043. * @returns The transform matrix used to create the shadow map
  62044. */
  62045. ShadowGenerator.prototype.getTransformMatrix = function () {
  62046. var scene = this._scene;
  62047. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  62048. return this._transformMatrix;
  62049. }
  62050. this._currentRenderID = scene.getRenderId();
  62051. this._currentFaceIndexCache = this._currentFaceIndex;
  62052. var lightPosition = this._light.position;
  62053. if (this._light.computeTransformedInformation()) {
  62054. lightPosition = this._light.transformedPosition;
  62055. }
  62056. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  62057. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  62058. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  62059. }
  62060. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  62061. this._cachedPosition.copyFrom(lightPosition);
  62062. this._cachedDirection.copyFrom(this._lightDirection);
  62063. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  62064. var shadowMap = this.getShadowMap();
  62065. if (shadowMap) {
  62066. var renderList = shadowMap.renderList;
  62067. if (renderList) {
  62068. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  62069. }
  62070. }
  62071. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  62072. }
  62073. return this._transformMatrix;
  62074. };
  62075. /**
  62076. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  62077. * Cube and 2D textures for instance.
  62078. */
  62079. ShadowGenerator.prototype.recreateShadowMap = function () {
  62080. var shadowMap = this._shadowMap;
  62081. if (!shadowMap) {
  62082. return;
  62083. }
  62084. // Track render list.
  62085. var renderList = shadowMap.renderList;
  62086. // Clean up existing data.
  62087. this._disposeRTTandPostProcesses();
  62088. // Reinitializes.
  62089. this._initializeGenerator();
  62090. // Reaffect the filter to ensure a correct fallback if necessary.
  62091. this.filter = this.filter;
  62092. // Reaffect the filter.
  62093. this._applyFilterValues();
  62094. // Reaffect Render List.
  62095. this._shadowMap.renderList = renderList;
  62096. };
  62097. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  62098. if (this._shadowMap2) {
  62099. this._shadowMap2.dispose();
  62100. this._shadowMap2 = null;
  62101. }
  62102. if (this._boxBlurPostprocess) {
  62103. this._boxBlurPostprocess.dispose();
  62104. this._boxBlurPostprocess = null;
  62105. }
  62106. if (this._kernelBlurXPostprocess) {
  62107. this._kernelBlurXPostprocess.dispose();
  62108. this._kernelBlurXPostprocess = null;
  62109. }
  62110. if (this._kernelBlurYPostprocess) {
  62111. this._kernelBlurYPostprocess.dispose();
  62112. this._kernelBlurYPostprocess = null;
  62113. }
  62114. this._blurPostProcesses = [];
  62115. };
  62116. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  62117. if (this._shadowMap) {
  62118. this._shadowMap.dispose();
  62119. this._shadowMap = null;
  62120. }
  62121. this._disposeBlurPostProcesses();
  62122. };
  62123. /**
  62124. * Disposes the ShadowGenerator.
  62125. * Returns nothing.
  62126. */
  62127. ShadowGenerator.prototype.dispose = function () {
  62128. this._disposeRTTandPostProcesses();
  62129. if (this._light) {
  62130. this._light._shadowGenerator = null;
  62131. this._light._markMeshesAsLightDirty();
  62132. }
  62133. };
  62134. /**
  62135. * Serializes the shadow generator setup to a json object.
  62136. * @returns The serialized JSON object
  62137. */
  62138. ShadowGenerator.prototype.serialize = function () {
  62139. var serializationObject = {};
  62140. var shadowMap = this.getShadowMap();
  62141. if (!shadowMap) {
  62142. return serializationObject;
  62143. }
  62144. serializationObject.lightId = this._light.id;
  62145. serializationObject.mapSize = shadowMap.getRenderSize();
  62146. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  62147. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  62148. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  62149. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  62150. serializationObject.usePoissonSampling = this.usePoissonSampling;
  62151. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  62152. serializationObject.depthScale = this.depthScale;
  62153. serializationObject.darkness = this.getDarkness();
  62154. serializationObject.blurBoxOffset = this.blurBoxOffset;
  62155. serializationObject.blurKernel = this.blurKernel;
  62156. serializationObject.blurScale = this.blurScale;
  62157. serializationObject.useKernelBlur = this.useKernelBlur;
  62158. serializationObject.transparencyShadow = this._transparencyShadow;
  62159. serializationObject.bias = this.bias;
  62160. serializationObject.normalBias = this.normalBias;
  62161. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  62162. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  62163. serializationObject.filteringQuality = this.filteringQuality;
  62164. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  62165. serializationObject.renderList = [];
  62166. if (shadowMap.renderList) {
  62167. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  62168. var mesh = shadowMap.renderList[meshIndex];
  62169. serializationObject.renderList.push(mesh.id);
  62170. }
  62171. }
  62172. return serializationObject;
  62173. };
  62174. /**
  62175. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  62176. * @param parsedShadowGenerator The JSON object to parse
  62177. * @param scene The scene to create the shadow map for
  62178. * @returns The parsed shadow generator
  62179. */
  62180. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  62181. //casting to point light, as light is missing the position attr and typescript complains.
  62182. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  62183. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  62184. var shadowMap = shadowGenerator.getShadowMap();
  62185. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  62186. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  62187. meshes.forEach(function (mesh) {
  62188. if (!shadowMap) {
  62189. return;
  62190. }
  62191. if (!shadowMap.renderList) {
  62192. shadowMap.renderList = [];
  62193. }
  62194. shadowMap.renderList.push(mesh);
  62195. });
  62196. }
  62197. if (parsedShadowGenerator.usePoissonSampling) {
  62198. shadowGenerator.usePoissonSampling = true;
  62199. }
  62200. else if (parsedShadowGenerator.useExponentialShadowMap) {
  62201. shadowGenerator.useExponentialShadowMap = true;
  62202. }
  62203. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  62204. shadowGenerator.useBlurExponentialShadowMap = true;
  62205. }
  62206. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  62207. shadowGenerator.useCloseExponentialShadowMap = true;
  62208. }
  62209. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  62210. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  62211. }
  62212. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  62213. shadowGenerator.usePercentageCloserFiltering = true;
  62214. }
  62215. else if (parsedShadowGenerator.useContactHardeningShadow) {
  62216. shadowGenerator.useContactHardeningShadow = true;
  62217. }
  62218. if (parsedShadowGenerator.filteringQuality) {
  62219. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  62220. }
  62221. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  62222. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  62223. }
  62224. else if (parsedShadowGenerator.useVarianceShadowMap) {
  62225. shadowGenerator.useExponentialShadowMap = true;
  62226. }
  62227. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  62228. shadowGenerator.useBlurExponentialShadowMap = true;
  62229. }
  62230. if (parsedShadowGenerator.depthScale) {
  62231. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  62232. }
  62233. if (parsedShadowGenerator.blurScale) {
  62234. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  62235. }
  62236. if (parsedShadowGenerator.blurBoxOffset) {
  62237. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  62238. }
  62239. if (parsedShadowGenerator.useKernelBlur) {
  62240. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  62241. }
  62242. if (parsedShadowGenerator.blurKernel) {
  62243. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  62244. }
  62245. if (parsedShadowGenerator.bias !== undefined) {
  62246. shadowGenerator.bias = parsedShadowGenerator.bias;
  62247. }
  62248. if (parsedShadowGenerator.normalBias !== undefined) {
  62249. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  62250. }
  62251. if (parsedShadowGenerator.darkness) {
  62252. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  62253. }
  62254. if (parsedShadowGenerator.transparencyShadow) {
  62255. shadowGenerator.setTransparencyShadow(true);
  62256. }
  62257. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  62258. return shadowGenerator;
  62259. };
  62260. /**
  62261. * Shadow generator mode None: no filtering applied.
  62262. */
  62263. ShadowGenerator.FILTER_NONE = 0;
  62264. /**
  62265. * Shadow generator mode ESM: Exponential Shadow Mapping.
  62266. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  62267. */
  62268. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  62269. /**
  62270. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  62271. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  62272. */
  62273. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  62274. /**
  62275. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  62276. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  62277. */
  62278. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  62279. /**
  62280. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  62281. * edge artifacts on steep falloff.
  62282. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  62283. */
  62284. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  62285. /**
  62286. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  62287. * edge artifacts on steep falloff.
  62288. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  62289. */
  62290. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  62291. /**
  62292. * Shadow generator mode PCF: Percentage Closer Filtering
  62293. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  62294. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  62295. */
  62296. ShadowGenerator.FILTER_PCF = 6;
  62297. /**
  62298. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  62299. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  62300. * Contact Hardening
  62301. */
  62302. ShadowGenerator.FILTER_PCSS = 7;
  62303. /**
  62304. * Reserved for PCF and PCSS
  62305. * Highest Quality.
  62306. *
  62307. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  62308. *
  62309. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  62310. */
  62311. ShadowGenerator.QUALITY_HIGH = 0;
  62312. /**
  62313. * Reserved for PCF and PCSS
  62314. * Good tradeoff for quality/perf cross devices
  62315. *
  62316. * Execute PCF on a 3*3 kernel.
  62317. *
  62318. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  62319. */
  62320. ShadowGenerator.QUALITY_MEDIUM = 1;
  62321. /**
  62322. * Reserved for PCF and PCSS
  62323. * The lowest quality but the fastest.
  62324. *
  62325. * Execute PCF on a 1*1 kernel.
  62326. *
  62327. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  62328. */
  62329. ShadowGenerator.QUALITY_LOW = 2;
  62330. return ShadowGenerator;
  62331. }());
  62332. BABYLON.ShadowGenerator = ShadowGenerator;
  62333. })(BABYLON || (BABYLON = {}));
  62334. //# sourceMappingURL=babylon.shadowGenerator.js.map
  62335. "use strict";
  62336. var BABYLON;
  62337. (function (BABYLON) {
  62338. var DefaultLoadingScreen = /** @class */ (function () {
  62339. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  62340. if (_loadingText === void 0) { _loadingText = ""; }
  62341. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  62342. var _this = this;
  62343. this._renderingCanvas = _renderingCanvas;
  62344. this._loadingText = _loadingText;
  62345. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  62346. // Resize
  62347. this._resizeLoadingUI = function () {
  62348. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  62349. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  62350. if (!_this._loadingDiv) {
  62351. return;
  62352. }
  62353. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  62354. _this._loadingDiv.style.left = canvasRect.left + "px";
  62355. _this._loadingDiv.style.top = canvasRect.top + "px";
  62356. _this._loadingDiv.style.width = canvasRect.width + "px";
  62357. _this._loadingDiv.style.height = canvasRect.height + "px";
  62358. };
  62359. }
  62360. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  62361. if (this._loadingDiv) {
  62362. // Do not add a loading screen if there is already one
  62363. return;
  62364. }
  62365. this._loadingDiv = document.createElement("div");
  62366. this._loadingDiv.id = "babylonjsLoadingDiv";
  62367. this._loadingDiv.style.opacity = "0";
  62368. this._loadingDiv.style.transition = "opacity 1.5s ease";
  62369. this._loadingDiv.style.pointerEvents = "none";
  62370. // Loading text
  62371. this._loadingTextDiv = document.createElement("div");
  62372. this._loadingTextDiv.style.position = "absolute";
  62373. this._loadingTextDiv.style.left = "0";
  62374. this._loadingTextDiv.style.top = "50%";
  62375. this._loadingTextDiv.style.marginTop = "80px";
  62376. this._loadingTextDiv.style.width = "100%";
  62377. this._loadingTextDiv.style.height = "20px";
  62378. this._loadingTextDiv.style.fontFamily = "Arial";
  62379. this._loadingTextDiv.style.fontSize = "14px";
  62380. this._loadingTextDiv.style.color = "white";
  62381. this._loadingTextDiv.style.textAlign = "center";
  62382. this._loadingTextDiv.innerHTML = "Loading";
  62383. this._loadingDiv.appendChild(this._loadingTextDiv);
  62384. //set the predefined text
  62385. this._loadingTextDiv.innerHTML = this._loadingText;
  62386. // Generating keyframes
  62387. var style = document.createElement('style');
  62388. style.type = 'text/css';
  62389. 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 }";
  62390. style.innerHTML = keyFrames;
  62391. document.getElementsByTagName('head')[0].appendChild(style);
  62392. // Loading img
  62393. var imgBack = new Image();
  62394. 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";
  62395. imgBack.style.position = "absolute";
  62396. imgBack.style.left = "50%";
  62397. imgBack.style.top = "50%";
  62398. imgBack.style.marginLeft = "-60px";
  62399. imgBack.style.marginTop = "-60px";
  62400. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  62401. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  62402. imgBack.style.transformOrigin = "50% 50%";
  62403. imgBack.style.webkitTransformOrigin = "50% 50%";
  62404. this._loadingDiv.appendChild(imgBack);
  62405. this._resizeLoadingUI();
  62406. window.addEventListener("resize", this._resizeLoadingUI);
  62407. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  62408. document.body.appendChild(this._loadingDiv);
  62409. this._loadingDiv.style.opacity = "1";
  62410. };
  62411. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  62412. var _this = this;
  62413. if (!this._loadingDiv) {
  62414. return;
  62415. }
  62416. var onTransitionEnd = function () {
  62417. if (!_this._loadingDiv) {
  62418. return;
  62419. }
  62420. document.body.removeChild(_this._loadingDiv);
  62421. window.removeEventListener("resize", _this._resizeLoadingUI);
  62422. _this._loadingDiv = null;
  62423. };
  62424. this._loadingDiv.style.opacity = "0";
  62425. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  62426. };
  62427. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  62428. set: function (text) {
  62429. this._loadingText = text;
  62430. if (this._loadingTextDiv) {
  62431. this._loadingTextDiv.innerHTML = this._loadingText;
  62432. }
  62433. },
  62434. enumerable: true,
  62435. configurable: true
  62436. });
  62437. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  62438. get: function () {
  62439. return this._loadingDivBackgroundColor;
  62440. },
  62441. set: function (color) {
  62442. this._loadingDivBackgroundColor = color;
  62443. if (!this._loadingDiv) {
  62444. return;
  62445. }
  62446. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  62447. },
  62448. enumerable: true,
  62449. configurable: true
  62450. });
  62451. return DefaultLoadingScreen;
  62452. }());
  62453. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  62454. })(BABYLON || (BABYLON = {}));
  62455. //# sourceMappingURL=babylon.loadingScreen.js.map
  62456. "use strict";
  62457. var BABYLON;
  62458. (function (BABYLON) {
  62459. var SceneLoaderProgressEvent = /** @class */ (function () {
  62460. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  62461. this.lengthComputable = lengthComputable;
  62462. this.loaded = loaded;
  62463. this.total = total;
  62464. }
  62465. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  62466. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  62467. };
  62468. return SceneLoaderProgressEvent;
  62469. }());
  62470. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  62471. var SceneLoader = /** @class */ (function () {
  62472. function SceneLoader() {
  62473. }
  62474. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  62475. get: function () {
  62476. return 0;
  62477. },
  62478. enumerable: true,
  62479. configurable: true
  62480. });
  62481. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  62482. get: function () {
  62483. return 1;
  62484. },
  62485. enumerable: true,
  62486. configurable: true
  62487. });
  62488. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  62489. get: function () {
  62490. return 2;
  62491. },
  62492. enumerable: true,
  62493. configurable: true
  62494. });
  62495. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  62496. get: function () {
  62497. return 3;
  62498. },
  62499. enumerable: true,
  62500. configurable: true
  62501. });
  62502. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  62503. get: function () {
  62504. return SceneLoader._ForceFullSceneLoadingForIncremental;
  62505. },
  62506. set: function (value) {
  62507. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  62508. },
  62509. enumerable: true,
  62510. configurable: true
  62511. });
  62512. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  62513. get: function () {
  62514. return SceneLoader._ShowLoadingScreen;
  62515. },
  62516. set: function (value) {
  62517. SceneLoader._ShowLoadingScreen = value;
  62518. },
  62519. enumerable: true,
  62520. configurable: true
  62521. });
  62522. Object.defineProperty(SceneLoader, "loggingLevel", {
  62523. get: function () {
  62524. return SceneLoader._loggingLevel;
  62525. },
  62526. set: function (value) {
  62527. SceneLoader._loggingLevel = value;
  62528. },
  62529. enumerable: true,
  62530. configurable: true
  62531. });
  62532. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  62533. get: function () {
  62534. return SceneLoader._CleanBoneMatrixWeights;
  62535. },
  62536. set: function (value) {
  62537. SceneLoader._CleanBoneMatrixWeights = value;
  62538. },
  62539. enumerable: true,
  62540. configurable: true
  62541. });
  62542. SceneLoader._getDefaultPlugin = function () {
  62543. return SceneLoader._registeredPlugins[".babylon"];
  62544. };
  62545. SceneLoader._getPluginForExtension = function (extension) {
  62546. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  62547. if (registeredPlugin) {
  62548. return registeredPlugin;
  62549. }
  62550. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  62551. return SceneLoader._getDefaultPlugin();
  62552. };
  62553. SceneLoader._getPluginForDirectLoad = function (data) {
  62554. for (var extension in SceneLoader._registeredPlugins) {
  62555. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  62556. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  62557. return SceneLoader._registeredPlugins[extension];
  62558. }
  62559. }
  62560. return SceneLoader._getDefaultPlugin();
  62561. };
  62562. SceneLoader._getPluginForFilename = function (sceneFilename) {
  62563. if (sceneFilename.name) {
  62564. sceneFilename = sceneFilename.name;
  62565. }
  62566. var queryStringPosition = sceneFilename.indexOf("?");
  62567. if (queryStringPosition !== -1) {
  62568. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  62569. }
  62570. var dotPosition = sceneFilename.lastIndexOf(".");
  62571. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  62572. return SceneLoader._getPluginForExtension(extension);
  62573. };
  62574. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  62575. SceneLoader._getDirectLoad = function (sceneFilename) {
  62576. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  62577. return sceneFilename.substr(5);
  62578. }
  62579. return null;
  62580. };
  62581. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  62582. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  62583. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  62584. var plugin;
  62585. if (registeredPlugin.plugin.createPlugin) {
  62586. plugin = registeredPlugin.plugin.createPlugin();
  62587. }
  62588. else {
  62589. plugin = registeredPlugin.plugin;
  62590. }
  62591. var useArrayBuffer = registeredPlugin.isBinary;
  62592. var database;
  62593. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  62594. var dataCallback = function (data, responseURL) {
  62595. if (scene.isDisposed) {
  62596. onError("Scene has been disposed");
  62597. return;
  62598. }
  62599. scene.database = database;
  62600. onSuccess(plugin, data, responseURL);
  62601. };
  62602. var request = null;
  62603. var pluginDisposed = false;
  62604. var onDisposeObservable = plugin.onDisposeObservable;
  62605. if (onDisposeObservable) {
  62606. onDisposeObservable.add(function () {
  62607. pluginDisposed = true;
  62608. if (request) {
  62609. request.abort();
  62610. request = null;
  62611. }
  62612. onDispose();
  62613. });
  62614. }
  62615. var manifestChecked = function () {
  62616. if (pluginDisposed) {
  62617. return;
  62618. }
  62619. var url = rootUrl + sceneFilename;
  62620. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  62621. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  62622. } : undefined, database, useArrayBuffer, function (request, exception) {
  62623. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  62624. });
  62625. };
  62626. if (directLoad) {
  62627. dataCallback(directLoad);
  62628. return plugin;
  62629. }
  62630. if (rootUrl.indexOf("file:") === -1) {
  62631. if (scene.getEngine().enableOfflineSupport) {
  62632. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  62633. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  62634. }
  62635. else {
  62636. manifestChecked();
  62637. }
  62638. }
  62639. else {
  62640. var fileOrString = sceneFilename;
  62641. if (fileOrString.name) {
  62642. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  62643. }
  62644. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  62645. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  62646. }
  62647. else {
  62648. onError("Unable to find file named " + sceneFilename);
  62649. }
  62650. }
  62651. return plugin;
  62652. };
  62653. // Public functions
  62654. SceneLoader.GetPluginForExtension = function (extension) {
  62655. return SceneLoader._getPluginForExtension(extension).plugin;
  62656. };
  62657. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  62658. return !!SceneLoader._registeredPlugins[extension];
  62659. };
  62660. SceneLoader.RegisterPlugin = function (plugin) {
  62661. if (typeof plugin.extensions === "string") {
  62662. var extension = plugin.extensions;
  62663. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  62664. plugin: plugin,
  62665. isBinary: false
  62666. };
  62667. }
  62668. else {
  62669. var extensions = plugin.extensions;
  62670. Object.keys(extensions).forEach(function (extension) {
  62671. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  62672. plugin: plugin,
  62673. isBinary: extensions[extension].isBinary
  62674. };
  62675. });
  62676. }
  62677. };
  62678. /**
  62679. * Import meshes into a scene
  62680. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  62681. * @param rootUrl a string that defines the root url for scene and resources
  62682. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62683. * @param scene the instance of BABYLON.Scene to append to
  62684. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  62685. * @param onProgress a callback with a progress event for each file being loaded
  62686. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  62687. * @param pluginExtension the extension used to determine the plugin
  62688. * @returns The loaded plugin
  62689. */
  62690. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  62691. if (onSuccess === void 0) { onSuccess = null; }
  62692. if (onProgress === void 0) { onProgress = null; }
  62693. if (onError === void 0) { onError = null; }
  62694. if (pluginExtension === void 0) { pluginExtension = null; }
  62695. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  62696. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  62697. return null;
  62698. }
  62699. var loadingToken = {};
  62700. scene._addPendingData(loadingToken);
  62701. var disposeHandler = function () {
  62702. scene._removePendingData(loadingToken);
  62703. };
  62704. var errorHandler = function (message, exception) {
  62705. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  62706. if (onError) {
  62707. onError(scene, errorMessage, exception);
  62708. }
  62709. else {
  62710. BABYLON.Tools.Error(errorMessage);
  62711. // should the exception be thrown?
  62712. }
  62713. disposeHandler();
  62714. };
  62715. var progressHandler = onProgress ? function (event) {
  62716. try {
  62717. onProgress(event);
  62718. }
  62719. catch (e) {
  62720. errorHandler("Error in onProgress callback", e);
  62721. }
  62722. } : undefined;
  62723. var successHandler = function (meshes, particleSystems, skeletons) {
  62724. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  62725. if (onSuccess) {
  62726. try {
  62727. onSuccess(meshes, particleSystems, skeletons);
  62728. }
  62729. catch (e) {
  62730. errorHandler("Error in onSuccess callback", e);
  62731. }
  62732. }
  62733. scene._removePendingData(loadingToken);
  62734. };
  62735. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  62736. if (plugin.rewriteRootURL) {
  62737. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  62738. }
  62739. if (sceneFilename === "") {
  62740. if (sceneFilename === "") {
  62741. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  62742. }
  62743. }
  62744. if (plugin.importMesh) {
  62745. var syncedPlugin = plugin;
  62746. var meshes = new Array();
  62747. var particleSystems = new Array();
  62748. var skeletons = new Array();
  62749. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  62750. return;
  62751. }
  62752. scene.loadingPluginName = plugin.name;
  62753. successHandler(meshes, particleSystems, skeletons);
  62754. }
  62755. else {
  62756. var asyncedPlugin = plugin;
  62757. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  62758. scene.loadingPluginName = plugin.name;
  62759. successHandler(result.meshes, result.particleSystems, result.skeletons);
  62760. }).catch(function (error) {
  62761. errorHandler(error.message, error);
  62762. });
  62763. }
  62764. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  62765. };
  62766. /**
  62767. * Import meshes into a scene
  62768. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  62769. * @param rootUrl a string that defines the root url for scene and resources
  62770. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62771. * @param scene the instance of BABYLON.Scene to append to
  62772. * @param onProgress a callback with a progress event for each file being loaded
  62773. * @param pluginExtension the extension used to determine the plugin
  62774. * @returns The loaded list of imported meshes, particleSystems, and skeletons
  62775. */
  62776. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  62777. if (onProgress === void 0) { onProgress = null; }
  62778. if (pluginExtension === void 0) { pluginExtension = null; }
  62779. return new Promise(function (resolve, reject) {
  62780. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  62781. resolve({
  62782. meshes: meshes,
  62783. particleSystems: particleSystems,
  62784. skeletons: skeletons
  62785. });
  62786. }, onProgress, function (scene, message, exception) {
  62787. reject(exception || new Error(message));
  62788. });
  62789. });
  62790. };
  62791. /**
  62792. * Load a scene
  62793. * @param rootUrl a string that defines the root url for scene and resources
  62794. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62795. * @param engine is the instance of BABYLON.Engine to use to create the scene
  62796. * @param onSuccess a callback with the scene when import succeeds
  62797. * @param onProgress a callback with a progress event for each file being loaded
  62798. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  62799. * @param pluginExtension the extension used to determine the plugin
  62800. * @returns The loaded plugin
  62801. */
  62802. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  62803. if (onSuccess === void 0) { onSuccess = null; }
  62804. if (onProgress === void 0) { onProgress = null; }
  62805. if (onError === void 0) { onError = null; }
  62806. if (pluginExtension === void 0) { pluginExtension = null; }
  62807. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  62808. };
  62809. /**
  62810. * Load a scene
  62811. * @param rootUrl a string that defines the root url for scene and resources
  62812. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62813. * @param engine is the instance of BABYLON.Engine to use to create the scene
  62814. * @param onProgress a callback with a progress event for each file being loaded
  62815. * @param pluginExtension the extension used to determine the plugin
  62816. * @returns The loaded scene
  62817. */
  62818. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  62819. if (onProgress === void 0) { onProgress = null; }
  62820. if (pluginExtension === void 0) { pluginExtension = null; }
  62821. return new Promise(function (resolve, reject) {
  62822. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  62823. resolve(scene);
  62824. }, onProgress, function (scene, message, exception) {
  62825. reject(exception || new Error(message));
  62826. }, pluginExtension);
  62827. });
  62828. };
  62829. /**
  62830. * Append a scene
  62831. * @param rootUrl a string that defines the root url for scene and resources
  62832. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62833. * @param scene is the instance of BABYLON.Scene to append to
  62834. * @param onSuccess a callback with the scene when import succeeds
  62835. * @param onProgress a callback with a progress event for each file being loaded
  62836. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  62837. * @param pluginExtension the extension used to determine the plugin
  62838. * @returns The loaded plugin
  62839. */
  62840. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  62841. if (onSuccess === void 0) { onSuccess = null; }
  62842. if (onProgress === void 0) { onProgress = null; }
  62843. if (onError === void 0) { onError = null; }
  62844. if (pluginExtension === void 0) { pluginExtension = null; }
  62845. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  62846. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  62847. return null;
  62848. }
  62849. if (SceneLoader.ShowLoadingScreen) {
  62850. scene.getEngine().displayLoadingUI();
  62851. }
  62852. var loadingToken = {};
  62853. scene._addPendingData(loadingToken);
  62854. var disposeHandler = function () {
  62855. scene._removePendingData(loadingToken);
  62856. scene.getEngine().hideLoadingUI();
  62857. };
  62858. var errorHandler = function (message, exception) {
  62859. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  62860. if (onError) {
  62861. onError(scene, errorMessage, exception);
  62862. }
  62863. else {
  62864. BABYLON.Tools.Error(errorMessage);
  62865. // should the exception be thrown?
  62866. }
  62867. disposeHandler();
  62868. };
  62869. var progressHandler = onProgress ? function (event) {
  62870. try {
  62871. onProgress(event);
  62872. }
  62873. catch (e) {
  62874. errorHandler("Error in onProgress callback", e);
  62875. }
  62876. } : undefined;
  62877. var successHandler = function () {
  62878. if (onSuccess) {
  62879. try {
  62880. onSuccess(scene);
  62881. }
  62882. catch (e) {
  62883. errorHandler("Error in onSuccess callback", e);
  62884. }
  62885. }
  62886. scene._removePendingData(loadingToken);
  62887. };
  62888. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  62889. if (sceneFilename === "") {
  62890. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  62891. }
  62892. if (plugin.load) {
  62893. var syncedPlugin = plugin;
  62894. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  62895. return;
  62896. }
  62897. scene.loadingPluginName = plugin.name;
  62898. successHandler();
  62899. }
  62900. else {
  62901. var asyncedPlugin = plugin;
  62902. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  62903. scene.loadingPluginName = plugin.name;
  62904. successHandler();
  62905. }).catch(function (error) {
  62906. errorHandler(error.message, error);
  62907. });
  62908. }
  62909. if (SceneLoader.ShowLoadingScreen) {
  62910. scene.executeWhenReady(function () {
  62911. scene.getEngine().hideLoadingUI();
  62912. });
  62913. }
  62914. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  62915. };
  62916. /**
  62917. * Append a scene
  62918. * @param rootUrl a string that defines the root url for scene and resources
  62919. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62920. * @param scene is the instance of BABYLON.Scene to append to
  62921. * @param onProgress a callback with a progress event for each file being loaded
  62922. * @param pluginExtension the extension used to determine the plugin
  62923. * @returns The given scene
  62924. */
  62925. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  62926. if (onProgress === void 0) { onProgress = null; }
  62927. if (pluginExtension === void 0) { pluginExtension = null; }
  62928. return new Promise(function (resolve, reject) {
  62929. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  62930. resolve(scene);
  62931. }, onProgress, function (scene, message, exception) {
  62932. reject(exception || new Error(message));
  62933. }, pluginExtension);
  62934. });
  62935. };
  62936. /**
  62937. * Load a scene into an asset container
  62938. * @param rootUrl a string that defines the root url for scene and resources
  62939. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62940. * @param scene is the instance of BABYLON.Scene to append to
  62941. * @param onSuccess a callback with the scene when import succeeds
  62942. * @param onProgress a callback with a progress event for each file being loaded
  62943. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  62944. * @param pluginExtension the extension used to determine the plugin
  62945. * @returns The loaded plugin
  62946. */
  62947. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  62948. if (onSuccess === void 0) { onSuccess = null; }
  62949. if (onProgress === void 0) { onProgress = null; }
  62950. if (onError === void 0) { onError = null; }
  62951. if (pluginExtension === void 0) { pluginExtension = null; }
  62952. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  62953. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  62954. return null;
  62955. }
  62956. var loadingToken = {};
  62957. scene._addPendingData(loadingToken);
  62958. var disposeHandler = function () {
  62959. scene._removePendingData(loadingToken);
  62960. };
  62961. var errorHandler = function (message, exception) {
  62962. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  62963. if (onError) {
  62964. onError(scene, errorMessage, exception);
  62965. }
  62966. else {
  62967. BABYLON.Tools.Error(errorMessage);
  62968. // should the exception be thrown?
  62969. }
  62970. disposeHandler();
  62971. };
  62972. var progressHandler = onProgress ? function (event) {
  62973. try {
  62974. onProgress(event);
  62975. }
  62976. catch (e) {
  62977. errorHandler("Error in onProgress callback", e);
  62978. }
  62979. } : undefined;
  62980. var successHandler = function (assets) {
  62981. if (onSuccess) {
  62982. try {
  62983. onSuccess(assets);
  62984. }
  62985. catch (e) {
  62986. errorHandler("Error in onSuccess callback", e);
  62987. }
  62988. }
  62989. scene._removePendingData(loadingToken);
  62990. };
  62991. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  62992. if (plugin.loadAssetContainer) {
  62993. var syncedPlugin = plugin;
  62994. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  62995. if (!assetContainer) {
  62996. return;
  62997. }
  62998. scene.loadingPluginName = plugin.name;
  62999. successHandler(assetContainer);
  63000. }
  63001. else if (plugin.loadAssetContainerAsync) {
  63002. var asyncedPlugin = plugin;
  63003. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  63004. scene.loadingPluginName = plugin.name;
  63005. successHandler(assetContainer);
  63006. }).catch(function (error) {
  63007. errorHandler(error.message, error);
  63008. });
  63009. }
  63010. else {
  63011. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  63012. }
  63013. if (SceneLoader.ShowLoadingScreen) {
  63014. scene.executeWhenReady(function () {
  63015. scene.getEngine().hideLoadingUI();
  63016. });
  63017. }
  63018. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  63019. };
  63020. /**
  63021. * Load a scene into an asset container
  63022. * @param rootUrl a string that defines the root url for scene and resources
  63023. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  63024. * @param scene is the instance of BABYLON.Scene to append to
  63025. * @param onProgress a callback with a progress event for each file being loaded
  63026. * @param pluginExtension the extension used to determine the plugin
  63027. * @returns The loaded asset container
  63028. */
  63029. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  63030. if (onProgress === void 0) { onProgress = null; }
  63031. if (pluginExtension === void 0) { pluginExtension = null; }
  63032. return new Promise(function (resolve, reject) {
  63033. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  63034. resolve(assetContainer);
  63035. }, onProgress, function (scene, message, exception) {
  63036. reject(exception || new Error(message));
  63037. }, pluginExtension);
  63038. });
  63039. };
  63040. // Flags
  63041. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  63042. SceneLoader._ShowLoadingScreen = true;
  63043. SceneLoader._CleanBoneMatrixWeights = false;
  63044. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  63045. // Members
  63046. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  63047. SceneLoader._registeredPlugins = {};
  63048. return SceneLoader;
  63049. }());
  63050. BABYLON.SceneLoader = SceneLoader;
  63051. ;
  63052. })(BABYLON || (BABYLON = {}));
  63053. //# sourceMappingURL=babylon.sceneLoader.js.map
  63054. "use strict";
  63055. var BABYLON;
  63056. (function (BABYLON) {
  63057. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  63058. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  63059. var parsedMaterial = parsedData.materials[index];
  63060. if (parsedMaterial.id === id) {
  63061. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  63062. }
  63063. }
  63064. return null;
  63065. };
  63066. var isDescendantOf = function (mesh, names, hierarchyIds) {
  63067. for (var i in names) {
  63068. if (mesh.name === names[i]) {
  63069. hierarchyIds.push(mesh.id);
  63070. return true;
  63071. }
  63072. }
  63073. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  63074. hierarchyIds.push(mesh.id);
  63075. return true;
  63076. }
  63077. return false;
  63078. };
  63079. var logOperation = function (operation, producer) {
  63080. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  63081. };
  63082. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  63083. if (addToScene === void 0) { addToScene = false; }
  63084. var container = new BABYLON.AssetContainer(scene);
  63085. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  63086. // when SceneLoader.debugLogging = true (default), or exception encountered.
  63087. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  63088. // and avoid problems with multiple concurrent .babylon loads.
  63089. var log = "importScene has failed JSON parse";
  63090. try {
  63091. var parsedData = JSON.parse(data);
  63092. log = "";
  63093. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  63094. var index;
  63095. var cache;
  63096. // Lights
  63097. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  63098. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  63099. var parsedLight = parsedData.lights[index];
  63100. var light = BABYLON.Light.Parse(parsedLight, scene);
  63101. if (light) {
  63102. container.lights.push(light);
  63103. log += (index === 0 ? "\n\tLights:" : "");
  63104. log += "\n\t\t" + light.toString(fullDetails);
  63105. }
  63106. }
  63107. }
  63108. // Animations
  63109. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  63110. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  63111. var parsedAnimation = parsedData.animations[index];
  63112. var animation = BABYLON.Animation.Parse(parsedAnimation);
  63113. scene.animations.push(animation);
  63114. container.animations.push(animation);
  63115. log += (index === 0 ? "\n\tAnimations:" : "");
  63116. log += "\n\t\t" + animation.toString(fullDetails);
  63117. }
  63118. }
  63119. // Materials
  63120. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  63121. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  63122. var parsedMaterial = parsedData.materials[index];
  63123. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  63124. container.materials.push(mat);
  63125. log += (index === 0 ? "\n\tMaterials:" : "");
  63126. log += "\n\t\t" + mat.toString(fullDetails);
  63127. }
  63128. }
  63129. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  63130. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  63131. var parsedMultiMaterial = parsedData.multiMaterials[index];
  63132. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  63133. container.multiMaterials.push(mmat);
  63134. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  63135. log += "\n\t\t" + mmat.toString(fullDetails);
  63136. }
  63137. }
  63138. // Morph targets
  63139. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  63140. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  63141. var managerData = _a[_i];
  63142. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  63143. }
  63144. }
  63145. // Skeletons
  63146. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  63147. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  63148. var parsedSkeleton = parsedData.skeletons[index];
  63149. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  63150. container.skeletons.push(skeleton);
  63151. log += (index === 0 ? "\n\tSkeletons:" : "");
  63152. log += "\n\t\t" + skeleton.toString(fullDetails);
  63153. }
  63154. }
  63155. // Geometries
  63156. var geometries = parsedData.geometries;
  63157. if (geometries !== undefined && geometries !== null) {
  63158. var addedGeometry = new Array();
  63159. // Boxes
  63160. var boxes = geometries.boxes;
  63161. if (boxes !== undefined && boxes !== null) {
  63162. for (index = 0, cache = boxes.length; index < cache; index++) {
  63163. var parsedBox = boxes[index];
  63164. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  63165. }
  63166. }
  63167. // Spheres
  63168. var spheres = geometries.spheres;
  63169. if (spheres !== undefined && spheres !== null) {
  63170. for (index = 0, cache = spheres.length; index < cache; index++) {
  63171. var parsedSphere = spheres[index];
  63172. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  63173. }
  63174. }
  63175. // Cylinders
  63176. var cylinders = geometries.cylinders;
  63177. if (cylinders !== undefined && cylinders !== null) {
  63178. for (index = 0, cache = cylinders.length; index < cache; index++) {
  63179. var parsedCylinder = cylinders[index];
  63180. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  63181. }
  63182. }
  63183. // Toruses
  63184. var toruses = geometries.toruses;
  63185. if (toruses !== undefined && toruses !== null) {
  63186. for (index = 0, cache = toruses.length; index < cache; index++) {
  63187. var parsedTorus = toruses[index];
  63188. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  63189. }
  63190. }
  63191. // Grounds
  63192. var grounds = geometries.grounds;
  63193. if (grounds !== undefined && grounds !== null) {
  63194. for (index = 0, cache = grounds.length; index < cache; index++) {
  63195. var parsedGround = grounds[index];
  63196. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  63197. }
  63198. }
  63199. // Planes
  63200. var planes = geometries.planes;
  63201. if (planes !== undefined && planes !== null) {
  63202. for (index = 0, cache = planes.length; index < cache; index++) {
  63203. var parsedPlane = planes[index];
  63204. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  63205. }
  63206. }
  63207. // TorusKnots
  63208. var torusKnots = geometries.torusKnots;
  63209. if (torusKnots !== undefined && torusKnots !== null) {
  63210. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  63211. var parsedTorusKnot = torusKnots[index];
  63212. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  63213. }
  63214. }
  63215. // VertexData
  63216. var vertexData = geometries.vertexData;
  63217. if (vertexData !== undefined && vertexData !== null) {
  63218. for (index = 0, cache = vertexData.length; index < cache; index++) {
  63219. var parsedVertexData = vertexData[index];
  63220. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  63221. }
  63222. }
  63223. addedGeometry.forEach(function (g) {
  63224. if (g) {
  63225. container.geometries.push(g);
  63226. }
  63227. });
  63228. }
  63229. // Transform nodes
  63230. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  63231. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  63232. var parsedTransformNode = parsedData.transformNodes[index];
  63233. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  63234. container.transformNodes.push(node);
  63235. }
  63236. }
  63237. // Meshes
  63238. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  63239. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  63240. var parsedMesh = parsedData.meshes[index];
  63241. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  63242. container.meshes.push(mesh);
  63243. log += (index === 0 ? "\n\tMeshes:" : "");
  63244. log += "\n\t\t" + mesh.toString(fullDetails);
  63245. }
  63246. }
  63247. // Cameras
  63248. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  63249. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  63250. var parsedCamera = parsedData.cameras[index];
  63251. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  63252. container.cameras.push(camera);
  63253. log += (index === 0 ? "\n\tCameras:" : "");
  63254. log += "\n\t\t" + camera.toString(fullDetails);
  63255. }
  63256. }
  63257. // Browsing all the graph to connect the dots
  63258. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  63259. var camera = scene.cameras[index];
  63260. if (camera._waitingParentId) {
  63261. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  63262. camera._waitingParentId = null;
  63263. }
  63264. }
  63265. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  63266. var light_1 = scene.lights[index];
  63267. if (light_1 && light_1._waitingParentId) {
  63268. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  63269. light_1._waitingParentId = null;
  63270. }
  63271. }
  63272. // Sounds
  63273. // TODO: add sound
  63274. var loadedSounds = [];
  63275. var loadedSound;
  63276. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  63277. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  63278. var parsedSound = parsedData.sounds[index];
  63279. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  63280. if (!parsedSound.url)
  63281. parsedSound.url = parsedSound.name;
  63282. if (!loadedSounds[parsedSound.url]) {
  63283. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  63284. loadedSounds[parsedSound.url] = loadedSound;
  63285. container.sounds.push(loadedSound);
  63286. }
  63287. else {
  63288. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  63289. }
  63290. }
  63291. else {
  63292. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  63293. }
  63294. }
  63295. }
  63296. loadedSounds = [];
  63297. // Connect parents & children and parse actions
  63298. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  63299. var transformNode = scene.transformNodes[index];
  63300. if (transformNode._waitingParentId) {
  63301. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  63302. transformNode._waitingParentId = null;
  63303. }
  63304. }
  63305. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  63306. var mesh = scene.meshes[index];
  63307. if (mesh._waitingParentId) {
  63308. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  63309. mesh._waitingParentId = null;
  63310. }
  63311. if (mesh._waitingActions) {
  63312. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  63313. mesh._waitingActions = null;
  63314. }
  63315. }
  63316. // freeze world matrix application
  63317. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  63318. var currentMesh = scene.meshes[index];
  63319. if (currentMesh._waitingFreezeWorldMatrix) {
  63320. currentMesh.freezeWorldMatrix();
  63321. currentMesh._waitingFreezeWorldMatrix = null;
  63322. }
  63323. else {
  63324. currentMesh.computeWorldMatrix(true);
  63325. }
  63326. }
  63327. // Particles Systems
  63328. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  63329. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  63330. var parsedParticleSystem = parsedData.particleSystems[index];
  63331. if (parsedParticleSystem.activeParticleCount) {
  63332. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  63333. container.particleSystems.push(ps);
  63334. }
  63335. else {
  63336. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  63337. container.particleSystems.push(ps);
  63338. }
  63339. }
  63340. }
  63341. // Lens flares
  63342. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  63343. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  63344. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  63345. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  63346. container.lensFlareSystems.push(lf);
  63347. }
  63348. }
  63349. // Shadows
  63350. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  63351. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  63352. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  63353. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  63354. container.shadowGenerators.push(sg);
  63355. }
  63356. }
  63357. // Lights exclusions / inclusions
  63358. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  63359. var light_2 = scene.lights[index];
  63360. // Excluded check
  63361. if (light_2._excludedMeshesIds.length > 0) {
  63362. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  63363. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  63364. if (excludedMesh) {
  63365. light_2.excludedMeshes.push(excludedMesh);
  63366. }
  63367. }
  63368. light_2._excludedMeshesIds = [];
  63369. }
  63370. // Included check
  63371. if (light_2._includedOnlyMeshesIds.length > 0) {
  63372. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  63373. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  63374. if (includedOnlyMesh) {
  63375. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  63376. }
  63377. }
  63378. light_2._includedOnlyMeshesIds = [];
  63379. }
  63380. }
  63381. // Actions (scene)
  63382. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  63383. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  63384. }
  63385. if (!addToScene) {
  63386. container.removeAllFromScene();
  63387. }
  63388. }
  63389. catch (err) {
  63390. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  63391. if (onError) {
  63392. onError(msg, err);
  63393. }
  63394. else {
  63395. BABYLON.Tools.Log(msg);
  63396. throw err;
  63397. }
  63398. }
  63399. finally {
  63400. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  63401. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  63402. }
  63403. }
  63404. return container;
  63405. };
  63406. BABYLON.SceneLoader.RegisterPlugin({
  63407. name: "babylon.js",
  63408. extensions: ".babylon",
  63409. canDirectLoad: function (data) {
  63410. if (data.indexOf("babylon") !== -1) {
  63411. return true;
  63412. }
  63413. return false;
  63414. },
  63415. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  63416. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  63417. // when SceneLoader.debugLogging = true (default), or exception encountered.
  63418. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  63419. // and avoid problems with multiple concurrent .babylon loads.
  63420. var log = "importMesh has failed JSON parse";
  63421. try {
  63422. var parsedData = JSON.parse(data);
  63423. log = "";
  63424. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  63425. if (!meshesNames) {
  63426. meshesNames = null;
  63427. }
  63428. else if (!Array.isArray(meshesNames)) {
  63429. meshesNames = [meshesNames];
  63430. }
  63431. var hierarchyIds = new Array();
  63432. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  63433. var loadedSkeletonsIds = [];
  63434. var loadedMaterialsIds = [];
  63435. var index;
  63436. var cache;
  63437. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  63438. var parsedMesh = parsedData.meshes[index];
  63439. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  63440. if (meshesNames !== null) {
  63441. // Remove found mesh name from list.
  63442. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  63443. }
  63444. //Geometry?
  63445. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  63446. //does the file contain geometries?
  63447. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  63448. //find the correct geometry and add it to the scene
  63449. var found = false;
  63450. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  63451. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  63452. return;
  63453. }
  63454. else {
  63455. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  63456. if (parsedGeometryData.id === parsedMesh.geometryId) {
  63457. switch (geometryType) {
  63458. case "boxes":
  63459. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  63460. break;
  63461. case "spheres":
  63462. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  63463. break;
  63464. case "cylinders":
  63465. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  63466. break;
  63467. case "toruses":
  63468. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  63469. break;
  63470. case "grounds":
  63471. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  63472. break;
  63473. case "planes":
  63474. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  63475. break;
  63476. case "torusKnots":
  63477. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  63478. break;
  63479. case "vertexData":
  63480. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  63481. break;
  63482. }
  63483. found = true;
  63484. }
  63485. });
  63486. }
  63487. });
  63488. if (found === false) {
  63489. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  63490. }
  63491. }
  63492. }
  63493. // Material ?
  63494. if (parsedMesh.materialId) {
  63495. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  63496. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  63497. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  63498. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  63499. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  63500. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  63501. var subMatId = parsedMultiMaterial.materials[matIndex];
  63502. loadedMaterialsIds.push(subMatId);
  63503. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  63504. if (mat) {
  63505. log += "\n\tMaterial " + mat.toString(fullDetails);
  63506. }
  63507. }
  63508. loadedMaterialsIds.push(parsedMultiMaterial.id);
  63509. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  63510. if (mmat) {
  63511. materialFound = true;
  63512. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  63513. }
  63514. break;
  63515. }
  63516. }
  63517. }
  63518. if (materialFound === false) {
  63519. loadedMaterialsIds.push(parsedMesh.materialId);
  63520. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  63521. if (!mat) {
  63522. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  63523. }
  63524. else {
  63525. log += "\n\tMaterial " + mat.toString(fullDetails);
  63526. }
  63527. }
  63528. }
  63529. // Skeleton ?
  63530. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  63531. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  63532. if (skeletonAlreadyLoaded === false) {
  63533. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  63534. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  63535. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  63536. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  63537. skeletons.push(skeleton);
  63538. loadedSkeletonsIds.push(parsedSkeleton.id);
  63539. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  63540. }
  63541. }
  63542. }
  63543. }
  63544. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  63545. meshes.push(mesh);
  63546. log += "\n\tMesh " + mesh.toString(fullDetails);
  63547. }
  63548. }
  63549. // Connecting parents
  63550. var currentMesh;
  63551. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  63552. currentMesh = scene.meshes[index];
  63553. if (currentMesh._waitingParentId) {
  63554. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  63555. currentMesh._waitingParentId = null;
  63556. }
  63557. }
  63558. // freeze and compute world matrix application
  63559. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  63560. currentMesh = scene.meshes[index];
  63561. if (currentMesh._waitingFreezeWorldMatrix) {
  63562. currentMesh.freezeWorldMatrix();
  63563. currentMesh._waitingFreezeWorldMatrix = null;
  63564. }
  63565. else {
  63566. currentMesh.computeWorldMatrix(true);
  63567. }
  63568. }
  63569. }
  63570. // Particles
  63571. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  63572. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  63573. var parsedParticleSystem = parsedData.particleSystems[index];
  63574. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  63575. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  63576. }
  63577. }
  63578. }
  63579. return true;
  63580. }
  63581. catch (err) {
  63582. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  63583. if (onError) {
  63584. onError(msg, err);
  63585. }
  63586. else {
  63587. BABYLON.Tools.Log(msg);
  63588. throw err;
  63589. }
  63590. }
  63591. finally {
  63592. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  63593. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  63594. }
  63595. }
  63596. return false;
  63597. },
  63598. load: function (scene, data, rootUrl, onError) {
  63599. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  63600. // when SceneLoader.debugLogging = true (default), or exception encountered.
  63601. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  63602. // and avoid problems with multiple concurrent .babylon loads.
  63603. var log = "importScene has failed JSON parse";
  63604. try {
  63605. var parsedData = JSON.parse(data);
  63606. log = "";
  63607. // Scene
  63608. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  63609. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  63610. }
  63611. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  63612. scene.autoClear = parsedData.autoClear;
  63613. }
  63614. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  63615. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  63616. }
  63617. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  63618. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  63619. }
  63620. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  63621. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  63622. }
  63623. // Fog
  63624. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  63625. scene.fogMode = parsedData.fogMode;
  63626. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  63627. scene.fogStart = parsedData.fogStart;
  63628. scene.fogEnd = parsedData.fogEnd;
  63629. scene.fogDensity = parsedData.fogDensity;
  63630. log += "\tFog mode for scene: ";
  63631. switch (scene.fogMode) {
  63632. // getters not compiling, so using hardcoded
  63633. case 1:
  63634. log += "exp\n";
  63635. break;
  63636. case 2:
  63637. log += "exp2\n";
  63638. break;
  63639. case 3:
  63640. log += "linear\n";
  63641. break;
  63642. }
  63643. }
  63644. //Physics
  63645. if (parsedData.physicsEnabled) {
  63646. var physicsPlugin;
  63647. if (parsedData.physicsEngine === "cannon") {
  63648. physicsPlugin = new BABYLON.CannonJSPlugin();
  63649. }
  63650. else if (parsedData.physicsEngine === "oimo") {
  63651. physicsPlugin = new BABYLON.OimoJSPlugin();
  63652. }
  63653. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  63654. //else - default engine, which is currently oimo
  63655. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  63656. scene.enablePhysics(physicsGravity, physicsPlugin);
  63657. }
  63658. // Metadata
  63659. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  63660. scene.metadata = parsedData.metadata;
  63661. }
  63662. //collisions, if defined. otherwise, default is true
  63663. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  63664. scene.collisionsEnabled = parsedData.collisionsEnabled;
  63665. }
  63666. scene.workerCollisions = !!parsedData.workerCollisions;
  63667. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  63668. if (!container) {
  63669. return false;
  63670. }
  63671. if (parsedData.autoAnimate) {
  63672. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  63673. }
  63674. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  63675. scene.setActiveCameraByID(parsedData.activeCameraID);
  63676. }
  63677. // Environment texture
  63678. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  63679. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  63680. if (parsedData.createDefaultSkybox === true) {
  63681. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  63682. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  63683. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  63684. }
  63685. }
  63686. // Finish
  63687. return true;
  63688. }
  63689. catch (err) {
  63690. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  63691. if (onError) {
  63692. onError(msg, err);
  63693. }
  63694. else {
  63695. BABYLON.Tools.Log(msg);
  63696. throw err;
  63697. }
  63698. }
  63699. finally {
  63700. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  63701. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  63702. }
  63703. }
  63704. return false;
  63705. },
  63706. loadAssetContainer: function (scene, data, rootUrl, onError) {
  63707. var container = loadAssetContainer(scene, data, rootUrl, onError);
  63708. return container;
  63709. }
  63710. });
  63711. })(BABYLON || (BABYLON = {}));
  63712. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  63713. "use strict";
  63714. var BABYLON;
  63715. (function (BABYLON) {
  63716. var FilesInput = /** @class */ (function () {
  63717. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  63718. this.onProcessFileCallback = function () { return true; };
  63719. this._engine = engine;
  63720. this._currentScene = scene;
  63721. this._sceneLoadedCallback = sceneLoadedCallback;
  63722. this._progressCallback = progressCallback;
  63723. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  63724. this._textureLoadingCallback = textureLoadingCallback;
  63725. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  63726. this._onReloadCallback = onReloadCallback;
  63727. this._errorCallback = errorCallback;
  63728. }
  63729. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  63730. var _this = this;
  63731. if (elementToMonitor) {
  63732. this._elementToMonitor = elementToMonitor;
  63733. this._dragEnterHandler = function (e) { _this.drag(e); };
  63734. this._dragOverHandler = function (e) { _this.drag(e); };
  63735. this._dropHandler = function (e) { _this.drop(e); };
  63736. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  63737. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  63738. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  63739. }
  63740. };
  63741. FilesInput.prototype.dispose = function () {
  63742. if (!this._elementToMonitor) {
  63743. return;
  63744. }
  63745. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  63746. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  63747. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  63748. };
  63749. FilesInput.prototype.renderFunction = function () {
  63750. if (this._additionalRenderLoopLogicCallback) {
  63751. this._additionalRenderLoopLogicCallback();
  63752. }
  63753. if (this._currentScene) {
  63754. if (this._textureLoadingCallback) {
  63755. var remaining = this._currentScene.getWaitingItemsCount();
  63756. if (remaining > 0) {
  63757. this._textureLoadingCallback(remaining);
  63758. }
  63759. }
  63760. this._currentScene.render();
  63761. }
  63762. };
  63763. FilesInput.prototype.drag = function (e) {
  63764. e.stopPropagation();
  63765. e.preventDefault();
  63766. };
  63767. FilesInput.prototype.drop = function (eventDrop) {
  63768. eventDrop.stopPropagation();
  63769. eventDrop.preventDefault();
  63770. this.loadFiles(eventDrop);
  63771. };
  63772. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  63773. var _this = this;
  63774. var reader = folder.createReader();
  63775. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  63776. reader.readEntries(function (entries) {
  63777. remaining.count += entries.length;
  63778. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  63779. var entry = entries_1[_i];
  63780. if (entry.isFile) {
  63781. entry.file(function (file) {
  63782. file.correctName = relativePath + file.name;
  63783. files.push(file);
  63784. if (--remaining.count === 0) {
  63785. callback();
  63786. }
  63787. });
  63788. }
  63789. else if (entry.isDirectory) {
  63790. _this._traverseFolder(entry, files, remaining, callback);
  63791. }
  63792. }
  63793. if (--remaining.count) {
  63794. callback();
  63795. }
  63796. });
  63797. };
  63798. FilesInput.prototype._processFiles = function (files) {
  63799. for (var i = 0; i < files.length; i++) {
  63800. var name = files[i].correctName.toLowerCase();
  63801. var extension = name.split('.').pop();
  63802. if (!this.onProcessFileCallback(files[i], name, extension)) {
  63803. continue;
  63804. }
  63805. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  63806. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  63807. this._sceneFileToLoad = files[i];
  63808. }
  63809. else {
  63810. FilesInput.FilesToLoad[name] = files[i];
  63811. }
  63812. }
  63813. };
  63814. FilesInput.prototype.loadFiles = function (event) {
  63815. var _this = this;
  63816. if (this._startingProcessingFilesCallback)
  63817. this._startingProcessingFilesCallback();
  63818. // Handling data transfer via drag'n'drop
  63819. if (event && event.dataTransfer && event.dataTransfer.files) {
  63820. this._filesToLoad = event.dataTransfer.files;
  63821. }
  63822. // Handling files from input files
  63823. if (event && event.target && event.target.files) {
  63824. this._filesToLoad = event.target.files;
  63825. }
  63826. if (this._filesToLoad && this._filesToLoad.length > 0) {
  63827. var files_1 = new Array();
  63828. var folders = [];
  63829. var items = event.dataTransfer ? event.dataTransfer.items : null;
  63830. for (var i = 0; i < this._filesToLoad.length; i++) {
  63831. var fileToLoad = this._filesToLoad[i];
  63832. var name_1 = fileToLoad.name.toLowerCase();
  63833. var entry = void 0;
  63834. fileToLoad.correctName = name_1;
  63835. if (items) {
  63836. var item = items[i];
  63837. if (item.getAsEntry) {
  63838. entry = item.getAsEntry();
  63839. }
  63840. else if (item.webkitGetAsEntry) {
  63841. entry = item.webkitGetAsEntry();
  63842. }
  63843. }
  63844. if (!entry) {
  63845. files_1.push(fileToLoad);
  63846. }
  63847. else {
  63848. if (entry.isDirectory) {
  63849. folders.push(entry);
  63850. }
  63851. else {
  63852. files_1.push(fileToLoad);
  63853. }
  63854. }
  63855. }
  63856. if (folders.length === 0) {
  63857. this._processFiles(files_1);
  63858. this._processReload();
  63859. }
  63860. else {
  63861. var remaining = { count: folders.length };
  63862. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  63863. var folder = folders_1[_i];
  63864. this._traverseFolder(folder, files_1, remaining, function () {
  63865. _this._processFiles(files_1);
  63866. if (remaining.count === 0) {
  63867. _this._processReload();
  63868. }
  63869. });
  63870. }
  63871. }
  63872. }
  63873. };
  63874. FilesInput.prototype._processReload = function () {
  63875. if (this._onReloadCallback) {
  63876. this._onReloadCallback(this._sceneFileToLoad);
  63877. }
  63878. else {
  63879. this.reload();
  63880. }
  63881. };
  63882. FilesInput.prototype.reload = function () {
  63883. var _this = this;
  63884. // If a scene file has been provided
  63885. if (this._sceneFileToLoad) {
  63886. if (this._currentScene) {
  63887. if (BABYLON.Tools.errorsCount > 0) {
  63888. BABYLON.Tools.ClearLogCache();
  63889. }
  63890. this._engine.stopRenderLoop();
  63891. this._currentScene.dispose();
  63892. }
  63893. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  63894. if (_this._progressCallback) {
  63895. _this._progressCallback(progress);
  63896. }
  63897. }).then(function (scene) {
  63898. _this._currentScene = scene;
  63899. if (_this._sceneLoadedCallback) {
  63900. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  63901. }
  63902. // Wait for textures and shaders to be ready
  63903. _this._currentScene.executeWhenReady(function () {
  63904. _this._engine.runRenderLoop(function () {
  63905. _this.renderFunction();
  63906. });
  63907. });
  63908. }).catch(function (error) {
  63909. if (_this._errorCallback) {
  63910. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  63911. }
  63912. });
  63913. }
  63914. else {
  63915. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  63916. }
  63917. };
  63918. FilesInput.FilesToLoad = {};
  63919. return FilesInput;
  63920. }());
  63921. BABYLON.FilesInput = FilesInput;
  63922. })(BABYLON || (BABYLON = {}));
  63923. //# sourceMappingURL=babylon.filesInput.js.map
  63924. "use strict";
  63925. var BABYLON;
  63926. (function (BABYLON) {
  63927. /**
  63928. * This class implement a typical dictionary using a string as key and the generic type T as value.
  63929. * The underlying implementation relies on an associative array to ensure the best performances.
  63930. * The value can be anything including 'null' but except 'undefined'
  63931. */
  63932. var StringDictionary = /** @class */ (function () {
  63933. function StringDictionary() {
  63934. this._count = 0;
  63935. this._data = {};
  63936. }
  63937. /**
  63938. * This will clear this dictionary and copy the content from the 'source' one.
  63939. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  63940. * @param source the dictionary to take the content from and copy to this dictionary
  63941. */
  63942. StringDictionary.prototype.copyFrom = function (source) {
  63943. var _this = this;
  63944. this.clear();
  63945. source.forEach(function (t, v) { return _this.add(t, v); });
  63946. };
  63947. /**
  63948. * Get a value based from its key
  63949. * @param key the given key to get the matching value from
  63950. * @return the value if found, otherwise undefined is returned
  63951. */
  63952. StringDictionary.prototype.get = function (key) {
  63953. var val = this._data[key];
  63954. if (val !== undefined) {
  63955. return val;
  63956. }
  63957. return undefined;
  63958. };
  63959. /**
  63960. * Get a value from its key or add it if it doesn't exist.
  63961. * This method will ensure you that a given key/data will be present in the dictionary.
  63962. * @param key the given key to get the matching value from
  63963. * @param factory the factory that will create the value if the key is not present in the dictionary.
  63964. * The factory will only be invoked if there's no data for the given key.
  63965. * @return the value corresponding to the key.
  63966. */
  63967. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  63968. var val = this.get(key);
  63969. if (val !== undefined) {
  63970. return val;
  63971. }
  63972. val = factory(key);
  63973. if (val) {
  63974. this.add(key, val);
  63975. }
  63976. return val;
  63977. };
  63978. /**
  63979. * Get a value from its key if present in the dictionary otherwise add it
  63980. * @param key the key to get the value from
  63981. * @param val if there's no such key/value pair in the dictionary add it with this value
  63982. * @return the value corresponding to the key
  63983. */
  63984. StringDictionary.prototype.getOrAdd = function (key, val) {
  63985. var curVal = this.get(key);
  63986. if (curVal !== undefined) {
  63987. return curVal;
  63988. }
  63989. this.add(key, val);
  63990. return val;
  63991. };
  63992. /**
  63993. * Check if there's a given key in the dictionary
  63994. * @param key the key to check for
  63995. * @return true if the key is present, false otherwise
  63996. */
  63997. StringDictionary.prototype.contains = function (key) {
  63998. return this._data[key] !== undefined;
  63999. };
  64000. /**
  64001. * Add a new key and its corresponding value
  64002. * @param key the key to add
  64003. * @param value the value corresponding to the key
  64004. * @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
  64005. */
  64006. StringDictionary.prototype.add = function (key, value) {
  64007. if (this._data[key] !== undefined) {
  64008. return false;
  64009. }
  64010. this._data[key] = value;
  64011. ++this._count;
  64012. return true;
  64013. };
  64014. StringDictionary.prototype.set = function (key, value) {
  64015. if (this._data[key] === undefined) {
  64016. return false;
  64017. }
  64018. this._data[key] = value;
  64019. return true;
  64020. };
  64021. /**
  64022. * Get the element of the given key and remove it from the dictionary
  64023. * @param key
  64024. */
  64025. StringDictionary.prototype.getAndRemove = function (key) {
  64026. var val = this.get(key);
  64027. if (val !== undefined) {
  64028. delete this._data[key];
  64029. --this._count;
  64030. return val;
  64031. }
  64032. return null;
  64033. };
  64034. /**
  64035. * Remove a key/value from the dictionary.
  64036. * @param key the key to remove
  64037. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  64038. */
  64039. StringDictionary.prototype.remove = function (key) {
  64040. if (this.contains(key)) {
  64041. delete this._data[key];
  64042. --this._count;
  64043. return true;
  64044. }
  64045. return false;
  64046. };
  64047. /**
  64048. * Clear the whole content of the dictionary
  64049. */
  64050. StringDictionary.prototype.clear = function () {
  64051. this._data = {};
  64052. this._count = 0;
  64053. };
  64054. Object.defineProperty(StringDictionary.prototype, "count", {
  64055. get: function () {
  64056. return this._count;
  64057. },
  64058. enumerable: true,
  64059. configurable: true
  64060. });
  64061. /**
  64062. * Execute a callback on each key/val of the dictionary.
  64063. * Note that you can remove any element in this dictionary in the callback implementation
  64064. * @param callback the callback to execute on a given key/value pair
  64065. */
  64066. StringDictionary.prototype.forEach = function (callback) {
  64067. for (var cur in this._data) {
  64068. var val = this._data[cur];
  64069. callback(cur, val);
  64070. }
  64071. };
  64072. /**
  64073. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  64074. * If the callback returns null or undefined the method will iterate to the next key/value pair
  64075. * Note that you can remove any element in this dictionary in the callback implementation
  64076. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  64077. */
  64078. StringDictionary.prototype.first = function (callback) {
  64079. for (var cur in this._data) {
  64080. var val = this._data[cur];
  64081. var res = callback(cur, val);
  64082. if (res) {
  64083. return res;
  64084. }
  64085. }
  64086. return null;
  64087. };
  64088. return StringDictionary;
  64089. }());
  64090. BABYLON.StringDictionary = StringDictionary;
  64091. })(BABYLON || (BABYLON = {}));
  64092. //# sourceMappingURL=babylon.stringDictionary.js.map
  64093. "use strict";
  64094. var BABYLON;
  64095. (function (BABYLON) {
  64096. var Tags = /** @class */ (function () {
  64097. function Tags() {
  64098. }
  64099. Tags.EnableFor = function (obj) {
  64100. obj._tags = obj._tags || {};
  64101. obj.hasTags = function () {
  64102. return Tags.HasTags(obj);
  64103. };
  64104. obj.addTags = function (tagsString) {
  64105. return Tags.AddTagsTo(obj, tagsString);
  64106. };
  64107. obj.removeTags = function (tagsString) {
  64108. return Tags.RemoveTagsFrom(obj, tagsString);
  64109. };
  64110. obj.matchesTagsQuery = function (tagsQuery) {
  64111. return Tags.MatchesQuery(obj, tagsQuery);
  64112. };
  64113. };
  64114. Tags.DisableFor = function (obj) {
  64115. delete obj._tags;
  64116. delete obj.hasTags;
  64117. delete obj.addTags;
  64118. delete obj.removeTags;
  64119. delete obj.matchesTagsQuery;
  64120. };
  64121. Tags.HasTags = function (obj) {
  64122. if (!obj._tags) {
  64123. return false;
  64124. }
  64125. return !BABYLON.Tools.IsEmpty(obj._tags);
  64126. };
  64127. Tags.GetTags = function (obj, asString) {
  64128. if (asString === void 0) { asString = true; }
  64129. if (!obj._tags) {
  64130. return null;
  64131. }
  64132. if (asString) {
  64133. var tagsArray = [];
  64134. for (var tag in obj._tags) {
  64135. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  64136. tagsArray.push(tag);
  64137. }
  64138. }
  64139. return tagsArray.join(" ");
  64140. }
  64141. else {
  64142. return obj._tags;
  64143. }
  64144. };
  64145. // the tags 'true' and 'false' are reserved and cannot be used as tags
  64146. // a tag cannot start with '||', '&&', and '!'
  64147. // it cannot contain whitespaces
  64148. Tags.AddTagsTo = function (obj, tagsString) {
  64149. if (!tagsString) {
  64150. return;
  64151. }
  64152. if (typeof tagsString !== "string") {
  64153. return;
  64154. }
  64155. var tags = tagsString.split(" ");
  64156. tags.forEach(function (tag, index, array) {
  64157. Tags._AddTagTo(obj, tag);
  64158. });
  64159. };
  64160. Tags._AddTagTo = function (obj, tag) {
  64161. tag = tag.trim();
  64162. if (tag === "" || tag === "true" || tag === "false") {
  64163. return;
  64164. }
  64165. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  64166. return;
  64167. }
  64168. Tags.EnableFor(obj);
  64169. obj._tags[tag] = true;
  64170. };
  64171. Tags.RemoveTagsFrom = function (obj, tagsString) {
  64172. if (!Tags.HasTags(obj)) {
  64173. return;
  64174. }
  64175. var tags = tagsString.split(" ");
  64176. for (var t in tags) {
  64177. Tags._RemoveTagFrom(obj, tags[t]);
  64178. }
  64179. };
  64180. Tags._RemoveTagFrom = function (obj, tag) {
  64181. delete obj._tags[tag];
  64182. };
  64183. Tags.MatchesQuery = function (obj, tagsQuery) {
  64184. if (tagsQuery === undefined) {
  64185. return true;
  64186. }
  64187. if (tagsQuery === "") {
  64188. return Tags.HasTags(obj);
  64189. }
  64190. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  64191. };
  64192. return Tags;
  64193. }());
  64194. BABYLON.Tags = Tags;
  64195. })(BABYLON || (BABYLON = {}));
  64196. //# sourceMappingURL=babylon.tags.js.map
  64197. "use strict";
  64198. var BABYLON;
  64199. (function (BABYLON) {
  64200. var AndOrNotEvaluator = /** @class */ (function () {
  64201. function AndOrNotEvaluator() {
  64202. }
  64203. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  64204. if (!query.match(/\([^\(\)]*\)/g)) {
  64205. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  64206. }
  64207. else {
  64208. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  64209. // remove parenthesis
  64210. r = r.slice(1, r.length - 1);
  64211. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  64212. });
  64213. }
  64214. if (query === "true") {
  64215. return true;
  64216. }
  64217. if (query === "false") {
  64218. return false;
  64219. }
  64220. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  64221. };
  64222. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  64223. evaluateCallback = evaluateCallback || (function (r) {
  64224. return r === "true" ? true : false;
  64225. });
  64226. var result;
  64227. var or = parenthesisContent.split("||");
  64228. for (var i in or) {
  64229. if (or.hasOwnProperty(i)) {
  64230. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  64231. var and = ori.split("&&");
  64232. if (and.length > 1) {
  64233. for (var j = 0; j < and.length; ++j) {
  64234. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  64235. if (andj !== "true" && andj !== "false") {
  64236. if (andj[0] === "!") {
  64237. result = !evaluateCallback(andj.substring(1));
  64238. }
  64239. else {
  64240. result = evaluateCallback(andj);
  64241. }
  64242. }
  64243. else {
  64244. result = andj === "true" ? true : false;
  64245. }
  64246. if (!result) {
  64247. ori = "false";
  64248. break;
  64249. }
  64250. }
  64251. }
  64252. if (result || ori === "true") {
  64253. result = true;
  64254. break;
  64255. }
  64256. // result equals false (or undefined)
  64257. if (ori !== "true" && ori !== "false") {
  64258. if (ori[0] === "!") {
  64259. result = !evaluateCallback(ori.substring(1));
  64260. }
  64261. else {
  64262. result = evaluateCallback(ori);
  64263. }
  64264. }
  64265. else {
  64266. result = ori === "true" ? true : false;
  64267. }
  64268. }
  64269. }
  64270. // the whole parenthesis scope is replaced by 'true' or 'false'
  64271. return result ? "true" : "false";
  64272. };
  64273. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  64274. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  64275. // remove whitespaces
  64276. r = r.replace(/[\s]/g, function () { return ""; });
  64277. return r.length % 2 ? "!" : "";
  64278. });
  64279. booleanString = booleanString.trim();
  64280. if (booleanString === "!true") {
  64281. booleanString = "false";
  64282. }
  64283. else if (booleanString === "!false") {
  64284. booleanString = "true";
  64285. }
  64286. return booleanString;
  64287. };
  64288. return AndOrNotEvaluator;
  64289. }());
  64290. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  64291. })(BABYLON || (BABYLON = {}));
  64292. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  64293. "use strict";
  64294. var BABYLON;
  64295. (function (BABYLON) {
  64296. var Database = /** @class */ (function () {
  64297. function Database(urlToScene, callbackManifestChecked) {
  64298. // Handling various flavors of prefixed version of IndexedDB
  64299. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  64300. this.callbackManifestChecked = callbackManifestChecked;
  64301. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  64302. this.db = null;
  64303. this._enableSceneOffline = false;
  64304. this._enableTexturesOffline = false;
  64305. this.manifestVersionFound = 0;
  64306. this.mustUpdateRessources = false;
  64307. this.hasReachedQuota = false;
  64308. if (!Database.IDBStorageEnabled) {
  64309. this.callbackManifestChecked(true);
  64310. }
  64311. else {
  64312. this.checkManifestFile();
  64313. }
  64314. }
  64315. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  64316. get: function () {
  64317. return this._enableSceneOffline;
  64318. },
  64319. enumerable: true,
  64320. configurable: true
  64321. });
  64322. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  64323. get: function () {
  64324. return this._enableTexturesOffline;
  64325. },
  64326. enumerable: true,
  64327. configurable: true
  64328. });
  64329. Database.prototype.checkManifestFile = function () {
  64330. var _this = this;
  64331. var noManifestFile = function () {
  64332. _this._enableSceneOffline = false;
  64333. _this._enableTexturesOffline = false;
  64334. _this.callbackManifestChecked(false);
  64335. };
  64336. var timeStampUsed = false;
  64337. var manifestURL = this.currentSceneUrl + ".manifest";
  64338. var xhr = new XMLHttpRequest();
  64339. if (navigator.onLine) {
  64340. // Adding a timestamp to by-pass browsers' cache
  64341. timeStampUsed = true;
  64342. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  64343. }
  64344. xhr.open("GET", manifestURL, true);
  64345. xhr.addEventListener("load", function () {
  64346. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  64347. try {
  64348. var manifestFile = JSON.parse(xhr.response);
  64349. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  64350. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  64351. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  64352. _this.manifestVersionFound = manifestFile.version;
  64353. }
  64354. if (_this.callbackManifestChecked) {
  64355. _this.callbackManifestChecked(true);
  64356. }
  64357. }
  64358. catch (ex) {
  64359. noManifestFile();
  64360. }
  64361. }
  64362. else {
  64363. noManifestFile();
  64364. }
  64365. }, false);
  64366. xhr.addEventListener("error", function (event) {
  64367. if (timeStampUsed) {
  64368. timeStampUsed = false;
  64369. // Let's retry without the timeStamp
  64370. // It could fail when coupled with HTML5 Offline API
  64371. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  64372. xhr.open("GET", retryManifestURL, true);
  64373. xhr.send();
  64374. }
  64375. else {
  64376. noManifestFile();
  64377. }
  64378. }, false);
  64379. try {
  64380. xhr.send();
  64381. }
  64382. catch (ex) {
  64383. BABYLON.Tools.Error("Error on XHR send request.");
  64384. this.callbackManifestChecked(false);
  64385. }
  64386. };
  64387. Database.prototype.openAsync = function (successCallback, errorCallback) {
  64388. var _this = this;
  64389. var handleError = function () {
  64390. _this.isSupported = false;
  64391. if (errorCallback)
  64392. errorCallback();
  64393. };
  64394. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  64395. // Your browser doesn't support IndexedDB
  64396. this.isSupported = false;
  64397. if (errorCallback)
  64398. errorCallback();
  64399. }
  64400. else {
  64401. // If the DB hasn't been opened or created yet
  64402. if (!this.db) {
  64403. this.hasReachedQuota = false;
  64404. this.isSupported = true;
  64405. var request = this.idbFactory.open("babylonjs", 1);
  64406. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  64407. request.onerror = function (event) {
  64408. handleError();
  64409. };
  64410. // executes when a version change transaction cannot complete due to other active transactions
  64411. request.onblocked = function (event) {
  64412. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  64413. handleError();
  64414. };
  64415. // DB has been opened successfully
  64416. request.onsuccess = function (event) {
  64417. _this.db = request.result;
  64418. successCallback();
  64419. };
  64420. // Initialization of the DB. Creating Scenes & Textures stores
  64421. request.onupgradeneeded = function (event) {
  64422. _this.db = (event.target).result;
  64423. if (_this.db) {
  64424. try {
  64425. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  64426. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  64427. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  64428. }
  64429. catch (ex) {
  64430. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  64431. handleError();
  64432. }
  64433. }
  64434. };
  64435. }
  64436. else {
  64437. if (successCallback)
  64438. successCallback();
  64439. }
  64440. }
  64441. };
  64442. Database.prototype.loadImageFromDB = function (url, image) {
  64443. var _this = this;
  64444. var completeURL = Database.ReturnFullUrlLocation(url);
  64445. var saveAndLoadImage = function () {
  64446. if (!_this.hasReachedQuota && _this.db !== null) {
  64447. // the texture is not yet in the DB, let's try to save it
  64448. _this._saveImageIntoDBAsync(completeURL, image);
  64449. }
  64450. else {
  64451. image.src = url;
  64452. }
  64453. };
  64454. if (!this.mustUpdateRessources) {
  64455. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  64456. }
  64457. else {
  64458. saveAndLoadImage();
  64459. }
  64460. };
  64461. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  64462. if (this.isSupported && this.db !== null) {
  64463. var texture;
  64464. var transaction = this.db.transaction(["textures"]);
  64465. transaction.onabort = function (event) {
  64466. image.src = url;
  64467. };
  64468. transaction.oncomplete = function (event) {
  64469. var blobTextureURL;
  64470. if (texture) {
  64471. var URL = window.URL || window.webkitURL;
  64472. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  64473. image.onerror = function () {
  64474. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  64475. image.src = url;
  64476. };
  64477. image.src = blobTextureURL;
  64478. }
  64479. else {
  64480. notInDBCallback();
  64481. }
  64482. };
  64483. var getRequest = transaction.objectStore("textures").get(url);
  64484. getRequest.onsuccess = function (event) {
  64485. texture = (event.target).result;
  64486. };
  64487. getRequest.onerror = function (event) {
  64488. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  64489. image.src = url;
  64490. };
  64491. }
  64492. else {
  64493. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  64494. image.src = url;
  64495. }
  64496. };
  64497. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  64498. var _this = this;
  64499. if (this.isSupported) {
  64500. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  64501. var generateBlobUrl = function () {
  64502. var blobTextureURL;
  64503. if (blob) {
  64504. var URL = window.URL || window.webkitURL;
  64505. try {
  64506. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  64507. }
  64508. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  64509. catch (ex) {
  64510. blobTextureURL = URL.createObjectURL(blob);
  64511. }
  64512. }
  64513. if (blobTextureURL) {
  64514. image.src = blobTextureURL;
  64515. }
  64516. };
  64517. if (Database.IsUASupportingBlobStorage) {
  64518. var xhr = new XMLHttpRequest(), blob;
  64519. xhr.open("GET", url, true);
  64520. xhr.responseType = "blob";
  64521. xhr.addEventListener("load", function () {
  64522. if (xhr.status === 200 && _this.db) {
  64523. // Blob as response (XHR2)
  64524. blob = xhr.response;
  64525. var transaction = _this.db.transaction(["textures"], "readwrite");
  64526. // the transaction could abort because of a QuotaExceededError error
  64527. transaction.onabort = function (event) {
  64528. try {
  64529. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  64530. var srcElement = (event.srcElement || event.target);
  64531. var error = srcElement.error;
  64532. if (error && error.name === "QuotaExceededError") {
  64533. _this.hasReachedQuota = true;
  64534. }
  64535. }
  64536. catch (ex) { }
  64537. generateBlobUrl();
  64538. };
  64539. transaction.oncomplete = function (event) {
  64540. generateBlobUrl();
  64541. };
  64542. var newTexture = { textureUrl: url, data: blob };
  64543. try {
  64544. // Put the blob into the dabase
  64545. var addRequest = transaction.objectStore("textures").put(newTexture);
  64546. addRequest.onsuccess = function (event) {
  64547. };
  64548. addRequest.onerror = function (event) {
  64549. generateBlobUrl();
  64550. };
  64551. }
  64552. catch (ex) {
  64553. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  64554. if (ex.code === 25) {
  64555. Database.IsUASupportingBlobStorage = false;
  64556. }
  64557. image.src = url;
  64558. }
  64559. }
  64560. else {
  64561. image.src = url;
  64562. }
  64563. }, false);
  64564. xhr.addEventListener("error", function (event) {
  64565. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  64566. image.src = url;
  64567. }, false);
  64568. xhr.send();
  64569. }
  64570. else {
  64571. image.src = url;
  64572. }
  64573. }
  64574. else {
  64575. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  64576. image.src = url;
  64577. }
  64578. };
  64579. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  64580. var _this = this;
  64581. var updateVersion = function () {
  64582. // the version is not yet in the DB or we need to update it
  64583. _this._saveVersionIntoDBAsync(url, versionLoaded);
  64584. };
  64585. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  64586. };
  64587. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  64588. var _this = this;
  64589. if (this.isSupported && this.db) {
  64590. var version;
  64591. try {
  64592. var transaction = this.db.transaction(["versions"]);
  64593. transaction.oncomplete = function (event) {
  64594. if (version) {
  64595. // If the version in the JSON file is > than the version in DB
  64596. if (_this.manifestVersionFound > version.data) {
  64597. _this.mustUpdateRessources = true;
  64598. updateInDBCallback();
  64599. }
  64600. else {
  64601. callback(version.data);
  64602. }
  64603. }
  64604. else {
  64605. _this.mustUpdateRessources = true;
  64606. updateInDBCallback();
  64607. }
  64608. };
  64609. transaction.onabort = function (event) {
  64610. callback(-1);
  64611. };
  64612. var getRequest = transaction.objectStore("versions").get(url);
  64613. getRequest.onsuccess = function (event) {
  64614. version = (event.target).result;
  64615. };
  64616. getRequest.onerror = function (event) {
  64617. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  64618. callback(-1);
  64619. };
  64620. }
  64621. catch (ex) {
  64622. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  64623. callback(-1);
  64624. }
  64625. }
  64626. else {
  64627. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  64628. callback(-1);
  64629. }
  64630. };
  64631. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  64632. var _this = this;
  64633. if (this.isSupported && !this.hasReachedQuota && this.db) {
  64634. try {
  64635. // Open a transaction to the database
  64636. var transaction = this.db.transaction(["versions"], "readwrite");
  64637. // the transaction could abort because of a QuotaExceededError error
  64638. transaction.onabort = function (event) {
  64639. try {
  64640. var error = event.srcElement['error'];
  64641. if (error && error.name === "QuotaExceededError") {
  64642. _this.hasReachedQuota = true;
  64643. }
  64644. }
  64645. catch (ex) { }
  64646. callback(-1);
  64647. };
  64648. transaction.oncomplete = function (event) {
  64649. callback(_this.manifestVersionFound);
  64650. };
  64651. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  64652. // Put the scene into the database
  64653. var addRequest = transaction.objectStore("versions").put(newVersion);
  64654. addRequest.onsuccess = function (event) {
  64655. };
  64656. addRequest.onerror = function (event) {
  64657. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  64658. };
  64659. }
  64660. catch (ex) {
  64661. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  64662. callback(-1);
  64663. }
  64664. }
  64665. else {
  64666. callback(-1);
  64667. }
  64668. };
  64669. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  64670. var _this = this;
  64671. var completeUrl = Database.ReturnFullUrlLocation(url);
  64672. var saveAndLoadFile = function () {
  64673. // the scene is not yet in the DB, let's try to save it
  64674. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  64675. };
  64676. this._checkVersionFromDB(completeUrl, function (version) {
  64677. if (version !== -1) {
  64678. if (!_this.mustUpdateRessources) {
  64679. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  64680. }
  64681. else {
  64682. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  64683. }
  64684. }
  64685. else {
  64686. if (errorCallback) {
  64687. errorCallback();
  64688. }
  64689. }
  64690. });
  64691. };
  64692. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  64693. if (this.isSupported && this.db) {
  64694. var targetStore;
  64695. if (url.indexOf(".babylon") !== -1) {
  64696. targetStore = "scenes";
  64697. }
  64698. else {
  64699. targetStore = "textures";
  64700. }
  64701. var file;
  64702. var transaction = this.db.transaction([targetStore]);
  64703. transaction.oncomplete = function (event) {
  64704. if (file) {
  64705. callback(file.data);
  64706. }
  64707. else {
  64708. notInDBCallback();
  64709. }
  64710. };
  64711. transaction.onabort = function (event) {
  64712. notInDBCallback();
  64713. };
  64714. var getRequest = transaction.objectStore(targetStore).get(url);
  64715. getRequest.onsuccess = function (event) {
  64716. file = (event.target).result;
  64717. };
  64718. getRequest.onerror = function (event) {
  64719. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  64720. notInDBCallback();
  64721. };
  64722. }
  64723. else {
  64724. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  64725. callback();
  64726. }
  64727. };
  64728. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  64729. var _this = this;
  64730. if (this.isSupported) {
  64731. var targetStore;
  64732. if (url.indexOf(".babylon") !== -1) {
  64733. targetStore = "scenes";
  64734. }
  64735. else {
  64736. targetStore = "textures";
  64737. }
  64738. // Create XHR
  64739. var xhr = new XMLHttpRequest();
  64740. var fileData;
  64741. xhr.open("GET", url, true);
  64742. if (useArrayBuffer) {
  64743. xhr.responseType = "arraybuffer";
  64744. }
  64745. if (progressCallback) {
  64746. xhr.onprogress = progressCallback;
  64747. }
  64748. xhr.addEventListener("load", function () {
  64749. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  64750. // Blob as response (XHR2)
  64751. //fileData = xhr.responseText;
  64752. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  64753. if (!_this.hasReachedQuota && _this.db) {
  64754. // Open a transaction to the database
  64755. var transaction = _this.db.transaction([targetStore], "readwrite");
  64756. // the transaction could abort because of a QuotaExceededError error
  64757. transaction.onabort = function (event) {
  64758. try {
  64759. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  64760. var error = event.srcElement['error'];
  64761. if (error && error.name === "QuotaExceededError") {
  64762. _this.hasReachedQuota = true;
  64763. }
  64764. }
  64765. catch (ex) { }
  64766. callback(fileData);
  64767. };
  64768. transaction.oncomplete = function (event) {
  64769. callback(fileData);
  64770. };
  64771. var newFile;
  64772. if (targetStore === "scenes") {
  64773. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  64774. }
  64775. else {
  64776. newFile = { textureUrl: url, data: fileData };
  64777. }
  64778. try {
  64779. // Put the scene into the database
  64780. var addRequest = transaction.objectStore(targetStore).put(newFile);
  64781. addRequest.onsuccess = function (event) {
  64782. };
  64783. addRequest.onerror = function (event) {
  64784. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  64785. };
  64786. }
  64787. catch (ex) {
  64788. callback(fileData);
  64789. }
  64790. }
  64791. else {
  64792. callback(fileData);
  64793. }
  64794. }
  64795. else {
  64796. callback();
  64797. }
  64798. }, false);
  64799. xhr.addEventListener("error", function (event) {
  64800. BABYLON.Tools.Error("error on XHR request.");
  64801. callback();
  64802. }, false);
  64803. xhr.send();
  64804. }
  64805. else {
  64806. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  64807. callback();
  64808. }
  64809. };
  64810. Database.IsUASupportingBlobStorage = true;
  64811. Database.IDBStorageEnabled = true;
  64812. Database.parseURL = function (url) {
  64813. var a = document.createElement('a');
  64814. a.href = url;
  64815. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  64816. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  64817. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  64818. return absLocation;
  64819. };
  64820. Database.ReturnFullUrlLocation = function (url) {
  64821. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  64822. return (Database.parseURL(window.location.href) + url);
  64823. }
  64824. else {
  64825. return url;
  64826. }
  64827. };
  64828. return Database;
  64829. }());
  64830. BABYLON.Database = Database;
  64831. })(BABYLON || (BABYLON = {}));
  64832. //# sourceMappingURL=babylon.database.js.map
  64833. "use strict";
  64834. var BABYLON;
  64835. (function (BABYLON) {
  64836. var FresnelParameters = /** @class */ (function () {
  64837. function FresnelParameters() {
  64838. this._isEnabled = true;
  64839. this.leftColor = BABYLON.Color3.White();
  64840. this.rightColor = BABYLON.Color3.Black();
  64841. this.bias = 0;
  64842. this.power = 1;
  64843. }
  64844. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  64845. get: function () {
  64846. return this._isEnabled;
  64847. },
  64848. set: function (value) {
  64849. if (this._isEnabled === value) {
  64850. return;
  64851. }
  64852. this._isEnabled = value;
  64853. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  64854. },
  64855. enumerable: true,
  64856. configurable: true
  64857. });
  64858. FresnelParameters.prototype.clone = function () {
  64859. var newFresnelParameters = new FresnelParameters();
  64860. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  64861. return newFresnelParameters;
  64862. };
  64863. FresnelParameters.prototype.serialize = function () {
  64864. var serializationObject = {};
  64865. serializationObject.isEnabled = this.isEnabled;
  64866. serializationObject.leftColor = this.leftColor;
  64867. serializationObject.rightColor = this.rightColor;
  64868. serializationObject.bias = this.bias;
  64869. serializationObject.power = this.power;
  64870. return serializationObject;
  64871. };
  64872. FresnelParameters.Parse = function (parsedFresnelParameters) {
  64873. var fresnelParameters = new FresnelParameters();
  64874. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  64875. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  64876. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  64877. fresnelParameters.bias = parsedFresnelParameters.bias;
  64878. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  64879. return fresnelParameters;
  64880. };
  64881. return FresnelParameters;
  64882. }());
  64883. BABYLON.FresnelParameters = FresnelParameters;
  64884. })(BABYLON || (BABYLON = {}));
  64885. //# sourceMappingURL=babylon.fresnelParameters.js.map
  64886. "use strict";
  64887. var BABYLON;
  64888. (function (BABYLON) {
  64889. var MultiMaterial = /** @class */ (function (_super) {
  64890. __extends(MultiMaterial, _super);
  64891. function MultiMaterial(name, scene) {
  64892. var _this = _super.call(this, name, scene, true) || this;
  64893. scene.multiMaterials.push(_this);
  64894. _this.subMaterials = new Array();
  64895. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  64896. return _this;
  64897. }
  64898. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  64899. get: function () {
  64900. return this._subMaterials;
  64901. },
  64902. set: function (value) {
  64903. this._subMaterials = value;
  64904. this._hookArray(value);
  64905. },
  64906. enumerable: true,
  64907. configurable: true
  64908. });
  64909. MultiMaterial.prototype._hookArray = function (array) {
  64910. var _this = this;
  64911. var oldPush = array.push;
  64912. array.push = function () {
  64913. var items = [];
  64914. for (var _i = 0; _i < arguments.length; _i++) {
  64915. items[_i] = arguments[_i];
  64916. }
  64917. var result = oldPush.apply(array, items);
  64918. _this._markAllSubMeshesAsTexturesDirty();
  64919. return result;
  64920. };
  64921. var oldSplice = array.splice;
  64922. array.splice = function (index, deleteCount) {
  64923. var deleted = oldSplice.apply(array, [index, deleteCount]);
  64924. _this._markAllSubMeshesAsTexturesDirty();
  64925. return deleted;
  64926. };
  64927. };
  64928. // Properties
  64929. MultiMaterial.prototype.getSubMaterial = function (index) {
  64930. if (index < 0 || index >= this.subMaterials.length) {
  64931. return this.getScene().defaultMaterial;
  64932. }
  64933. return this.subMaterials[index];
  64934. };
  64935. MultiMaterial.prototype.getActiveTextures = function () {
  64936. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  64937. if (subMaterial) {
  64938. return subMaterial.getActiveTextures();
  64939. }
  64940. else {
  64941. return [];
  64942. }
  64943. }));
  64944. var _a;
  64945. };
  64946. // Methods
  64947. MultiMaterial.prototype.getClassName = function () {
  64948. return "MultiMaterial";
  64949. };
  64950. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  64951. for (var index = 0; index < this.subMaterials.length; index++) {
  64952. var subMaterial = this.subMaterials[index];
  64953. if (subMaterial) {
  64954. if (subMaterial.storeEffectOnSubMeshes) {
  64955. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  64956. return false;
  64957. }
  64958. continue;
  64959. }
  64960. if (!subMaterial.isReady(mesh)) {
  64961. return false;
  64962. }
  64963. }
  64964. }
  64965. return true;
  64966. };
  64967. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  64968. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  64969. for (var index = 0; index < this.subMaterials.length; index++) {
  64970. var subMaterial = null;
  64971. var current = this.subMaterials[index];
  64972. if (cloneChildren && current) {
  64973. subMaterial = current.clone(name + "-" + current.name);
  64974. }
  64975. else {
  64976. subMaterial = this.subMaterials[index];
  64977. }
  64978. newMultiMaterial.subMaterials.push(subMaterial);
  64979. }
  64980. return newMultiMaterial;
  64981. };
  64982. MultiMaterial.prototype.serialize = function () {
  64983. var serializationObject = {};
  64984. serializationObject.name = this.name;
  64985. serializationObject.id = this.id;
  64986. if (BABYLON.Tags) {
  64987. serializationObject.tags = BABYLON.Tags.GetTags(this);
  64988. }
  64989. serializationObject.materials = [];
  64990. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  64991. var subMat = this.subMaterials[matIndex];
  64992. if (subMat) {
  64993. serializationObject.materials.push(subMat.id);
  64994. }
  64995. else {
  64996. serializationObject.materials.push(null);
  64997. }
  64998. }
  64999. return serializationObject;
  65000. };
  65001. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  65002. var scene = this.getScene();
  65003. if (!scene) {
  65004. return;
  65005. }
  65006. var index = scene.multiMaterials.indexOf(this);
  65007. if (index >= 0) {
  65008. scene.multiMaterials.splice(index, 1);
  65009. }
  65010. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  65011. };
  65012. return MultiMaterial;
  65013. }(BABYLON.Material));
  65014. BABYLON.MultiMaterial = MultiMaterial;
  65015. })(BABYLON || (BABYLON = {}));
  65016. //# sourceMappingURL=babylon.multiMaterial.js.map
  65017. "use strict";
  65018. var BABYLON;
  65019. (function (BABYLON) {
  65020. var FreeCameraTouchInput = /** @class */ (function () {
  65021. function FreeCameraTouchInput() {
  65022. this._offsetX = null;
  65023. this._offsetY = null;
  65024. this._pointerPressed = new Array();
  65025. this.touchAngularSensibility = 200000.0;
  65026. this.touchMoveSensibility = 250.0;
  65027. }
  65028. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  65029. var _this = this;
  65030. var previousPosition = null;
  65031. if (this._pointerInput === undefined) {
  65032. this._onLostFocus = function (evt) {
  65033. _this._offsetX = null;
  65034. _this._offsetY = null;
  65035. };
  65036. this._pointerInput = function (p, s) {
  65037. var evt = p.event;
  65038. if (evt.pointerType === "mouse") {
  65039. return;
  65040. }
  65041. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  65042. if (!noPreventDefault) {
  65043. evt.preventDefault();
  65044. }
  65045. _this._pointerPressed.push(evt.pointerId);
  65046. if (_this._pointerPressed.length !== 1) {
  65047. return;
  65048. }
  65049. previousPosition = {
  65050. x: evt.clientX,
  65051. y: evt.clientY
  65052. };
  65053. }
  65054. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  65055. if (!noPreventDefault) {
  65056. evt.preventDefault();
  65057. }
  65058. var index = _this._pointerPressed.indexOf(evt.pointerId);
  65059. if (index === -1) {
  65060. return;
  65061. }
  65062. _this._pointerPressed.splice(index, 1);
  65063. if (index != 0) {
  65064. return;
  65065. }
  65066. previousPosition = null;
  65067. _this._offsetX = null;
  65068. _this._offsetY = null;
  65069. }
  65070. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  65071. if (!noPreventDefault) {
  65072. evt.preventDefault();
  65073. }
  65074. if (!previousPosition) {
  65075. return;
  65076. }
  65077. var index = _this._pointerPressed.indexOf(evt.pointerId);
  65078. if (index != 0) {
  65079. return;
  65080. }
  65081. _this._offsetX = evt.clientX - previousPosition.x;
  65082. _this._offsetY = -(evt.clientY - previousPosition.y);
  65083. }
  65084. };
  65085. }
  65086. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  65087. if (this._onLostFocus) {
  65088. element.addEventListener("blur", this._onLostFocus);
  65089. }
  65090. };
  65091. FreeCameraTouchInput.prototype.detachControl = function (element) {
  65092. if (this._pointerInput && element) {
  65093. if (this._observer) {
  65094. this.camera.getScene().onPointerObservable.remove(this._observer);
  65095. this._observer = null;
  65096. }
  65097. if (this._onLostFocus) {
  65098. element.removeEventListener("blur", this._onLostFocus);
  65099. this._onLostFocus = null;
  65100. }
  65101. this._pointerPressed = [];
  65102. this._offsetX = null;
  65103. this._offsetY = null;
  65104. }
  65105. };
  65106. FreeCameraTouchInput.prototype.checkInputs = function () {
  65107. if (this._offsetX && this._offsetY) {
  65108. var camera = this.camera;
  65109. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  65110. if (this._pointerPressed.length > 1) {
  65111. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  65112. }
  65113. else {
  65114. var speed = camera._computeLocalCameraSpeed();
  65115. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  65116. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  65117. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  65118. }
  65119. }
  65120. };
  65121. FreeCameraTouchInput.prototype.getClassName = function () {
  65122. return "FreeCameraTouchInput";
  65123. };
  65124. FreeCameraTouchInput.prototype.getSimpleName = function () {
  65125. return "touch";
  65126. };
  65127. __decorate([
  65128. BABYLON.serialize()
  65129. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  65130. __decorate([
  65131. BABYLON.serialize()
  65132. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  65133. return FreeCameraTouchInput;
  65134. }());
  65135. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  65136. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  65137. })(BABYLON || (BABYLON = {}));
  65138. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  65139. "use strict";
  65140. var BABYLON;
  65141. (function (BABYLON) {
  65142. // We're mainly based on the logic defined into the FreeCamera code
  65143. var TouchCamera = /** @class */ (function (_super) {
  65144. __extends(TouchCamera, _super);
  65145. //-- end properties for backward compatibility for inputs
  65146. function TouchCamera(name, position, scene) {
  65147. var _this = _super.call(this, name, position, scene) || this;
  65148. _this.inputs.addTouch();
  65149. _this._setupInputs();
  65150. return _this;
  65151. }
  65152. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  65153. //-- Begin properties for backward compatibility for inputs
  65154. get: function () {
  65155. var touch = this.inputs.attached["touch"];
  65156. if (touch)
  65157. return touch.touchAngularSensibility;
  65158. return 0;
  65159. },
  65160. set: function (value) {
  65161. var touch = this.inputs.attached["touch"];
  65162. if (touch)
  65163. touch.touchAngularSensibility = value;
  65164. },
  65165. enumerable: true,
  65166. configurable: true
  65167. });
  65168. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  65169. get: function () {
  65170. var touch = this.inputs.attached["touch"];
  65171. if (touch)
  65172. return touch.touchMoveSensibility;
  65173. return 0;
  65174. },
  65175. set: function (value) {
  65176. var touch = this.inputs.attached["touch"];
  65177. if (touch)
  65178. touch.touchMoveSensibility = value;
  65179. },
  65180. enumerable: true,
  65181. configurable: true
  65182. });
  65183. TouchCamera.prototype.getClassName = function () {
  65184. return "TouchCamera";
  65185. };
  65186. TouchCamera.prototype._setupInputs = function () {
  65187. var mouse = this.inputs.attached["mouse"];
  65188. if (mouse) {
  65189. mouse.touchEnabled = false;
  65190. }
  65191. };
  65192. return TouchCamera;
  65193. }(BABYLON.FreeCamera));
  65194. BABYLON.TouchCamera = TouchCamera;
  65195. })(BABYLON || (BABYLON = {}));
  65196. //# sourceMappingURL=babylon.touchCamera.js.map
  65197. "use strict";
  65198. var BABYLON;
  65199. (function (BABYLON) {
  65200. var ProceduralTexture = /** @class */ (function (_super) {
  65201. __extends(ProceduralTexture, _super);
  65202. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  65203. if (fallbackTexture === void 0) { fallbackTexture = null; }
  65204. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65205. if (isCube === void 0) { isCube = false; }
  65206. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  65207. _this.isCube = isCube;
  65208. _this.isEnabled = true;
  65209. _this._currentRefreshId = -1;
  65210. _this._refreshRate = 1;
  65211. _this._vertexBuffers = {};
  65212. _this._uniforms = new Array();
  65213. _this._samplers = new Array();
  65214. _this._textures = {};
  65215. _this._floats = {};
  65216. _this._floatsArrays = {};
  65217. _this._colors3 = {};
  65218. _this._colors4 = {};
  65219. _this._vectors2 = {};
  65220. _this._vectors3 = {};
  65221. _this._matrices = {};
  65222. _this._fallbackTextureUsed = false;
  65223. scene._proceduralTextures.push(_this);
  65224. _this._engine = scene.getEngine();
  65225. _this.name = name;
  65226. _this.isRenderTarget = true;
  65227. _this._size = size;
  65228. _this._generateMipMaps = generateMipMaps;
  65229. _this.setFragment(fragment);
  65230. _this._fallbackTexture = fallbackTexture;
  65231. if (isCube) {
  65232. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  65233. _this.setFloat("face", 0);
  65234. }
  65235. else {
  65236. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  65237. }
  65238. // VBO
  65239. var vertices = [];
  65240. vertices.push(1, 1);
  65241. vertices.push(-1, 1);
  65242. vertices.push(-1, -1);
  65243. vertices.push(1, -1);
  65244. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  65245. _this._createIndexBuffer();
  65246. return _this;
  65247. }
  65248. ProceduralTexture.prototype._createIndexBuffer = function () {
  65249. var engine = this._engine;
  65250. // Indices
  65251. var indices = [];
  65252. indices.push(0);
  65253. indices.push(1);
  65254. indices.push(2);
  65255. indices.push(0);
  65256. indices.push(2);
  65257. indices.push(3);
  65258. this._indexBuffer = engine.createIndexBuffer(indices);
  65259. };
  65260. ProceduralTexture.prototype._rebuild = function () {
  65261. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  65262. if (vb) {
  65263. vb._rebuild();
  65264. }
  65265. this._createIndexBuffer();
  65266. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  65267. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  65268. }
  65269. };
  65270. ProceduralTexture.prototype.reset = function () {
  65271. if (this._effect === undefined) {
  65272. return;
  65273. }
  65274. var engine = this._engine;
  65275. engine._releaseEffect(this._effect);
  65276. };
  65277. ProceduralTexture.prototype.isReady = function () {
  65278. var _this = this;
  65279. var engine = this._engine;
  65280. var shaders;
  65281. if (!this._fragment) {
  65282. return false;
  65283. }
  65284. if (this._fallbackTextureUsed) {
  65285. return true;
  65286. }
  65287. if (this._fragment.fragmentElement !== undefined) {
  65288. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  65289. }
  65290. else {
  65291. shaders = { vertex: "procedural", fragment: this._fragment };
  65292. }
  65293. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  65294. _this.releaseInternalTexture();
  65295. if (_this._fallbackTexture) {
  65296. _this._texture = _this._fallbackTexture._texture;
  65297. if (_this._texture) {
  65298. _this._texture.incrementReferences();
  65299. }
  65300. }
  65301. _this._fallbackTextureUsed = true;
  65302. });
  65303. return this._effect.isReady();
  65304. };
  65305. ProceduralTexture.prototype.resetRefreshCounter = function () {
  65306. this._currentRefreshId = -1;
  65307. };
  65308. ProceduralTexture.prototype.setFragment = function (fragment) {
  65309. this._fragment = fragment;
  65310. };
  65311. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  65312. get: function () {
  65313. return this._refreshRate;
  65314. },
  65315. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  65316. set: function (value) {
  65317. this._refreshRate = value;
  65318. this.resetRefreshCounter();
  65319. },
  65320. enumerable: true,
  65321. configurable: true
  65322. });
  65323. ProceduralTexture.prototype._shouldRender = function () {
  65324. if (!this.isEnabled || !this.isReady() || !this._texture) {
  65325. return false;
  65326. }
  65327. if (this._fallbackTextureUsed) {
  65328. return false;
  65329. }
  65330. if (this._currentRefreshId === -1) {
  65331. this._currentRefreshId = 1;
  65332. return true;
  65333. }
  65334. if (this.refreshRate === this._currentRefreshId) {
  65335. this._currentRefreshId = 1;
  65336. return true;
  65337. }
  65338. this._currentRefreshId++;
  65339. return false;
  65340. };
  65341. ProceduralTexture.prototype.getRenderSize = function () {
  65342. return this._size;
  65343. };
  65344. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  65345. if (this._fallbackTextureUsed) {
  65346. return;
  65347. }
  65348. this.releaseInternalTexture();
  65349. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  65350. };
  65351. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  65352. if (this._uniforms.indexOf(uniformName) === -1) {
  65353. this._uniforms.push(uniformName);
  65354. }
  65355. };
  65356. ProceduralTexture.prototype.setTexture = function (name, texture) {
  65357. if (this._samplers.indexOf(name) === -1) {
  65358. this._samplers.push(name);
  65359. }
  65360. this._textures[name] = texture;
  65361. return this;
  65362. };
  65363. ProceduralTexture.prototype.setFloat = function (name, value) {
  65364. this._checkUniform(name);
  65365. this._floats[name] = value;
  65366. return this;
  65367. };
  65368. ProceduralTexture.prototype.setFloats = function (name, value) {
  65369. this._checkUniform(name);
  65370. this._floatsArrays[name] = value;
  65371. return this;
  65372. };
  65373. ProceduralTexture.prototype.setColor3 = function (name, value) {
  65374. this._checkUniform(name);
  65375. this._colors3[name] = value;
  65376. return this;
  65377. };
  65378. ProceduralTexture.prototype.setColor4 = function (name, value) {
  65379. this._checkUniform(name);
  65380. this._colors4[name] = value;
  65381. return this;
  65382. };
  65383. ProceduralTexture.prototype.setVector2 = function (name, value) {
  65384. this._checkUniform(name);
  65385. this._vectors2[name] = value;
  65386. return this;
  65387. };
  65388. ProceduralTexture.prototype.setVector3 = function (name, value) {
  65389. this._checkUniform(name);
  65390. this._vectors3[name] = value;
  65391. return this;
  65392. };
  65393. ProceduralTexture.prototype.setMatrix = function (name, value) {
  65394. this._checkUniform(name);
  65395. this._matrices[name] = value;
  65396. return this;
  65397. };
  65398. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  65399. var scene = this.getScene();
  65400. if (!scene) {
  65401. return;
  65402. }
  65403. var engine = this._engine;
  65404. // Render
  65405. engine.enableEffect(this._effect);
  65406. engine.setState(false);
  65407. // Texture
  65408. for (var name in this._textures) {
  65409. this._effect.setTexture(name, this._textures[name]);
  65410. }
  65411. // Float
  65412. for (name in this._floats) {
  65413. this._effect.setFloat(name, this._floats[name]);
  65414. }
  65415. // Floats
  65416. for (name in this._floatsArrays) {
  65417. this._effect.setArray(name, this._floatsArrays[name]);
  65418. }
  65419. // Color3
  65420. for (name in this._colors3) {
  65421. this._effect.setColor3(name, this._colors3[name]);
  65422. }
  65423. // Color4
  65424. for (name in this._colors4) {
  65425. var color = this._colors4[name];
  65426. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  65427. }
  65428. // Vector2
  65429. for (name in this._vectors2) {
  65430. this._effect.setVector2(name, this._vectors2[name]);
  65431. }
  65432. // Vector3
  65433. for (name in this._vectors3) {
  65434. this._effect.setVector3(name, this._vectors3[name]);
  65435. }
  65436. // Matrix
  65437. for (name in this._matrices) {
  65438. this._effect.setMatrix(name, this._matrices[name]);
  65439. }
  65440. if (!this._texture) {
  65441. return;
  65442. }
  65443. if (this.isCube) {
  65444. for (var face = 0; face < 6; face++) {
  65445. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  65446. // VBOs
  65447. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  65448. this._effect.setFloat("face", face);
  65449. // Clear
  65450. engine.clear(scene.clearColor, true, true, true);
  65451. // Draw order
  65452. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  65453. // Mipmaps
  65454. if (face === 5) {
  65455. engine.generateMipMapsForCubemap(this._texture);
  65456. }
  65457. }
  65458. }
  65459. else {
  65460. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  65461. // VBOs
  65462. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  65463. // Clear
  65464. engine.clear(scene.clearColor, true, true, true);
  65465. // Draw order
  65466. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  65467. }
  65468. // Unbind
  65469. engine.unBindFramebuffer(this._texture, this.isCube);
  65470. if (this.onGenerated) {
  65471. this.onGenerated();
  65472. }
  65473. };
  65474. ProceduralTexture.prototype.clone = function () {
  65475. var textureSize = this.getSize();
  65476. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  65477. // Base texture
  65478. newTexture.hasAlpha = this.hasAlpha;
  65479. newTexture.level = this.level;
  65480. // RenderTarget Texture
  65481. newTexture.coordinatesMode = this.coordinatesMode;
  65482. return newTexture;
  65483. };
  65484. ProceduralTexture.prototype.dispose = function () {
  65485. var scene = this.getScene();
  65486. if (!scene) {
  65487. return;
  65488. }
  65489. var index = scene._proceduralTextures.indexOf(this);
  65490. if (index >= 0) {
  65491. scene._proceduralTextures.splice(index, 1);
  65492. }
  65493. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  65494. if (vertexBuffer) {
  65495. vertexBuffer.dispose();
  65496. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  65497. }
  65498. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  65499. this._indexBuffer = null;
  65500. }
  65501. _super.prototype.dispose.call(this);
  65502. };
  65503. return ProceduralTexture;
  65504. }(BABYLON.Texture));
  65505. BABYLON.ProceduralTexture = ProceduralTexture;
  65506. })(BABYLON || (BABYLON = {}));
  65507. //# sourceMappingURL=babylon.proceduralTexture.js.map
  65508. "use strict";
  65509. var BABYLON;
  65510. (function (BABYLON) {
  65511. var CustomProceduralTexture = /** @class */ (function (_super) {
  65512. __extends(CustomProceduralTexture, _super);
  65513. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  65514. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  65515. _this._animate = true;
  65516. _this._time = 0;
  65517. _this._texturePath = texturePath;
  65518. //Try to load json
  65519. _this.loadJson(texturePath);
  65520. _this.refreshRate = 1;
  65521. return _this;
  65522. }
  65523. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  65524. var _this = this;
  65525. var noConfigFile = function () {
  65526. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  65527. try {
  65528. _this.setFragment(_this._texturePath);
  65529. }
  65530. catch (ex) {
  65531. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  65532. }
  65533. };
  65534. var configFileUrl = jsonUrl + "/config.json";
  65535. var xhr = new XMLHttpRequest();
  65536. xhr.open("GET", configFileUrl, true);
  65537. xhr.addEventListener("load", function () {
  65538. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  65539. try {
  65540. _this._config = JSON.parse(xhr.response);
  65541. _this.updateShaderUniforms();
  65542. _this.updateTextures();
  65543. _this.setFragment(_this._texturePath + "/custom");
  65544. _this._animate = _this._config.animate;
  65545. _this.refreshRate = _this._config.refreshrate;
  65546. }
  65547. catch (ex) {
  65548. noConfigFile();
  65549. }
  65550. }
  65551. else {
  65552. noConfigFile();
  65553. }
  65554. }, false);
  65555. xhr.addEventListener("error", function () {
  65556. noConfigFile();
  65557. }, false);
  65558. try {
  65559. xhr.send();
  65560. }
  65561. catch (ex) {
  65562. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  65563. }
  65564. };
  65565. CustomProceduralTexture.prototype.isReady = function () {
  65566. if (!_super.prototype.isReady.call(this)) {
  65567. return false;
  65568. }
  65569. for (var name in this._textures) {
  65570. var texture = this._textures[name];
  65571. if (!texture.isReady()) {
  65572. return false;
  65573. }
  65574. }
  65575. return true;
  65576. };
  65577. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  65578. var scene = this.getScene();
  65579. if (this._animate && scene) {
  65580. this._time += scene.getAnimationRatio() * 0.03;
  65581. this.updateShaderUniforms();
  65582. }
  65583. _super.prototype.render.call(this, useCameraPostProcess);
  65584. };
  65585. CustomProceduralTexture.prototype.updateTextures = function () {
  65586. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  65587. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  65588. }
  65589. };
  65590. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  65591. if (this._config) {
  65592. for (var j = 0; j < this._config.uniforms.length; j++) {
  65593. var uniform = this._config.uniforms[j];
  65594. switch (uniform.type) {
  65595. case "float":
  65596. this.setFloat(uniform.name, uniform.value);
  65597. break;
  65598. case "color3":
  65599. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  65600. break;
  65601. case "color4":
  65602. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  65603. break;
  65604. case "vector2":
  65605. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  65606. break;
  65607. case "vector3":
  65608. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  65609. break;
  65610. }
  65611. }
  65612. }
  65613. this.setFloat("time", this._time);
  65614. };
  65615. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  65616. get: function () {
  65617. return this._animate;
  65618. },
  65619. set: function (value) {
  65620. this._animate = value;
  65621. },
  65622. enumerable: true,
  65623. configurable: true
  65624. });
  65625. return CustomProceduralTexture;
  65626. }(BABYLON.ProceduralTexture));
  65627. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  65628. })(BABYLON || (BABYLON = {}));
  65629. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  65630. "use strict";
  65631. var BABYLON;
  65632. (function (BABYLON) {
  65633. var FreeCameraGamepadInput = /** @class */ (function () {
  65634. function FreeCameraGamepadInput() {
  65635. this.gamepadAngularSensibility = 200;
  65636. this.gamepadMoveSensibility = 40;
  65637. // private members
  65638. this._cameraTransform = BABYLON.Matrix.Identity();
  65639. this._deltaTransform = BABYLON.Vector3.Zero();
  65640. this._vector3 = BABYLON.Vector3.Zero();
  65641. this._vector2 = BABYLON.Vector2.Zero();
  65642. }
  65643. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  65644. var _this = this;
  65645. var manager = this.camera.getScene().gamepadManager;
  65646. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  65647. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  65648. // prioritize XBOX gamepads.
  65649. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  65650. _this.gamepad = gamepad;
  65651. }
  65652. }
  65653. });
  65654. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  65655. if (_this.gamepad === gamepad) {
  65656. _this.gamepad = null;
  65657. }
  65658. });
  65659. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  65660. };
  65661. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  65662. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  65663. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  65664. this.gamepad = null;
  65665. };
  65666. FreeCameraGamepadInput.prototype.checkInputs = function () {
  65667. if (this.gamepad && this.gamepad.leftStick) {
  65668. var camera = this.camera;
  65669. var LSValues = this.gamepad.leftStick;
  65670. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  65671. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  65672. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  65673. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  65674. var RSValues = this.gamepad.rightStick;
  65675. if (RSValues) {
  65676. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  65677. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  65678. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  65679. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  65680. }
  65681. else {
  65682. RSValues = { x: 0, y: 0 };
  65683. }
  65684. if (!camera.rotationQuaternion) {
  65685. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  65686. }
  65687. else {
  65688. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  65689. }
  65690. var speed = camera._computeLocalCameraSpeed() * 50.0;
  65691. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  65692. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  65693. camera.cameraDirection.addInPlace(this._deltaTransform);
  65694. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  65695. camera.cameraRotation.addInPlace(this._vector2);
  65696. }
  65697. };
  65698. FreeCameraGamepadInput.prototype.getClassName = function () {
  65699. return "FreeCameraGamepadInput";
  65700. };
  65701. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  65702. return "gamepad";
  65703. };
  65704. __decorate([
  65705. BABYLON.serialize()
  65706. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  65707. __decorate([
  65708. BABYLON.serialize()
  65709. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  65710. return FreeCameraGamepadInput;
  65711. }());
  65712. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  65713. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  65714. })(BABYLON || (BABYLON = {}));
  65715. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  65716. "use strict";
  65717. var BABYLON;
  65718. (function (BABYLON) {
  65719. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  65720. function ArcRotateCameraGamepadInput() {
  65721. this.gamepadRotationSensibility = 80;
  65722. this.gamepadMoveSensibility = 40;
  65723. }
  65724. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  65725. var _this = this;
  65726. var manager = this.camera.getScene().gamepadManager;
  65727. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  65728. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  65729. // prioritize XBOX gamepads.
  65730. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  65731. _this.gamepad = gamepad;
  65732. }
  65733. }
  65734. });
  65735. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  65736. if (_this.gamepad === gamepad) {
  65737. _this.gamepad = null;
  65738. }
  65739. });
  65740. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  65741. };
  65742. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  65743. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  65744. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  65745. this.gamepad = null;
  65746. };
  65747. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  65748. if (this.gamepad) {
  65749. var camera = this.camera;
  65750. var RSValues = this.gamepad.rightStick;
  65751. if (RSValues) {
  65752. if (RSValues.x != 0) {
  65753. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  65754. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  65755. camera.inertialAlphaOffset += normalizedRX;
  65756. }
  65757. }
  65758. if (RSValues.y != 0) {
  65759. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  65760. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  65761. camera.inertialBetaOffset += normalizedRY;
  65762. }
  65763. }
  65764. }
  65765. var LSValues = this.gamepad.leftStick;
  65766. if (LSValues && LSValues.y != 0) {
  65767. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  65768. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  65769. this.camera.inertialRadiusOffset -= normalizedLY;
  65770. }
  65771. }
  65772. }
  65773. };
  65774. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  65775. return "ArcRotateCameraGamepadInput";
  65776. };
  65777. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  65778. return "gamepad";
  65779. };
  65780. __decorate([
  65781. BABYLON.serialize()
  65782. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  65783. __decorate([
  65784. BABYLON.serialize()
  65785. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  65786. return ArcRotateCameraGamepadInput;
  65787. }());
  65788. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  65789. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  65790. })(BABYLON || (BABYLON = {}));
  65791. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  65792. "use strict";
  65793. var BABYLON;
  65794. (function (BABYLON) {
  65795. var GamepadManager = /** @class */ (function () {
  65796. function GamepadManager(_scene) {
  65797. var _this = this;
  65798. this._scene = _scene;
  65799. this._babylonGamepads = [];
  65800. this._oneGamepadConnected = false;
  65801. this._isMonitoring = false;
  65802. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  65803. if (!BABYLON.Tools.IsWindowObjectExist()) {
  65804. this._gamepadEventSupported = false;
  65805. }
  65806. else {
  65807. this._gamepadEventSupported = 'GamepadEvent' in window;
  65808. this._gamepadSupport = (navigator.getGamepads ||
  65809. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  65810. }
  65811. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  65812. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  65813. for (var i in _this._babylonGamepads) {
  65814. var gamepad = _this._babylonGamepads[i];
  65815. if (gamepad && gamepad._isConnected) {
  65816. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  65817. }
  65818. }
  65819. });
  65820. this._onGamepadConnectedEvent = function (evt) {
  65821. var gamepad = evt.gamepad;
  65822. if (gamepad.index in _this._babylonGamepads) {
  65823. if (_this._babylonGamepads[gamepad.index].isConnected) {
  65824. return;
  65825. }
  65826. }
  65827. var newGamepad;
  65828. if (_this._babylonGamepads[gamepad.index]) {
  65829. newGamepad = _this._babylonGamepads[gamepad.index];
  65830. newGamepad.browserGamepad = gamepad;
  65831. newGamepad._isConnected = true;
  65832. }
  65833. else {
  65834. newGamepad = _this._addNewGamepad(gamepad);
  65835. }
  65836. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  65837. _this._startMonitoringGamepads();
  65838. };
  65839. this._onGamepadDisconnectedEvent = function (evt) {
  65840. var gamepad = evt.gamepad;
  65841. // Remove the gamepad from the list of gamepads to monitor.
  65842. for (var i in _this._babylonGamepads) {
  65843. if (_this._babylonGamepads[i].index === gamepad.index) {
  65844. var disconnectedGamepad = _this._babylonGamepads[i];
  65845. disconnectedGamepad._isConnected = false;
  65846. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  65847. break;
  65848. }
  65849. }
  65850. };
  65851. if (this._gamepadSupport) {
  65852. //first add already-connected gamepads
  65853. this._updateGamepadObjects();
  65854. if (this._babylonGamepads.length) {
  65855. this._startMonitoringGamepads();
  65856. }
  65857. // Checking if the gamepad connected event is supported (like in Firefox)
  65858. if (this._gamepadEventSupported) {
  65859. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  65860. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  65861. }
  65862. else {
  65863. this._startMonitoringGamepads();
  65864. }
  65865. }
  65866. }
  65867. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  65868. get: function () {
  65869. return this._babylonGamepads;
  65870. },
  65871. enumerable: true,
  65872. configurable: true
  65873. });
  65874. GamepadManager.prototype.getGamepadByType = function (type) {
  65875. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  65876. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  65877. var gamepad = _a[_i];
  65878. if (gamepad && gamepad.type === type) {
  65879. return gamepad;
  65880. }
  65881. }
  65882. return null;
  65883. };
  65884. GamepadManager.prototype.dispose = function () {
  65885. if (this._gamepadEventSupported) {
  65886. if (this._onGamepadConnectedEvent) {
  65887. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  65888. }
  65889. if (this._onGamepadDisconnectedEvent) {
  65890. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  65891. }
  65892. this._onGamepadConnectedEvent = null;
  65893. this._onGamepadDisconnectedEvent = null;
  65894. }
  65895. this._babylonGamepads.forEach(function (gamepad) {
  65896. gamepad.dispose();
  65897. });
  65898. this.onGamepadConnectedObservable.clear();
  65899. this.onGamepadDisconnectedObservable.clear();
  65900. this._oneGamepadConnected = false;
  65901. this._stopMonitoringGamepads();
  65902. this._babylonGamepads = [];
  65903. };
  65904. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  65905. if (!this._oneGamepadConnected) {
  65906. this._oneGamepadConnected = true;
  65907. }
  65908. var newGamepad;
  65909. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  65910. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  65911. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  65912. }
  65913. else if (gamepad.pose) {
  65914. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  65915. }
  65916. else {
  65917. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  65918. }
  65919. this._babylonGamepads[newGamepad.index] = newGamepad;
  65920. return newGamepad;
  65921. };
  65922. GamepadManager.prototype._startMonitoringGamepads = function () {
  65923. if (!this._isMonitoring) {
  65924. this._isMonitoring = true;
  65925. //back-comp
  65926. if (!this._scene) {
  65927. this._checkGamepadsStatus();
  65928. }
  65929. }
  65930. };
  65931. GamepadManager.prototype._stopMonitoringGamepads = function () {
  65932. this._isMonitoring = false;
  65933. };
  65934. GamepadManager.prototype._checkGamepadsStatus = function () {
  65935. var _this = this;
  65936. // Hack to be compatible Chrome
  65937. this._updateGamepadObjects();
  65938. for (var i in this._babylonGamepads) {
  65939. var gamepad = this._babylonGamepads[i];
  65940. if (!gamepad || !gamepad.isConnected) {
  65941. continue;
  65942. }
  65943. gamepad.update();
  65944. }
  65945. if (this._isMonitoring && !this._scene) {
  65946. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  65947. }
  65948. };
  65949. // This function is called only on Chrome, which does not properly support
  65950. // connection/disconnection events and forces you to recopy again the gamepad object
  65951. GamepadManager.prototype._updateGamepadObjects = function () {
  65952. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  65953. for (var i = 0; i < gamepads.length; i++) {
  65954. if (gamepads[i]) {
  65955. if (!this._babylonGamepads[gamepads[i].index]) {
  65956. var newGamepad = this._addNewGamepad(gamepads[i]);
  65957. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  65958. }
  65959. else {
  65960. // Forced to copy again this object for Chrome for unknown reason
  65961. this._babylonGamepads[i].browserGamepad = gamepads[i];
  65962. if (!this._babylonGamepads[i].isConnected) {
  65963. this._babylonGamepads[i]._isConnected = true;
  65964. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  65965. }
  65966. }
  65967. }
  65968. }
  65969. };
  65970. return GamepadManager;
  65971. }());
  65972. BABYLON.GamepadManager = GamepadManager;
  65973. })(BABYLON || (BABYLON = {}));
  65974. //# sourceMappingURL=babylon.gamepadManager.js.map
  65975. "use strict";
  65976. var BABYLON;
  65977. (function (BABYLON) {
  65978. var StickValues = /** @class */ (function () {
  65979. function StickValues(x, y) {
  65980. this.x = x;
  65981. this.y = y;
  65982. }
  65983. return StickValues;
  65984. }());
  65985. BABYLON.StickValues = StickValues;
  65986. var Gamepad = /** @class */ (function () {
  65987. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  65988. if (leftStickX === void 0) { leftStickX = 0; }
  65989. if (leftStickY === void 0) { leftStickY = 1; }
  65990. if (rightStickX === void 0) { rightStickX = 2; }
  65991. if (rightStickY === void 0) { rightStickY = 3; }
  65992. this.id = id;
  65993. this.index = index;
  65994. this.browserGamepad = browserGamepad;
  65995. this._isConnected = true;
  65996. this._invertLeftStickY = false;
  65997. this.type = Gamepad.GAMEPAD;
  65998. this._leftStickAxisX = leftStickX;
  65999. this._leftStickAxisY = leftStickY;
  66000. this._rightStickAxisX = rightStickX;
  66001. this._rightStickAxisY = rightStickY;
  66002. if (this.browserGamepad.axes.length >= 2) {
  66003. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  66004. }
  66005. if (this.browserGamepad.axes.length >= 4) {
  66006. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  66007. }
  66008. }
  66009. Object.defineProperty(Gamepad.prototype, "isConnected", {
  66010. get: function () {
  66011. return this._isConnected;
  66012. },
  66013. enumerable: true,
  66014. configurable: true
  66015. });
  66016. Gamepad.prototype.onleftstickchanged = function (callback) {
  66017. this._onleftstickchanged = callback;
  66018. };
  66019. Gamepad.prototype.onrightstickchanged = function (callback) {
  66020. this._onrightstickchanged = callback;
  66021. };
  66022. Object.defineProperty(Gamepad.prototype, "leftStick", {
  66023. get: function () {
  66024. return this._leftStick;
  66025. },
  66026. set: function (newValues) {
  66027. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  66028. this._onleftstickchanged(newValues);
  66029. }
  66030. this._leftStick = newValues;
  66031. },
  66032. enumerable: true,
  66033. configurable: true
  66034. });
  66035. Object.defineProperty(Gamepad.prototype, "rightStick", {
  66036. get: function () {
  66037. return this._rightStick;
  66038. },
  66039. set: function (newValues) {
  66040. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  66041. this._onrightstickchanged(newValues);
  66042. }
  66043. this._rightStick = newValues;
  66044. },
  66045. enumerable: true,
  66046. configurable: true
  66047. });
  66048. Gamepad.prototype.update = function () {
  66049. if (this._leftStick) {
  66050. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  66051. if (this._invertLeftStickY) {
  66052. this.leftStick.y *= -1;
  66053. }
  66054. }
  66055. if (this._rightStick) {
  66056. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  66057. }
  66058. };
  66059. Gamepad.prototype.dispose = function () {
  66060. };
  66061. Gamepad.GAMEPAD = 0;
  66062. Gamepad.GENERIC = 1;
  66063. Gamepad.XBOX = 2;
  66064. Gamepad.POSE_ENABLED = 3;
  66065. return Gamepad;
  66066. }());
  66067. BABYLON.Gamepad = Gamepad;
  66068. var GenericPad = /** @class */ (function (_super) {
  66069. __extends(GenericPad, _super);
  66070. function GenericPad(id, index, browserGamepad) {
  66071. var _this = _super.call(this, id, index, browserGamepad) || this;
  66072. _this.onButtonDownObservable = new BABYLON.Observable();
  66073. _this.onButtonUpObservable = new BABYLON.Observable();
  66074. _this.type = Gamepad.GENERIC;
  66075. _this._buttons = new Array(browserGamepad.buttons.length);
  66076. return _this;
  66077. }
  66078. GenericPad.prototype.onbuttondown = function (callback) {
  66079. this._onbuttondown = callback;
  66080. };
  66081. GenericPad.prototype.onbuttonup = function (callback) {
  66082. this._onbuttonup = callback;
  66083. };
  66084. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  66085. if (newValue !== currentValue) {
  66086. if (newValue === 1) {
  66087. if (this._onbuttondown) {
  66088. this._onbuttondown(buttonIndex);
  66089. }
  66090. this.onButtonDownObservable.notifyObservers(buttonIndex);
  66091. }
  66092. if (newValue === 0) {
  66093. if (this._onbuttonup) {
  66094. this._onbuttonup(buttonIndex);
  66095. }
  66096. this.onButtonUpObservable.notifyObservers(buttonIndex);
  66097. }
  66098. }
  66099. return newValue;
  66100. };
  66101. GenericPad.prototype.update = function () {
  66102. _super.prototype.update.call(this);
  66103. for (var index = 0; index < this._buttons.length; index++) {
  66104. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  66105. }
  66106. };
  66107. GenericPad.prototype.dispose = function () {
  66108. _super.prototype.dispose.call(this);
  66109. this.onButtonDownObservable.clear();
  66110. this.onButtonUpObservable.clear();
  66111. };
  66112. return GenericPad;
  66113. }(Gamepad));
  66114. BABYLON.GenericPad = GenericPad;
  66115. })(BABYLON || (BABYLON = {}));
  66116. //# sourceMappingURL=babylon.gamepad.js.map
  66117. "use strict";
  66118. var BABYLON;
  66119. (function (BABYLON) {
  66120. var Xbox360Button;
  66121. (function (Xbox360Button) {
  66122. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  66123. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  66124. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  66125. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  66126. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  66127. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  66128. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  66129. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  66130. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  66131. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  66132. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  66133. var Xbox360Dpad;
  66134. (function (Xbox360Dpad) {
  66135. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  66136. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  66137. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  66138. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  66139. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  66140. var Xbox360Pad = /** @class */ (function (_super) {
  66141. __extends(Xbox360Pad, _super);
  66142. function Xbox360Pad(id, index, gamepad, xboxOne) {
  66143. if (xboxOne === void 0) { xboxOne = false; }
  66144. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  66145. _this._leftTrigger = 0;
  66146. _this._rightTrigger = 0;
  66147. _this.onButtonDownObservable = new BABYLON.Observable();
  66148. _this.onButtonUpObservable = new BABYLON.Observable();
  66149. _this.onPadDownObservable = new BABYLON.Observable();
  66150. _this.onPadUpObservable = new BABYLON.Observable();
  66151. _this._buttonA = 0;
  66152. _this._buttonB = 0;
  66153. _this._buttonX = 0;
  66154. _this._buttonY = 0;
  66155. _this._buttonBack = 0;
  66156. _this._buttonStart = 0;
  66157. _this._buttonLB = 0;
  66158. _this._buttonRB = 0;
  66159. _this._buttonLeftStick = 0;
  66160. _this._buttonRightStick = 0;
  66161. _this._dPadUp = 0;
  66162. _this._dPadDown = 0;
  66163. _this._dPadLeft = 0;
  66164. _this._dPadRight = 0;
  66165. _this._isXboxOnePad = false;
  66166. _this.type = BABYLON.Gamepad.XBOX;
  66167. _this._isXboxOnePad = xboxOne;
  66168. return _this;
  66169. }
  66170. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  66171. this._onlefttriggerchanged = callback;
  66172. };
  66173. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  66174. this._onrighttriggerchanged = callback;
  66175. };
  66176. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  66177. get: function () {
  66178. return this._leftTrigger;
  66179. },
  66180. set: function (newValue) {
  66181. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  66182. this._onlefttriggerchanged(newValue);
  66183. }
  66184. this._leftTrigger = newValue;
  66185. },
  66186. enumerable: true,
  66187. configurable: true
  66188. });
  66189. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  66190. get: function () {
  66191. return this._rightTrigger;
  66192. },
  66193. set: function (newValue) {
  66194. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  66195. this._onrighttriggerchanged(newValue);
  66196. }
  66197. this._rightTrigger = newValue;
  66198. },
  66199. enumerable: true,
  66200. configurable: true
  66201. });
  66202. Xbox360Pad.prototype.onbuttondown = function (callback) {
  66203. this._onbuttondown = callback;
  66204. };
  66205. Xbox360Pad.prototype.onbuttonup = function (callback) {
  66206. this._onbuttonup = callback;
  66207. };
  66208. Xbox360Pad.prototype.ondpaddown = function (callback) {
  66209. this._ondpaddown = callback;
  66210. };
  66211. Xbox360Pad.prototype.ondpadup = function (callback) {
  66212. this._ondpadup = callback;
  66213. };
  66214. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  66215. if (newValue !== currentValue) {
  66216. if (newValue === 1) {
  66217. if (this._onbuttondown) {
  66218. this._onbuttondown(buttonType);
  66219. }
  66220. this.onButtonDownObservable.notifyObservers(buttonType);
  66221. }
  66222. if (newValue === 0) {
  66223. if (this._onbuttonup) {
  66224. this._onbuttonup(buttonType);
  66225. }
  66226. this.onButtonUpObservable.notifyObservers(buttonType);
  66227. }
  66228. }
  66229. return newValue;
  66230. };
  66231. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  66232. if (newValue !== currentValue) {
  66233. if (newValue === 1) {
  66234. if (this._ondpaddown) {
  66235. this._ondpaddown(buttonType);
  66236. }
  66237. this.onPadDownObservable.notifyObservers(buttonType);
  66238. }
  66239. if (newValue === 0) {
  66240. if (this._ondpadup) {
  66241. this._ondpadup(buttonType);
  66242. }
  66243. this.onPadUpObservable.notifyObservers(buttonType);
  66244. }
  66245. }
  66246. return newValue;
  66247. };
  66248. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  66249. get: function () {
  66250. return this._buttonA;
  66251. },
  66252. set: function (value) {
  66253. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  66254. },
  66255. enumerable: true,
  66256. configurable: true
  66257. });
  66258. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  66259. get: function () {
  66260. return this._buttonB;
  66261. },
  66262. set: function (value) {
  66263. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  66264. },
  66265. enumerable: true,
  66266. configurable: true
  66267. });
  66268. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  66269. get: function () {
  66270. return this._buttonX;
  66271. },
  66272. set: function (value) {
  66273. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  66274. },
  66275. enumerable: true,
  66276. configurable: true
  66277. });
  66278. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  66279. get: function () {
  66280. return this._buttonY;
  66281. },
  66282. set: function (value) {
  66283. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  66284. },
  66285. enumerable: true,
  66286. configurable: true
  66287. });
  66288. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  66289. get: function () {
  66290. return this._buttonStart;
  66291. },
  66292. set: function (value) {
  66293. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  66294. },
  66295. enumerable: true,
  66296. configurable: true
  66297. });
  66298. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  66299. get: function () {
  66300. return this._buttonBack;
  66301. },
  66302. set: function (value) {
  66303. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  66304. },
  66305. enumerable: true,
  66306. configurable: true
  66307. });
  66308. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  66309. get: function () {
  66310. return this._buttonLB;
  66311. },
  66312. set: function (value) {
  66313. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  66314. },
  66315. enumerable: true,
  66316. configurable: true
  66317. });
  66318. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  66319. get: function () {
  66320. return this._buttonRB;
  66321. },
  66322. set: function (value) {
  66323. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  66324. },
  66325. enumerable: true,
  66326. configurable: true
  66327. });
  66328. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  66329. get: function () {
  66330. return this._buttonLeftStick;
  66331. },
  66332. set: function (value) {
  66333. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  66334. },
  66335. enumerable: true,
  66336. configurable: true
  66337. });
  66338. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  66339. get: function () {
  66340. return this._buttonRightStick;
  66341. },
  66342. set: function (value) {
  66343. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  66344. },
  66345. enumerable: true,
  66346. configurable: true
  66347. });
  66348. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  66349. get: function () {
  66350. return this._dPadUp;
  66351. },
  66352. set: function (value) {
  66353. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  66354. },
  66355. enumerable: true,
  66356. configurable: true
  66357. });
  66358. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  66359. get: function () {
  66360. return this._dPadDown;
  66361. },
  66362. set: function (value) {
  66363. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  66364. },
  66365. enumerable: true,
  66366. configurable: true
  66367. });
  66368. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  66369. get: function () {
  66370. return this._dPadLeft;
  66371. },
  66372. set: function (value) {
  66373. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  66374. },
  66375. enumerable: true,
  66376. configurable: true
  66377. });
  66378. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  66379. get: function () {
  66380. return this._dPadRight;
  66381. },
  66382. set: function (value) {
  66383. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  66384. },
  66385. enumerable: true,
  66386. configurable: true
  66387. });
  66388. Xbox360Pad.prototype.update = function () {
  66389. _super.prototype.update.call(this);
  66390. if (this._isXboxOnePad) {
  66391. this.buttonA = this.browserGamepad.buttons[0].value;
  66392. this.buttonB = this.browserGamepad.buttons[1].value;
  66393. this.buttonX = this.browserGamepad.buttons[2].value;
  66394. this.buttonY = this.browserGamepad.buttons[3].value;
  66395. this.buttonLB = this.browserGamepad.buttons[4].value;
  66396. this.buttonRB = this.browserGamepad.buttons[5].value;
  66397. this.leftTrigger = this.browserGamepad.axes[2];
  66398. this.rightTrigger = this.browserGamepad.axes[5];
  66399. this.buttonBack = this.browserGamepad.buttons[9].value;
  66400. this.buttonStart = this.browserGamepad.buttons[8].value;
  66401. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  66402. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  66403. this.dPadUp = this.browserGamepad.buttons[11].value;
  66404. this.dPadDown = this.browserGamepad.buttons[12].value;
  66405. this.dPadLeft = this.browserGamepad.buttons[13].value;
  66406. this.dPadRight = this.browserGamepad.buttons[14].value;
  66407. }
  66408. else {
  66409. this.buttonA = this.browserGamepad.buttons[0].value;
  66410. this.buttonB = this.browserGamepad.buttons[1].value;
  66411. this.buttonX = this.browserGamepad.buttons[2].value;
  66412. this.buttonY = this.browserGamepad.buttons[3].value;
  66413. this.buttonLB = this.browserGamepad.buttons[4].value;
  66414. this.buttonRB = this.browserGamepad.buttons[5].value;
  66415. this.leftTrigger = this.browserGamepad.buttons[6].value;
  66416. this.rightTrigger = this.browserGamepad.buttons[7].value;
  66417. this.buttonBack = this.browserGamepad.buttons[8].value;
  66418. this.buttonStart = this.browserGamepad.buttons[9].value;
  66419. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  66420. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  66421. this.dPadUp = this.browserGamepad.buttons[12].value;
  66422. this.dPadDown = this.browserGamepad.buttons[13].value;
  66423. this.dPadLeft = this.browserGamepad.buttons[14].value;
  66424. this.dPadRight = this.browserGamepad.buttons[15].value;
  66425. }
  66426. };
  66427. Xbox360Pad.prototype.dispose = function () {
  66428. _super.prototype.dispose.call(this);
  66429. this.onButtonDownObservable.clear();
  66430. this.onButtonUpObservable.clear();
  66431. this.onPadDownObservable.clear();
  66432. this.onPadUpObservable.clear();
  66433. };
  66434. return Xbox360Pad;
  66435. }(BABYLON.Gamepad));
  66436. BABYLON.Xbox360Pad = Xbox360Pad;
  66437. })(BABYLON || (BABYLON = {}));
  66438. //# sourceMappingURL=babylon.xboxGamepad.js.map
  66439. "use strict";
  66440. var BABYLON;
  66441. (function (BABYLON) {
  66442. var PoseEnabledControllerType;
  66443. (function (PoseEnabledControllerType) {
  66444. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  66445. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  66446. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  66447. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  66448. /**
  66449. * Google Daydream
  66450. */
  66451. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  66452. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  66453. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  66454. var PoseEnabledControllerHelper = /** @class */ (function () {
  66455. function PoseEnabledControllerHelper() {
  66456. }
  66457. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  66458. // Oculus Touch
  66459. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  66460. return new BABYLON.OculusTouchController(vrGamepad);
  66461. }
  66462. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  66463. return new BABYLON.WindowsMotionController(vrGamepad);
  66464. }
  66465. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  66466. return new BABYLON.ViveController(vrGamepad);
  66467. }
  66468. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  66469. return new BABYLON.GearVRController(vrGamepad);
  66470. }
  66471. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  66472. return new BABYLON.DaydreamController(vrGamepad);
  66473. }
  66474. else {
  66475. return new BABYLON.GenericController(vrGamepad);
  66476. }
  66477. };
  66478. return PoseEnabledControllerHelper;
  66479. }());
  66480. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  66481. var PoseEnabledController = /** @class */ (function (_super) {
  66482. __extends(PoseEnabledController, _super);
  66483. function PoseEnabledController(browserGamepad) {
  66484. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  66485. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  66486. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  66487. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  66488. // Represents device position and rotation in babylon space
  66489. _this.devicePosition = BABYLON.Vector3.Zero();
  66490. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  66491. _this.deviceScaleFactor = 1;
  66492. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  66493. _this._deviceToWorld = BABYLON.Matrix.Identity();
  66494. /**
  66495. * Node to be used when casting a ray from the controller
  66496. */
  66497. _this._pointingPoseNode = null;
  66498. _this._workingMatrix = BABYLON.Matrix.Identity();
  66499. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  66500. _this.controllerType = PoseEnabledControllerType.GENERIC;
  66501. _this.position = BABYLON.Vector3.Zero();
  66502. _this.rotationQuaternion = new BABYLON.Quaternion();
  66503. _this._calculatedPosition = BABYLON.Vector3.Zero();
  66504. _this._calculatedRotation = new BABYLON.Quaternion();
  66505. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  66506. return _this;
  66507. }
  66508. PoseEnabledController.prototype.update = function () {
  66509. _super.prototype.update.call(this);
  66510. var pose = this.browserGamepad.pose;
  66511. this.updateFromDevice(pose);
  66512. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  66513. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  66514. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  66515. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  66516. if (this._mesh) {
  66517. this._mesh.position.copyFrom(this.devicePosition);
  66518. if (this._mesh.rotationQuaternion) {
  66519. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  66520. }
  66521. }
  66522. };
  66523. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  66524. if (poseData) {
  66525. this.rawPose = poseData;
  66526. if (poseData.position) {
  66527. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  66528. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  66529. this._deviceRoomPosition.z *= -1;
  66530. }
  66531. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  66532. this._calculatedPosition.addInPlace(this.position);
  66533. }
  66534. var pose = this.rawPose;
  66535. if (poseData.orientation && pose.orientation) {
  66536. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  66537. if (this._mesh) {
  66538. if (this._mesh.getScene().useRightHandedSystem) {
  66539. this._deviceRoomRotationQuaternion.z *= -1;
  66540. this._deviceRoomRotationQuaternion.w *= -1;
  66541. }
  66542. else {
  66543. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  66544. }
  66545. }
  66546. // if the camera is set, rotate to the camera's rotation
  66547. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  66548. }
  66549. }
  66550. };
  66551. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  66552. if (this._mesh) {
  66553. this._mesh.parent = null;
  66554. }
  66555. this._mesh = mesh;
  66556. if (this._poseControlledCamera) {
  66557. this._mesh.parent = this._poseControlledCamera;
  66558. }
  66559. if (!this._mesh.rotationQuaternion) {
  66560. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  66561. }
  66562. };
  66563. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  66564. this._poseControlledCamera = camera;
  66565. if (this._mesh) {
  66566. this._mesh.parent = this._poseControlledCamera;
  66567. }
  66568. };
  66569. PoseEnabledController.prototype.dispose = function () {
  66570. if (this._mesh) {
  66571. this._mesh.dispose();
  66572. }
  66573. this._mesh = null;
  66574. _super.prototype.dispose.call(this);
  66575. };
  66576. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  66577. get: function () {
  66578. return this._mesh;
  66579. },
  66580. enumerable: true,
  66581. configurable: true
  66582. });
  66583. PoseEnabledController.prototype.getForwardRay = function (length) {
  66584. if (length === void 0) { length = 100; }
  66585. if (!this.mesh) {
  66586. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  66587. }
  66588. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  66589. var origin = m.getTranslation();
  66590. var forward = new BABYLON.Vector3(0, 0, -1);
  66591. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  66592. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  66593. return new BABYLON.Ray(origin, direction, length);
  66594. };
  66595. /**
  66596. * Name of the child mesh that can be used to cast a ray from the controller
  66597. */
  66598. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  66599. return PoseEnabledController;
  66600. }(BABYLON.Gamepad));
  66601. BABYLON.PoseEnabledController = PoseEnabledController;
  66602. })(BABYLON || (BABYLON = {}));
  66603. //# sourceMappingURL=babylon.poseEnabledController.js.map
  66604. "use strict";
  66605. var BABYLON;
  66606. (function (BABYLON) {
  66607. var WebVRController = /** @class */ (function (_super) {
  66608. __extends(WebVRController, _super);
  66609. function WebVRController(vrGamepad) {
  66610. var _this = _super.call(this, vrGamepad) || this;
  66611. // Observables
  66612. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  66613. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  66614. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  66615. _this.onPadStateChangedObservable = new BABYLON.Observable();
  66616. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  66617. _this.pad = { x: 0, y: 0 };
  66618. // avoid GC, store state in a tmp object
  66619. _this._changes = {
  66620. pressChanged: false,
  66621. touchChanged: false,
  66622. valueChanged: false,
  66623. changed: false
  66624. };
  66625. _this._buttons = new Array(vrGamepad.buttons.length);
  66626. _this.hand = vrGamepad.hand;
  66627. return _this;
  66628. }
  66629. WebVRController.prototype.onButtonStateChange = function (callback) {
  66630. this._onButtonStateChange = callback;
  66631. };
  66632. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  66633. get: function () {
  66634. return this._defaultModel;
  66635. },
  66636. enumerable: true,
  66637. configurable: true
  66638. });
  66639. WebVRController.prototype.update = function () {
  66640. _super.prototype.update.call(this);
  66641. for (var index = 0; index < this._buttons.length; index++) {
  66642. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  66643. }
  66644. ;
  66645. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  66646. this.pad.x = this.leftStick.x;
  66647. this.pad.y = this.leftStick.y;
  66648. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  66649. }
  66650. };
  66651. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  66652. if (!newState) {
  66653. newState = {
  66654. pressed: false,
  66655. touched: false,
  66656. value: 0
  66657. };
  66658. }
  66659. if (!currentState) {
  66660. this._buttons[buttonIndex] = {
  66661. pressed: newState.pressed,
  66662. touched: newState.touched,
  66663. value: newState.value
  66664. };
  66665. return;
  66666. }
  66667. this._checkChanges(newState, currentState);
  66668. if (this._changes.changed) {
  66669. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  66670. this._handleButtonChange(buttonIndex, newState, this._changes);
  66671. }
  66672. this._buttons[buttonIndex].pressed = newState.pressed;
  66673. this._buttons[buttonIndex].touched = newState.touched;
  66674. // oculus triggers are never 0, thou not touched.
  66675. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  66676. };
  66677. WebVRController.prototype._checkChanges = function (newState, currentState) {
  66678. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  66679. this._changes.touchChanged = newState.touched !== currentState.touched;
  66680. this._changes.valueChanged = newState.value !== currentState.value;
  66681. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  66682. return this._changes;
  66683. };
  66684. WebVRController.prototype.dispose = function () {
  66685. _super.prototype.dispose.call(this);
  66686. this.onTriggerStateChangedObservable.clear();
  66687. this.onMainButtonStateChangedObservable.clear();
  66688. this.onSecondaryButtonStateChangedObservable.clear();
  66689. this.onPadStateChangedObservable.clear();
  66690. this.onPadValuesChangedObservable.clear();
  66691. };
  66692. return WebVRController;
  66693. }(BABYLON.PoseEnabledController));
  66694. BABYLON.WebVRController = WebVRController;
  66695. })(BABYLON || (BABYLON = {}));
  66696. //# sourceMappingURL=babylon.webVRController.js.map
  66697. "use strict";
  66698. var BABYLON;
  66699. (function (BABYLON) {
  66700. var OculusTouchController = /** @class */ (function (_super) {
  66701. __extends(OculusTouchController, _super);
  66702. function OculusTouchController(vrGamepad) {
  66703. var _this = _super.call(this, vrGamepad) || this;
  66704. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  66705. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  66706. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  66707. return _this;
  66708. }
  66709. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  66710. var _this = this;
  66711. var meshName;
  66712. // Hand
  66713. if (this.hand === 'left') {
  66714. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  66715. }
  66716. else {
  66717. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  66718. }
  66719. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  66720. /*
  66721. Parent Mesh name: oculus_touch_left
  66722. - body
  66723. - trigger
  66724. - thumbstick
  66725. - grip
  66726. - button_y
  66727. - button_x
  66728. - button_enter
  66729. */
  66730. _this._defaultModel = newMeshes[1];
  66731. _this.attachToMesh(_this._defaultModel);
  66732. if (meshLoaded) {
  66733. meshLoaded(_this._defaultModel);
  66734. }
  66735. });
  66736. };
  66737. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  66738. // helper getters for left and right hand.
  66739. get: function () {
  66740. if (this.hand === 'right') {
  66741. return this.onMainButtonStateChangedObservable;
  66742. }
  66743. else {
  66744. throw new Error('No A button on left hand');
  66745. }
  66746. },
  66747. enumerable: true,
  66748. configurable: true
  66749. });
  66750. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  66751. get: function () {
  66752. if (this.hand === 'right') {
  66753. return this.onSecondaryButtonStateChangedObservable;
  66754. }
  66755. else {
  66756. throw new Error('No B button on left hand');
  66757. }
  66758. },
  66759. enumerable: true,
  66760. configurable: true
  66761. });
  66762. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  66763. get: function () {
  66764. if (this.hand === 'left') {
  66765. return this.onMainButtonStateChangedObservable;
  66766. }
  66767. else {
  66768. throw new Error('No X button on right hand');
  66769. }
  66770. },
  66771. enumerable: true,
  66772. configurable: true
  66773. });
  66774. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  66775. get: function () {
  66776. if (this.hand === 'left') {
  66777. return this.onSecondaryButtonStateChangedObservable;
  66778. }
  66779. else {
  66780. throw new Error('No Y button on right hand');
  66781. }
  66782. },
  66783. enumerable: true,
  66784. configurable: true
  66785. });
  66786. /*
  66787. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  66788. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  66789. 2) secondary trigger (same)
  66790. 3) A (right) X (left), touch, pressed = value
  66791. 4) B / Y
  66792. 5) thumb rest
  66793. */
  66794. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  66795. var notifyObject = state; //{ state: state, changes: changes };
  66796. var triggerDirection = this.hand === 'right' ? -1 : 1;
  66797. switch (buttonIdx) {
  66798. case 0:
  66799. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  66800. return;
  66801. case 1:// index trigger
  66802. if (this._defaultModel) {
  66803. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  66804. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  66805. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  66806. }
  66807. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  66808. return;
  66809. case 2:// secondary trigger
  66810. if (this._defaultModel) {
  66811. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  66812. }
  66813. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  66814. return;
  66815. case 3:
  66816. if (this._defaultModel) {
  66817. if (notifyObject.pressed) {
  66818. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  66819. }
  66820. else {
  66821. (this._defaultModel.getChildren()[1]).position.y = 0;
  66822. }
  66823. }
  66824. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  66825. return;
  66826. case 4:
  66827. if (this._defaultModel) {
  66828. if (notifyObject.pressed) {
  66829. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  66830. }
  66831. else {
  66832. (this._defaultModel.getChildren()[2]).position.y = 0;
  66833. }
  66834. }
  66835. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  66836. return;
  66837. case 5:
  66838. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  66839. return;
  66840. }
  66841. };
  66842. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  66843. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  66844. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  66845. return OculusTouchController;
  66846. }(BABYLON.WebVRController));
  66847. BABYLON.OculusTouchController = OculusTouchController;
  66848. })(BABYLON || (BABYLON = {}));
  66849. //# sourceMappingURL=babylon.oculusTouchController.js.map
  66850. "use strict";
  66851. var BABYLON;
  66852. (function (BABYLON) {
  66853. var ViveController = /** @class */ (function (_super) {
  66854. __extends(ViveController, _super);
  66855. function ViveController(vrGamepad) {
  66856. var _this = _super.call(this, vrGamepad) || this;
  66857. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  66858. _this._invertLeftStickY = true;
  66859. return _this;
  66860. }
  66861. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  66862. var _this = this;
  66863. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  66864. /*
  66865. Parent Mesh name: ViveWand
  66866. - body
  66867. - r_gripper
  66868. - l_gripper
  66869. - menu_button
  66870. - system_button
  66871. - trackpad
  66872. - trigger
  66873. - LED
  66874. */
  66875. _this._defaultModel = newMeshes[1];
  66876. _this.attachToMesh(_this._defaultModel);
  66877. if (meshLoaded) {
  66878. meshLoaded(_this._defaultModel);
  66879. }
  66880. });
  66881. };
  66882. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  66883. get: function () {
  66884. return this.onMainButtonStateChangedObservable;
  66885. },
  66886. enumerable: true,
  66887. configurable: true
  66888. });
  66889. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  66890. get: function () {
  66891. return this.onMainButtonStateChangedObservable;
  66892. },
  66893. enumerable: true,
  66894. configurable: true
  66895. });
  66896. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  66897. get: function () {
  66898. return this.onSecondaryButtonStateChangedObservable;
  66899. },
  66900. enumerable: true,
  66901. configurable: true
  66902. });
  66903. /**
  66904. * Vive mapping:
  66905. * 0: touchpad
  66906. * 1: trigger
  66907. * 2: left AND right buttons
  66908. * 3: menu button
  66909. */
  66910. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  66911. var notifyObject = state; //{ state: state, changes: changes };
  66912. switch (buttonIdx) {
  66913. case 0:
  66914. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  66915. return;
  66916. case 1:// index trigger
  66917. if (this._defaultModel) {
  66918. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  66919. }
  66920. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  66921. return;
  66922. case 2:// left AND right button
  66923. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  66924. return;
  66925. case 3:
  66926. if (this._defaultModel) {
  66927. if (notifyObject.pressed) {
  66928. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  66929. }
  66930. else {
  66931. (this._defaultModel.getChildren()[2]).position.y = 0;
  66932. }
  66933. }
  66934. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  66935. return;
  66936. }
  66937. };
  66938. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  66939. ViveController.MODEL_FILENAME = 'wand.babylon';
  66940. return ViveController;
  66941. }(BABYLON.WebVRController));
  66942. BABYLON.ViveController = ViveController;
  66943. })(BABYLON || (BABYLON = {}));
  66944. //# sourceMappingURL=babylon.viveController.js.map
  66945. "use strict";
  66946. var BABYLON;
  66947. (function (BABYLON) {
  66948. var GenericController = /** @class */ (function (_super) {
  66949. __extends(GenericController, _super);
  66950. function GenericController(vrGamepad) {
  66951. return _super.call(this, vrGamepad) || this;
  66952. }
  66953. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  66954. var _this = this;
  66955. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  66956. _this._defaultModel = newMeshes[1];
  66957. _this.attachToMesh(_this._defaultModel);
  66958. if (meshLoaded) {
  66959. meshLoaded(_this._defaultModel);
  66960. }
  66961. });
  66962. };
  66963. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  66964. console.log("Button id: " + buttonIdx + "state: ");
  66965. console.dir(state);
  66966. };
  66967. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  66968. GenericController.MODEL_FILENAME = 'generic.babylon';
  66969. return GenericController;
  66970. }(BABYLON.WebVRController));
  66971. BABYLON.GenericController = GenericController;
  66972. })(BABYLON || (BABYLON = {}));
  66973. //# sourceMappingURL=babylon.genericController.js.map
  66974. "use strict";
  66975. var BABYLON;
  66976. (function (BABYLON) {
  66977. var LoadedMeshInfo = /** @class */ (function () {
  66978. function LoadedMeshInfo() {
  66979. this.buttonMeshes = {};
  66980. this.axisMeshes = {};
  66981. }
  66982. return LoadedMeshInfo;
  66983. }());
  66984. var WindowsMotionController = /** @class */ (function (_super) {
  66985. __extends(WindowsMotionController, _super);
  66986. function WindowsMotionController(vrGamepad) {
  66987. var _this = _super.call(this, vrGamepad) || this;
  66988. _this._mapping = {
  66989. // Semantic button names
  66990. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  66991. // A mapping of the button name to glTF model node name
  66992. // that should be transformed by button value.
  66993. buttonMeshNames: {
  66994. 'trigger': 'SELECT',
  66995. 'menu': 'MENU',
  66996. 'grip': 'GRASP',
  66997. 'thumbstick': 'THUMBSTICK_PRESS',
  66998. 'trackpad': 'TOUCHPAD_PRESS'
  66999. },
  67000. // This mapping is used to translate from the Motion Controller to Babylon semantics
  67001. buttonObservableNames: {
  67002. 'trigger': 'onTriggerStateChangedObservable',
  67003. 'menu': 'onSecondaryButtonStateChangedObservable',
  67004. 'grip': 'onMainButtonStateChangedObservable',
  67005. 'thumbstick': 'onPadStateChangedObservable',
  67006. 'trackpad': 'onTrackpadChangedObservable'
  67007. },
  67008. // A mapping of the axis name to glTF model node name
  67009. // that should be transformed by axis value.
  67010. // This array mirrors the browserGamepad.axes array, such that
  67011. // the mesh corresponding to axis 0 is in this array index 0.
  67012. axisMeshNames: [
  67013. 'THUMBSTICK_X',
  67014. 'THUMBSTICK_Y',
  67015. 'TOUCHPAD_TOUCH_X',
  67016. 'TOUCHPAD_TOUCH_Y'
  67017. ],
  67018. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  67019. };
  67020. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  67021. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  67022. _this.trackpad = { x: 0, y: 0 };
  67023. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  67024. _this._loadedMeshInfo = null;
  67025. return _this;
  67026. }
  67027. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  67028. get: function () {
  67029. return this.onTriggerStateChangedObservable;
  67030. },
  67031. enumerable: true,
  67032. configurable: true
  67033. });
  67034. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  67035. get: function () {
  67036. return this.onSecondaryButtonStateChangedObservable;
  67037. },
  67038. enumerable: true,
  67039. configurable: true
  67040. });
  67041. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  67042. get: function () {
  67043. return this.onMainButtonStateChangedObservable;
  67044. },
  67045. enumerable: true,
  67046. configurable: true
  67047. });
  67048. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  67049. get: function () {
  67050. return this.onPadStateChangedObservable;
  67051. },
  67052. enumerable: true,
  67053. configurable: true
  67054. });
  67055. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  67056. get: function () {
  67057. return this.onTrackpadChangedObservable;
  67058. },
  67059. enumerable: true,
  67060. configurable: true
  67061. });
  67062. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  67063. get: function () {
  67064. return this.onTrackpadValuesChangedObservable;
  67065. },
  67066. enumerable: true,
  67067. configurable: true
  67068. });
  67069. /**
  67070. * Called once per frame by the engine.
  67071. */
  67072. WindowsMotionController.prototype.update = function () {
  67073. _super.prototype.update.call(this);
  67074. if (this.browserGamepad.axes) {
  67075. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  67076. this.trackpad.x = this.browserGamepad["axes"][2];
  67077. this.trackpad.y = this.browserGamepad["axes"][3];
  67078. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  67079. }
  67080. // Only need to animate axes if there is a loaded mesh
  67081. if (this._loadedMeshInfo) {
  67082. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  67083. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  67084. }
  67085. }
  67086. }
  67087. };
  67088. /**
  67089. * Called once for each button that changed state since the last frame
  67090. * @param buttonIdx Which button index changed
  67091. * @param state New state of the button
  67092. * @param changes Which properties on the state changed since last frame
  67093. */
  67094. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  67095. var buttonName = this._mapping.buttons[buttonIdx];
  67096. if (!buttonName) {
  67097. return;
  67098. }
  67099. // Only emit events for buttons that we know how to map from index to name
  67100. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  67101. if (observable) {
  67102. observable.notifyObservers(state);
  67103. }
  67104. this.lerpButtonTransform(buttonName, state.value);
  67105. };
  67106. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  67107. // If there is no loaded mesh, there is nothing to transform.
  67108. if (!this._loadedMeshInfo) {
  67109. return;
  67110. }
  67111. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  67112. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  67113. return;
  67114. }
  67115. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  67116. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  67117. };
  67118. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  67119. if (!this._loadedMeshInfo) {
  67120. return;
  67121. }
  67122. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  67123. if (!meshInfo) {
  67124. return;
  67125. }
  67126. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  67127. return;
  67128. }
  67129. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  67130. var lerpValue = axisValue * 0.5 + 0.5;
  67131. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  67132. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  67133. };
  67134. /**
  67135. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  67136. * @param scene scene in which to add meshes
  67137. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  67138. */
  67139. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  67140. var _this = this;
  67141. if (forceDefault === void 0) { forceDefault = false; }
  67142. var path;
  67143. var filename;
  67144. // Checking if GLB loader is present
  67145. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  67146. // Determine the device specific folder based on the ID suffix
  67147. var device = 'default';
  67148. if (this.id && !forceDefault) {
  67149. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  67150. device = ((match && match[0]) || device);
  67151. }
  67152. // Hand
  67153. if (this.hand === 'left') {
  67154. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  67155. }
  67156. else {
  67157. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  67158. }
  67159. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  67160. }
  67161. else {
  67162. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  67163. path = BABYLON.GenericController.MODEL_BASE_URL;
  67164. filename = BABYLON.GenericController.MODEL_FILENAME;
  67165. }
  67166. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  67167. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  67168. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  67169. if (!_this._loadedMeshInfo) {
  67170. return;
  67171. }
  67172. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  67173. _this.attachToMesh(_this._defaultModel);
  67174. if (meshLoaded) {
  67175. meshLoaded(_this._defaultModel);
  67176. }
  67177. }, null, function (scene, message) {
  67178. BABYLON.Tools.Log(message);
  67179. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  67180. if (!forceDefault) {
  67181. _this.initControllerMesh(scene, meshLoaded, true);
  67182. }
  67183. });
  67184. };
  67185. /**
  67186. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  67187. * can be transformed by button presses and axes values, based on this._mapping.
  67188. *
  67189. * @param scene scene in which the meshes exist
  67190. * @param meshes list of meshes that make up the controller model to process
  67191. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  67192. */
  67193. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  67194. var loadedMeshInfo = null;
  67195. // Create a new mesh to contain the glTF hierarchy
  67196. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  67197. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  67198. var childMesh = null;
  67199. for (var i = 0; i < meshes.length; i++) {
  67200. var mesh = meshes[i];
  67201. if (!mesh.parent) {
  67202. // Exclude controller meshes from picking results
  67203. mesh.isPickable = false;
  67204. // Handle root node, attach to the new parentMesh
  67205. childMesh = mesh;
  67206. break;
  67207. }
  67208. }
  67209. if (childMesh) {
  67210. childMesh.setParent(parentMesh);
  67211. // Create our mesh info. Note that this method will always return non-null.
  67212. loadedMeshInfo = this.createMeshInfo(parentMesh);
  67213. }
  67214. else {
  67215. BABYLON.Tools.Warn('Could not find root node in model file.');
  67216. }
  67217. return loadedMeshInfo;
  67218. };
  67219. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  67220. var loadedMeshInfo = new LoadedMeshInfo();
  67221. var i;
  67222. loadedMeshInfo.rootNode = rootNode;
  67223. // Reset the caches
  67224. loadedMeshInfo.buttonMeshes = {};
  67225. loadedMeshInfo.axisMeshes = {};
  67226. // Button Meshes
  67227. for (i = 0; i < this._mapping.buttons.length; i++) {
  67228. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  67229. if (!buttonMeshName) {
  67230. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  67231. continue;
  67232. }
  67233. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  67234. if (!buttonMesh) {
  67235. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  67236. continue;
  67237. }
  67238. var buttonMeshInfo = {
  67239. index: i,
  67240. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  67241. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  67242. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  67243. };
  67244. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  67245. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  67246. }
  67247. else {
  67248. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  67249. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  67250. '(VALUE: ' + !!buttonMeshInfo.value +
  67251. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  67252. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  67253. ')');
  67254. }
  67255. }
  67256. // Axis Meshes
  67257. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  67258. var axisMeshName = this._mapping.axisMeshNames[i];
  67259. if (!axisMeshName) {
  67260. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  67261. continue;
  67262. }
  67263. var axisMesh = getChildByName(rootNode, axisMeshName);
  67264. if (!axisMesh) {
  67265. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  67266. continue;
  67267. }
  67268. var axisMeshInfo = {
  67269. index: i,
  67270. value: getImmediateChildByName(axisMesh, 'VALUE'),
  67271. min: getImmediateChildByName(axisMesh, 'MIN'),
  67272. max: getImmediateChildByName(axisMesh, 'MAX')
  67273. };
  67274. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  67275. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  67276. }
  67277. else {
  67278. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  67279. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  67280. '(VALUE: ' + !!axisMeshInfo.value +
  67281. ', MIN: ' + !!axisMeshInfo.min +
  67282. ', MAX:' + !!axisMeshInfo.max +
  67283. ')');
  67284. }
  67285. }
  67286. // Pointing Ray
  67287. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  67288. if (!loadedMeshInfo.pointingPoseNode) {
  67289. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  67290. }
  67291. return loadedMeshInfo;
  67292. // Look through all children recursively. This will return null if no mesh exists with the given name.
  67293. function getChildByName(node, name) {
  67294. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  67295. }
  67296. // Look through only immediate children. This will return null if no mesh exists with the given name.
  67297. function getImmediateChildByName(node, name) {
  67298. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  67299. }
  67300. };
  67301. WindowsMotionController.prototype.getForwardRay = function (length) {
  67302. if (length === void 0) { length = 100; }
  67303. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  67304. return _super.prototype.getForwardRay.call(this, length);
  67305. }
  67306. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  67307. var origin = m.getTranslation();
  67308. var forward = new BABYLON.Vector3(0, 0, -1);
  67309. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  67310. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  67311. return new BABYLON.Ray(origin, direction, length);
  67312. };
  67313. WindowsMotionController.prototype.dispose = function () {
  67314. _super.prototype.dispose.call(this);
  67315. this.onTrackpadChangedObservable.clear();
  67316. };
  67317. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  67318. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  67319. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  67320. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  67321. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  67322. return WindowsMotionController;
  67323. }(BABYLON.WebVRController));
  67324. BABYLON.WindowsMotionController = WindowsMotionController;
  67325. })(BABYLON || (BABYLON = {}));
  67326. //# sourceMappingURL=babylon.windowsMotionController.js.map
  67327. "use strict";
  67328. var BABYLON;
  67329. (function (BABYLON) {
  67330. var GearVRController = /** @class */ (function (_super) {
  67331. __extends(GearVRController, _super);
  67332. function GearVRController(vrGamepad) {
  67333. var _this = _super.call(this, vrGamepad) || this;
  67334. _this._buttonIndexToObservableNameMap = [
  67335. 'onTrackpadChangedObservable',
  67336. 'onTriggerStateChangedObservable' // Trigger
  67337. ];
  67338. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  67339. return _this;
  67340. }
  67341. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  67342. var _this = this;
  67343. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  67344. _this._defaultModel = newMeshes[1];
  67345. _this.attachToMesh(_this._defaultModel);
  67346. if (meshLoaded) {
  67347. meshLoaded(_this._defaultModel);
  67348. }
  67349. });
  67350. };
  67351. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  67352. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  67353. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  67354. // Only emit events for buttons that we know how to map from index to observable
  67355. var observable = this[observableName];
  67356. if (observable) {
  67357. observable.notifyObservers(state);
  67358. }
  67359. }
  67360. };
  67361. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  67362. GearVRController.MODEL_FILENAME = 'generic.babylon';
  67363. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  67364. return GearVRController;
  67365. }(BABYLON.WebVRController));
  67366. BABYLON.GearVRController = GearVRController;
  67367. })(BABYLON || (BABYLON = {}));
  67368. //# sourceMappingURL=babylon.gearVRController.js.map
  67369. "use strict";
  67370. var BABYLON;
  67371. (function (BABYLON) {
  67372. /**
  67373. * Google Daydream controller
  67374. */
  67375. var DaydreamController = /** @class */ (function (_super) {
  67376. __extends(DaydreamController, _super);
  67377. function DaydreamController(vrGamepad) {
  67378. var _this = _super.call(this, vrGamepad) || this;
  67379. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  67380. return _this;
  67381. }
  67382. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  67383. var _this = this;
  67384. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  67385. _this._defaultModel = newMeshes[1];
  67386. _this.attachToMesh(_this._defaultModel);
  67387. if (meshLoaded) {
  67388. meshLoaded(_this._defaultModel);
  67389. }
  67390. });
  67391. };
  67392. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  67393. // Daydream controller only has 1 GamepadButton (on the trackpad).
  67394. if (buttonIdx === 0) {
  67395. var observable = this.onTriggerStateChangedObservable;
  67396. if (observable) {
  67397. observable.notifyObservers(state);
  67398. }
  67399. }
  67400. else {
  67401. // If the app or home buttons are ever made available
  67402. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  67403. }
  67404. };
  67405. /**
  67406. * Base Url for the controller model.
  67407. */
  67408. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  67409. /**
  67410. * File name for the controller model.
  67411. */
  67412. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  67413. /**
  67414. * Gamepad Id prefix used to identify Daydream Controller.
  67415. */
  67416. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  67417. return DaydreamController;
  67418. }(BABYLON.WebVRController));
  67419. BABYLON.DaydreamController = DaydreamController;
  67420. })(BABYLON || (BABYLON = {}));
  67421. //# sourceMappingURL=babylon.daydreamController.js.map
  67422. "use strict";
  67423. var BABYLON;
  67424. (function (BABYLON) {
  67425. var FollowCamera = /** @class */ (function (_super) {
  67426. __extends(FollowCamera, _super);
  67427. function FollowCamera(name, position, scene, lockedTarget) {
  67428. if (lockedTarget === void 0) { lockedTarget = null; }
  67429. var _this = _super.call(this, name, position, scene) || this;
  67430. _this.radius = 12;
  67431. _this.rotationOffset = 0;
  67432. _this.heightOffset = 4;
  67433. _this.cameraAcceleration = 0.05;
  67434. _this.maxCameraSpeed = 20;
  67435. _this.lockedTarget = lockedTarget;
  67436. return _this;
  67437. }
  67438. FollowCamera.prototype.getRadians = function (degrees) {
  67439. return degrees * Math.PI / 180;
  67440. };
  67441. FollowCamera.prototype.follow = function (cameraTarget) {
  67442. if (!cameraTarget)
  67443. return;
  67444. var yRotation;
  67445. if (cameraTarget.rotationQuaternion) {
  67446. var rotMatrix = new BABYLON.Matrix();
  67447. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  67448. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  67449. }
  67450. else {
  67451. yRotation = cameraTarget.rotation.y;
  67452. }
  67453. var radians = this.getRadians(this.rotationOffset) + yRotation;
  67454. var targetPosition = cameraTarget.getAbsolutePosition();
  67455. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  67456. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  67457. var dx = targetX - this.position.x;
  67458. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  67459. var dz = (targetZ) - this.position.z;
  67460. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  67461. var vy = dy * this.cameraAcceleration;
  67462. var vz = dz * this.cameraAcceleration * 2;
  67463. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  67464. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  67465. }
  67466. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  67467. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  67468. }
  67469. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  67470. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  67471. }
  67472. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  67473. this.setTarget(targetPosition);
  67474. };
  67475. FollowCamera.prototype._checkInputs = function () {
  67476. _super.prototype._checkInputs.call(this);
  67477. if (this.lockedTarget) {
  67478. this.follow(this.lockedTarget);
  67479. }
  67480. };
  67481. FollowCamera.prototype.getClassName = function () {
  67482. return "FollowCamera";
  67483. };
  67484. __decorate([
  67485. BABYLON.serialize()
  67486. ], FollowCamera.prototype, "radius", void 0);
  67487. __decorate([
  67488. BABYLON.serialize()
  67489. ], FollowCamera.prototype, "rotationOffset", void 0);
  67490. __decorate([
  67491. BABYLON.serialize()
  67492. ], FollowCamera.prototype, "heightOffset", void 0);
  67493. __decorate([
  67494. BABYLON.serialize()
  67495. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  67496. __decorate([
  67497. BABYLON.serialize()
  67498. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  67499. __decorate([
  67500. BABYLON.serializeAsMeshReference("lockedTargetId")
  67501. ], FollowCamera.prototype, "lockedTarget", void 0);
  67502. return FollowCamera;
  67503. }(BABYLON.TargetCamera));
  67504. BABYLON.FollowCamera = FollowCamera;
  67505. var ArcFollowCamera = /** @class */ (function (_super) {
  67506. __extends(ArcFollowCamera, _super);
  67507. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  67508. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  67509. _this.alpha = alpha;
  67510. _this.beta = beta;
  67511. _this.radius = radius;
  67512. _this.target = target;
  67513. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  67514. _this.follow();
  67515. return _this;
  67516. }
  67517. ArcFollowCamera.prototype.follow = function () {
  67518. if (!this.target) {
  67519. return;
  67520. }
  67521. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  67522. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  67523. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  67524. var targetPosition = this.target.getAbsolutePosition();
  67525. this.position = targetPosition.add(this._cartesianCoordinates);
  67526. this.setTarget(targetPosition);
  67527. };
  67528. ArcFollowCamera.prototype._checkInputs = function () {
  67529. _super.prototype._checkInputs.call(this);
  67530. this.follow();
  67531. };
  67532. ArcFollowCamera.prototype.getClassName = function () {
  67533. return "ArcFollowCamera";
  67534. };
  67535. return ArcFollowCamera;
  67536. }(BABYLON.TargetCamera));
  67537. BABYLON.ArcFollowCamera = ArcFollowCamera;
  67538. })(BABYLON || (BABYLON = {}));
  67539. //# sourceMappingURL=babylon.followCamera.js.map
  67540. "use strict";
  67541. var BABYLON;
  67542. (function (BABYLON) {
  67543. // We're mainly based on the logic defined into the FreeCamera code
  67544. var UniversalCamera = /** @class */ (function (_super) {
  67545. __extends(UniversalCamera, _super);
  67546. //-- end properties for backward compatibility for inputs
  67547. function UniversalCamera(name, position, scene) {
  67548. var _this = _super.call(this, name, position, scene) || this;
  67549. _this.inputs.addGamepad();
  67550. return _this;
  67551. }
  67552. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  67553. //-- Begin properties for backward compatibility for inputs
  67554. get: function () {
  67555. var gamepad = this.inputs.attached["gamepad"];
  67556. if (gamepad)
  67557. return gamepad.gamepadAngularSensibility;
  67558. return 0;
  67559. },
  67560. set: function (value) {
  67561. var gamepad = this.inputs.attached["gamepad"];
  67562. if (gamepad)
  67563. gamepad.gamepadAngularSensibility = value;
  67564. },
  67565. enumerable: true,
  67566. configurable: true
  67567. });
  67568. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  67569. get: function () {
  67570. var gamepad = this.inputs.attached["gamepad"];
  67571. if (gamepad)
  67572. return gamepad.gamepadMoveSensibility;
  67573. return 0;
  67574. },
  67575. set: function (value) {
  67576. var gamepad = this.inputs.attached["gamepad"];
  67577. if (gamepad)
  67578. gamepad.gamepadMoveSensibility = value;
  67579. },
  67580. enumerable: true,
  67581. configurable: true
  67582. });
  67583. UniversalCamera.prototype.getClassName = function () {
  67584. return "UniversalCamera";
  67585. };
  67586. return UniversalCamera;
  67587. }(BABYLON.TouchCamera));
  67588. BABYLON.UniversalCamera = UniversalCamera;
  67589. })(BABYLON || (BABYLON = {}));
  67590. //# sourceMappingURL=babylon.universalCamera.js.map
  67591. "use strict";
  67592. var BABYLON;
  67593. (function (BABYLON) {
  67594. // We're mainly based on the logic defined into the FreeCamera code
  67595. var GamepadCamera = /** @class */ (function (_super) {
  67596. __extends(GamepadCamera, _super);
  67597. //-- end properties for backward compatibility for inputs
  67598. function GamepadCamera(name, position, scene) {
  67599. return _super.call(this, name, position, scene) || this;
  67600. }
  67601. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  67602. //-- Begin properties for backward compatibility for inputs
  67603. get: function () {
  67604. var gamepad = this.inputs.attached["gamepad"];
  67605. if (gamepad)
  67606. return gamepad.gamepadAngularSensibility;
  67607. return 0;
  67608. },
  67609. set: function (value) {
  67610. var gamepad = this.inputs.attached["gamepad"];
  67611. if (gamepad)
  67612. gamepad.gamepadAngularSensibility = value;
  67613. },
  67614. enumerable: true,
  67615. configurable: true
  67616. });
  67617. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  67618. get: function () {
  67619. var gamepad = this.inputs.attached["gamepad"];
  67620. if (gamepad)
  67621. return gamepad.gamepadMoveSensibility;
  67622. return 0;
  67623. },
  67624. set: function (value) {
  67625. var gamepad = this.inputs.attached["gamepad"];
  67626. if (gamepad)
  67627. gamepad.gamepadMoveSensibility = value;
  67628. },
  67629. enumerable: true,
  67630. configurable: true
  67631. });
  67632. GamepadCamera.prototype.getClassName = function () {
  67633. return "GamepadCamera";
  67634. };
  67635. return GamepadCamera;
  67636. }(BABYLON.UniversalCamera));
  67637. BABYLON.GamepadCamera = GamepadCamera;
  67638. })(BABYLON || (BABYLON = {}));
  67639. //# sourceMappingURL=babylon.gamepadCamera.js.map
  67640. "use strict";
  67641. var BABYLON;
  67642. (function (BABYLON) {
  67643. var PostProcessRenderPipelineManager = /** @class */ (function () {
  67644. function PostProcessRenderPipelineManager() {
  67645. this._renderPipelines = {};
  67646. }
  67647. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  67648. this._renderPipelines[renderPipeline._name] = renderPipeline;
  67649. };
  67650. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  67651. if (unique === void 0) { unique = false; }
  67652. var renderPipeline = this._renderPipelines[renderPipelineName];
  67653. if (!renderPipeline) {
  67654. return;
  67655. }
  67656. renderPipeline._attachCameras(cameras, unique);
  67657. };
  67658. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  67659. var renderPipeline = this._renderPipelines[renderPipelineName];
  67660. if (!renderPipeline) {
  67661. return;
  67662. }
  67663. renderPipeline._detachCameras(cameras);
  67664. };
  67665. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  67666. var renderPipeline = this._renderPipelines[renderPipelineName];
  67667. if (!renderPipeline) {
  67668. return;
  67669. }
  67670. renderPipeline._enableEffect(renderEffectName, cameras);
  67671. };
  67672. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  67673. var renderPipeline = this._renderPipelines[renderPipelineName];
  67674. if (!renderPipeline) {
  67675. return;
  67676. }
  67677. renderPipeline._disableEffect(renderEffectName, cameras);
  67678. };
  67679. PostProcessRenderPipelineManager.prototype.update = function () {
  67680. for (var renderPipelineName in this._renderPipelines) {
  67681. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  67682. var pipeline = this._renderPipelines[renderPipelineName];
  67683. if (!pipeline.isSupported) {
  67684. pipeline.dispose();
  67685. delete this._renderPipelines[renderPipelineName];
  67686. }
  67687. else {
  67688. pipeline._update();
  67689. }
  67690. }
  67691. }
  67692. };
  67693. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  67694. for (var renderPipelineName in this._renderPipelines) {
  67695. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  67696. var pipeline = this._renderPipelines[renderPipelineName];
  67697. pipeline._rebuild();
  67698. }
  67699. }
  67700. };
  67701. PostProcessRenderPipelineManager.prototype.dispose = function () {
  67702. for (var renderPipelineName in this._renderPipelines) {
  67703. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  67704. var pipeline = this._renderPipelines[renderPipelineName];
  67705. pipeline.dispose();
  67706. }
  67707. }
  67708. };
  67709. return PostProcessRenderPipelineManager;
  67710. }());
  67711. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  67712. })(BABYLON || (BABYLON = {}));
  67713. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  67714. "use strict";
  67715. var BABYLON;
  67716. (function (BABYLON) {
  67717. /**
  67718. * This represents a set of one or more post processes in Babylon.
  67719. * A post process can be used to apply a shader to a texture after it is rendered.
  67720. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  67721. */
  67722. var PostProcessRenderEffect = /** @class */ (function () {
  67723. /**
  67724. * Instantiates a post process render effect.
  67725. * A post process can be used to apply a shader to a texture after it is rendered.
  67726. * @param engine The engine the effect is tied to
  67727. * @param name The name of the effect
  67728. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  67729. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  67730. */
  67731. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  67732. this._name = name;
  67733. this._singleInstance = singleInstance || true;
  67734. this._getPostProcesses = getPostProcesses;
  67735. this._cameras = {};
  67736. this._indicesForCamera = {};
  67737. this._postProcesses = {};
  67738. }
  67739. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  67740. /**
  67741. * Checks if all the post processes in the effect are supported.
  67742. */
  67743. get: function () {
  67744. for (var index in this._postProcesses) {
  67745. for (var ppIndex in this._postProcesses[index]) {
  67746. if (!this._postProcesses[index][ppIndex].isSupported) {
  67747. return false;
  67748. }
  67749. }
  67750. }
  67751. return true;
  67752. },
  67753. enumerable: true,
  67754. configurable: true
  67755. });
  67756. /**
  67757. * Updates the current state of the effect
  67758. */
  67759. PostProcessRenderEffect.prototype._update = function () {
  67760. };
  67761. /**
  67762. * Attaches the effect on cameras
  67763. * @param cameras The camera to attach to.
  67764. */
  67765. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  67766. var _this = this;
  67767. var cameraKey;
  67768. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  67769. if (!cams) {
  67770. return;
  67771. }
  67772. for (var i = 0; i < cams.length; i++) {
  67773. var camera = cams[i];
  67774. var cameraName = camera.name;
  67775. if (this._singleInstance) {
  67776. cameraKey = 0;
  67777. }
  67778. else {
  67779. cameraKey = cameraName;
  67780. }
  67781. if (!this._postProcesses[cameraKey]) {
  67782. var postProcess = this._getPostProcesses();
  67783. if (postProcess) {
  67784. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  67785. }
  67786. }
  67787. if (!this._indicesForCamera[cameraName]) {
  67788. this._indicesForCamera[cameraName] = [];
  67789. }
  67790. this._postProcesses[cameraKey].forEach(function (postProcess) {
  67791. var index = camera.attachPostProcess(postProcess);
  67792. _this._indicesForCamera[cameraName].push(index);
  67793. });
  67794. if (!this._cameras[cameraName]) {
  67795. this._cameras[cameraName] = camera;
  67796. }
  67797. }
  67798. };
  67799. /**
  67800. * Detatches the effect on cameras
  67801. * @param cameras The camera to detatch from.
  67802. */
  67803. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  67804. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  67805. if (!cams) {
  67806. return;
  67807. }
  67808. for (var i = 0; i < cams.length; i++) {
  67809. var camera = cams[i];
  67810. var cameraName = camera.name;
  67811. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  67812. camera.detachPostProcess(postProcess);
  67813. });
  67814. if (this._cameras[cameraName]) {
  67815. //this._indicesForCamera.splice(index, 1);
  67816. this._cameras[cameraName] = null;
  67817. }
  67818. }
  67819. };
  67820. /**
  67821. * Enables the effect on given cameras
  67822. * @param cameras The camera to enable.
  67823. */
  67824. PostProcessRenderEffect.prototype._enable = function (cameras) {
  67825. var _this = this;
  67826. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  67827. if (!cams) {
  67828. return;
  67829. }
  67830. for (var i = 0; i < cams.length; i++) {
  67831. var camera = cams[i];
  67832. var cameraName = camera.name;
  67833. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  67834. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  67835. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  67836. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  67837. });
  67838. }
  67839. }
  67840. }
  67841. };
  67842. /**
  67843. * Disables the effect on the given cameras
  67844. * @param cameras The camera to disable.
  67845. */
  67846. PostProcessRenderEffect.prototype._disable = function (cameras) {
  67847. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  67848. if (!cams) {
  67849. return;
  67850. }
  67851. for (var i = 0; i < cams.length; i++) {
  67852. var camera = cams[i];
  67853. var cameraName = camera.name;
  67854. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  67855. camera.detachPostProcess(postProcess);
  67856. });
  67857. }
  67858. };
  67859. /**
  67860. * Gets a list of the post processes contained in the effect.
  67861. * @param camera The camera to get the post processes on.
  67862. * @returns The list of the post processes in the effect.
  67863. */
  67864. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  67865. if (this._singleInstance) {
  67866. return this._postProcesses[0];
  67867. }
  67868. else {
  67869. if (!camera) {
  67870. return null;
  67871. }
  67872. return this._postProcesses[camera.name];
  67873. }
  67874. };
  67875. return PostProcessRenderEffect;
  67876. }());
  67877. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  67878. })(BABYLON || (BABYLON = {}));
  67879. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  67880. "use strict";
  67881. var BABYLON;
  67882. (function (BABYLON) {
  67883. var PostProcessRenderPipeline = /** @class */ (function () {
  67884. function PostProcessRenderPipeline(engine, name) {
  67885. this.engine = engine;
  67886. this._name = name;
  67887. this._renderEffects = {};
  67888. this._renderEffectsForIsolatedPass = new Array();
  67889. this._cameras = [];
  67890. }
  67891. PostProcessRenderPipeline.prototype.getClassName = function () {
  67892. return "PostProcessRenderPipeline";
  67893. };
  67894. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  67895. get: function () {
  67896. for (var renderEffectName in this._renderEffects) {
  67897. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  67898. if (!this._renderEffects[renderEffectName].isSupported) {
  67899. return false;
  67900. }
  67901. }
  67902. }
  67903. return true;
  67904. },
  67905. enumerable: true,
  67906. configurable: true
  67907. });
  67908. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  67909. this._renderEffects[renderEffect._name] = renderEffect;
  67910. };
  67911. // private
  67912. PostProcessRenderPipeline.prototype._rebuild = function () {
  67913. };
  67914. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  67915. var renderEffects = this._renderEffects[renderEffectName];
  67916. if (!renderEffects) {
  67917. return;
  67918. }
  67919. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  67920. };
  67921. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  67922. var renderEffects = this._renderEffects[renderEffectName];
  67923. if (!renderEffects) {
  67924. return;
  67925. }
  67926. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  67927. };
  67928. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  67929. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  67930. if (!cams) {
  67931. return;
  67932. }
  67933. var indicesToDelete = [];
  67934. var i;
  67935. for (i = 0; i < cams.length; i++) {
  67936. var camera = cams[i];
  67937. var cameraName = camera.name;
  67938. if (this._cameras.indexOf(camera) === -1) {
  67939. this._cameras[cameraName] = camera;
  67940. }
  67941. else if (unique) {
  67942. indicesToDelete.push(i);
  67943. }
  67944. }
  67945. for (i = 0; i < indicesToDelete.length; i++) {
  67946. cameras.splice(indicesToDelete[i], 1);
  67947. }
  67948. for (var renderEffectName in this._renderEffects) {
  67949. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  67950. this._renderEffects[renderEffectName]._attachCameras(cams);
  67951. }
  67952. }
  67953. };
  67954. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  67955. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  67956. if (!cams) {
  67957. return;
  67958. }
  67959. for (var renderEffectName in this._renderEffects) {
  67960. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  67961. this._renderEffects[renderEffectName]._detachCameras(cams);
  67962. }
  67963. }
  67964. for (var i = 0; i < cams.length; i++) {
  67965. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  67966. }
  67967. };
  67968. PostProcessRenderPipeline.prototype._update = function () {
  67969. for (var renderEffectName in this._renderEffects) {
  67970. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  67971. this._renderEffects[renderEffectName]._update();
  67972. }
  67973. }
  67974. for (var i = 0; i < this._cameras.length; i++) {
  67975. var cameraName = this._cameras[i].name;
  67976. if (this._renderEffectsForIsolatedPass[cameraName]) {
  67977. this._renderEffectsForIsolatedPass[cameraName]._update();
  67978. }
  67979. }
  67980. };
  67981. PostProcessRenderPipeline.prototype._reset = function () {
  67982. this._renderEffects = {};
  67983. this._renderEffectsForIsolatedPass = new Array();
  67984. };
  67985. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function () {
  67986. // 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)
  67987. var effectKeys = Object.keys(this._renderEffects);
  67988. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  67989. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  67990. if (postProcesses) {
  67991. postProcesses[0].samples = 4;
  67992. return true;
  67993. }
  67994. }
  67995. return false;
  67996. };
  67997. PostProcessRenderPipeline.prototype.dispose = function () {
  67998. // Must be implemented by children
  67999. };
  68000. __decorate([
  68001. BABYLON.serialize()
  68002. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  68003. return PostProcessRenderPipeline;
  68004. }());
  68005. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  68006. })(BABYLON || (BABYLON = {}));
  68007. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  68008. "use strict";
  68009. var BABYLON;
  68010. (function (BABYLON) {
  68011. /**
  68012. * This represents a depth renderer in Babylon.
  68013. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  68014. */
  68015. var DepthRenderer = /** @class */ (function () {
  68016. /**
  68017. * Instantiates a depth renderer
  68018. * @param scene The scene the renderer belongs to
  68019. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  68020. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  68021. */
  68022. function DepthRenderer(scene, type, camera) {
  68023. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  68024. if (camera === void 0) { camera = null; }
  68025. var _this = this;
  68026. this._scene = scene;
  68027. this._camera = camera;
  68028. var engine = scene.getEngine();
  68029. // Render target
  68030. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  68031. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68032. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68033. this._depthMap.refreshRate = 1;
  68034. this._depthMap.renderParticles = false;
  68035. this._depthMap.renderList = null;
  68036. // Camera to get depth map from to support multiple concurrent cameras
  68037. this._depthMap.activeCamera = this._camera;
  68038. this._depthMap.ignoreCameraViewport = true;
  68039. this._depthMap.useCameraPostProcesses = false;
  68040. // set default depth value to 1.0 (far away)
  68041. this._depthMap.onClearObservable.add(function (engine) {
  68042. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  68043. });
  68044. // Custom render function
  68045. var renderSubMesh = function (subMesh) {
  68046. var mesh = subMesh.getRenderingMesh();
  68047. var scene = _this._scene;
  68048. var engine = scene.getEngine();
  68049. var material = subMesh.getMaterial();
  68050. if (!material) {
  68051. return;
  68052. }
  68053. // Culling and reverse (right handed system)
  68054. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  68055. // Managing instances
  68056. var batch = mesh._getInstancesRenderList(subMesh._id);
  68057. if (batch.mustReturn) {
  68058. return;
  68059. }
  68060. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  68061. var camera = _this._camera || scene.activeCamera;
  68062. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  68063. engine.enableEffect(_this._effect);
  68064. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  68065. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  68066. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  68067. // Alpha test
  68068. if (material && material.needAlphaTesting()) {
  68069. var alphaTexture = material.getAlphaTestTexture();
  68070. if (alphaTexture) {
  68071. _this._effect.setTexture("diffuseSampler", alphaTexture);
  68072. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  68073. }
  68074. }
  68075. // Bones
  68076. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  68077. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  68078. }
  68079. // Draw
  68080. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  68081. }
  68082. };
  68083. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  68084. var index;
  68085. if (depthOnlySubMeshes.length) {
  68086. engine.setColorWrite(false);
  68087. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  68088. renderSubMesh(depthOnlySubMeshes.data[index]);
  68089. }
  68090. engine.setColorWrite(true);
  68091. }
  68092. for (index = 0; index < opaqueSubMeshes.length; index++) {
  68093. renderSubMesh(opaqueSubMeshes.data[index]);
  68094. }
  68095. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  68096. renderSubMesh(alphaTestSubMeshes.data[index]);
  68097. }
  68098. };
  68099. }
  68100. /**
  68101. * Creates the depth rendering effect and checks if the effect is ready.
  68102. * @param subMesh The submesh to be used to render the depth map of
  68103. * @param useInstances If multiple world instances should be used
  68104. * @returns if the depth renderer is ready to render the depth map
  68105. */
  68106. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  68107. var material = subMesh.getMaterial();
  68108. if (material.disableDepthWrite) {
  68109. return false;
  68110. }
  68111. var defines = [];
  68112. var attribs = [BABYLON.VertexBuffer.PositionKind];
  68113. var mesh = subMesh.getMesh();
  68114. // Alpha test
  68115. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  68116. defines.push("#define ALPHATEST");
  68117. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  68118. attribs.push(BABYLON.VertexBuffer.UVKind);
  68119. defines.push("#define UV1");
  68120. }
  68121. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  68122. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  68123. defines.push("#define UV2");
  68124. }
  68125. }
  68126. // Bones
  68127. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  68128. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  68129. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  68130. if (mesh.numBoneInfluencers > 4) {
  68131. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  68132. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  68133. }
  68134. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  68135. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  68136. }
  68137. else {
  68138. defines.push("#define NUM_BONE_INFLUENCERS 0");
  68139. }
  68140. // Instances
  68141. if (useInstances) {
  68142. defines.push("#define INSTANCES");
  68143. attribs.push("world0");
  68144. attribs.push("world1");
  68145. attribs.push("world2");
  68146. attribs.push("world3");
  68147. }
  68148. // Get correct effect
  68149. var join = defines.join("\n");
  68150. if (this._cachedDefines !== join) {
  68151. this._cachedDefines = join;
  68152. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  68153. }
  68154. return this._effect.isReady();
  68155. };
  68156. /**
  68157. * Gets the texture which the depth map will be written to.
  68158. * @returns The depth map texture
  68159. */
  68160. DepthRenderer.prototype.getDepthMap = function () {
  68161. return this._depthMap;
  68162. };
  68163. /**
  68164. * Disposes of the depth renderer.
  68165. */
  68166. DepthRenderer.prototype.dispose = function () {
  68167. this._depthMap.dispose();
  68168. };
  68169. return DepthRenderer;
  68170. }());
  68171. BABYLON.DepthRenderer = DepthRenderer;
  68172. })(BABYLON || (BABYLON = {}));
  68173. //# sourceMappingURL=babylon.depthRenderer.js.map
  68174. "use strict";
  68175. var BABYLON;
  68176. (function (BABYLON) {
  68177. var SSAORenderingPipeline = /** @class */ (function (_super) {
  68178. __extends(SSAORenderingPipeline, _super);
  68179. /**
  68180. * @constructor
  68181. * @param {string} name - The rendering pipeline name
  68182. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  68183. * @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 }
  68184. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  68185. */
  68186. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  68187. var _this = _super.call(this, scene.getEngine(), name) || this;
  68188. // Members
  68189. /**
  68190. * The PassPostProcess id in the pipeline that contains the original scene color
  68191. * @type {string}
  68192. */
  68193. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  68194. /**
  68195. * The SSAO PostProcess id in the pipeline
  68196. * @type {string}
  68197. */
  68198. _this.SSAORenderEffect = "SSAORenderEffect";
  68199. /**
  68200. * The horizontal blur PostProcess id in the pipeline
  68201. * @type {string}
  68202. */
  68203. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  68204. /**
  68205. * The vertical blur PostProcess id in the pipeline
  68206. * @type {string}
  68207. */
  68208. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  68209. /**
  68210. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  68211. * @type {string}
  68212. */
  68213. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  68214. /**
  68215. * The output strength of the SSAO post-process. Default value is 1.0.
  68216. * @type {number}
  68217. */
  68218. _this.totalStrength = 1.0;
  68219. /**
  68220. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  68221. * @type {number}
  68222. */
  68223. _this.radius = 0.0001;
  68224. /**
  68225. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  68226. * Must not be equal to fallOff and superior to fallOff.
  68227. * Default value is 0.975
  68228. * @type {number}
  68229. */
  68230. _this.area = 0.0075;
  68231. /**
  68232. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  68233. * Must not be equal to area and inferior to area.
  68234. * Default value is 0.0
  68235. * @type {number}
  68236. */
  68237. _this.fallOff = 0.000001;
  68238. /**
  68239. * The base color of the SSAO post-process
  68240. * The final result is "base + ssao" between [0, 1]
  68241. * @type {number}
  68242. */
  68243. _this.base = 0.5;
  68244. _this._firstUpdate = true;
  68245. _this._scene = scene;
  68246. // Set up assets
  68247. _this._createRandomTexture();
  68248. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  68249. var ssaoRatio = ratio.ssaoRatio || ratio;
  68250. var combineRatio = ratio.combineRatio || ratio;
  68251. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  68252. _this._createSSAOPostProcess(ssaoRatio);
  68253. _this._createBlurPostProcess(ssaoRatio);
  68254. _this._createSSAOCombinePostProcess(combineRatio);
  68255. // Set up pipeline
  68256. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  68257. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  68258. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  68259. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  68260. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  68261. // Finish
  68262. scene.postProcessRenderPipelineManager.addPipeline(_this);
  68263. if (cameras)
  68264. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  68265. return _this;
  68266. }
  68267. // Public Methods
  68268. /**
  68269. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  68270. */
  68271. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  68272. if (disableDepthRender === void 0) { disableDepthRender = false; }
  68273. for (var i = 0; i < this._scene.cameras.length; i++) {
  68274. var camera = this._scene.cameras[i];
  68275. this._originalColorPostProcess.dispose(camera);
  68276. this._ssaoPostProcess.dispose(camera);
  68277. this._blurHPostProcess.dispose(camera);
  68278. this._blurVPostProcess.dispose(camera);
  68279. this._ssaoCombinePostProcess.dispose(camera);
  68280. }
  68281. this._randomTexture.dispose();
  68282. if (disableDepthRender)
  68283. this._scene.disableDepthRenderer();
  68284. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  68285. _super.prototype.dispose.call(this);
  68286. };
  68287. // Private Methods
  68288. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  68289. var _this = this;
  68290. var size = 16;
  68291. 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);
  68292. 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);
  68293. this._blurHPostProcess.onActivateObservable.add(function () {
  68294. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  68295. _this._blurHPostProcess.kernel = size * dw;
  68296. });
  68297. this._blurVPostProcess.onActivateObservable.add(function () {
  68298. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  68299. _this._blurVPostProcess.kernel = size * dw;
  68300. });
  68301. };
  68302. SSAORenderingPipeline.prototype._rebuild = function () {
  68303. this._firstUpdate = true;
  68304. _super.prototype._rebuild.call(this);
  68305. };
  68306. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  68307. var _this = this;
  68308. var numSamples = 16;
  68309. var sampleSphere = [
  68310. 0.5381, 0.1856, -0.4319,
  68311. 0.1379, 0.2486, 0.4430,
  68312. 0.3371, 0.5679, -0.0057,
  68313. -0.6999, -0.0451, -0.0019,
  68314. 0.0689, -0.1598, -0.8547,
  68315. 0.0560, 0.0069, -0.1843,
  68316. -0.0146, 0.1402, 0.0762,
  68317. 0.0100, -0.1924, -0.0344,
  68318. -0.3577, -0.5301, -0.4358,
  68319. -0.3169, 0.1063, 0.0158,
  68320. 0.0103, -0.5869, 0.0046,
  68321. -0.0897, -0.4940, 0.3287,
  68322. 0.7119, -0.0154, -0.0918,
  68323. -0.0533, 0.0596, -0.5411,
  68324. 0.0352, -0.0631, 0.5460,
  68325. -0.4776, 0.2847, -0.0271
  68326. ];
  68327. var samplesFactor = 1.0 / numSamples;
  68328. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  68329. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  68330. "area", "fallOff", "base", "range", "viewport"
  68331. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  68332. this._ssaoPostProcess.onApply = function (effect) {
  68333. if (_this._firstUpdate) {
  68334. effect.setArray3("sampleSphere", sampleSphere);
  68335. effect.setFloat("samplesFactor", samplesFactor);
  68336. effect.setFloat("randTextureTiles", 4.0);
  68337. }
  68338. effect.setFloat("totalStrength", _this.totalStrength);
  68339. effect.setFloat("radius", _this.radius);
  68340. effect.setFloat("area", _this.area);
  68341. effect.setFloat("fallOff", _this.fallOff);
  68342. effect.setFloat("base", _this.base);
  68343. effect.setTexture("textureSampler", _this._depthTexture);
  68344. effect.setTexture("randomSampler", _this._randomTexture);
  68345. };
  68346. };
  68347. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  68348. var _this = this;
  68349. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  68350. this._ssaoCombinePostProcess.onApply = function (effect) {
  68351. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  68352. };
  68353. };
  68354. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  68355. var size = 512;
  68356. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  68357. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  68358. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  68359. var context = this._randomTexture.getContext();
  68360. var rand = function (min, max) {
  68361. return Math.random() * (max - min) + min;
  68362. };
  68363. var randVector = BABYLON.Vector3.Zero();
  68364. for (var x = 0; x < size; x++) {
  68365. for (var y = 0; y < size; y++) {
  68366. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  68367. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  68368. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  68369. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  68370. context.fillRect(x, y, 1, 1);
  68371. }
  68372. }
  68373. this._randomTexture.update(false);
  68374. };
  68375. __decorate([
  68376. BABYLON.serialize()
  68377. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  68378. __decorate([
  68379. BABYLON.serialize()
  68380. ], SSAORenderingPipeline.prototype, "radius", void 0);
  68381. __decorate([
  68382. BABYLON.serialize()
  68383. ], SSAORenderingPipeline.prototype, "area", void 0);
  68384. __decorate([
  68385. BABYLON.serialize()
  68386. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  68387. __decorate([
  68388. BABYLON.serialize()
  68389. ], SSAORenderingPipeline.prototype, "base", void 0);
  68390. return SSAORenderingPipeline;
  68391. }(BABYLON.PostProcessRenderPipeline));
  68392. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  68393. })(BABYLON || (BABYLON = {}));
  68394. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  68395. "use strict";
  68396. var BABYLON;
  68397. (function (BABYLON) {
  68398. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  68399. __extends(SSAO2RenderingPipeline, _super);
  68400. /**
  68401. * @constructor
  68402. * @param {string} name - The rendering pipeline name
  68403. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  68404. * @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 }
  68405. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  68406. */
  68407. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  68408. var _this = _super.call(this, scene.getEngine(), name) || this;
  68409. // Members
  68410. /**
  68411. * The PassPostProcess id in the pipeline that contains the original scene color
  68412. * @type {string}
  68413. */
  68414. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  68415. /**
  68416. * The SSAO PostProcess id in the pipeline
  68417. * @type {string}
  68418. */
  68419. _this.SSAORenderEffect = "SSAORenderEffect";
  68420. /**
  68421. * The horizontal blur PostProcess id in the pipeline
  68422. * @type {string}
  68423. */
  68424. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  68425. /**
  68426. * The vertical blur PostProcess id in the pipeline
  68427. * @type {string}
  68428. */
  68429. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  68430. /**
  68431. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  68432. * @type {string}
  68433. */
  68434. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  68435. /**
  68436. * The output strength of the SSAO post-process. Default value is 1.0.
  68437. * @type {number}
  68438. */
  68439. _this.totalStrength = 1.0;
  68440. /**
  68441. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  68442. * @type {number}
  68443. */
  68444. _this.maxZ = 100.0;
  68445. /**
  68446. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  68447. * @type {number}
  68448. */
  68449. _this.minZAspect = 0.2;
  68450. /**
  68451. * Number of samples used for the SSAO calculations. Default value is 8
  68452. * @type {number}
  68453. */
  68454. _this._samples = 8;
  68455. /**
  68456. * Are we using bilateral blur ?
  68457. * @type {boolean}
  68458. */
  68459. _this._expensiveBlur = true;
  68460. /**
  68461. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  68462. * @type {number}
  68463. */
  68464. _this.radius = 2.0;
  68465. /**
  68466. * The base color of the SSAO post-process
  68467. * The final result is "base + ssao" between [0, 1]
  68468. * @type {number}
  68469. */
  68470. _this.base = 0.1;
  68471. _this._firstUpdate = true;
  68472. _this._scene = scene;
  68473. if (!_this.isSupported) {
  68474. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  68475. return _this;
  68476. }
  68477. var ssaoRatio = ratio.ssaoRatio || ratio;
  68478. var blurRatio = ratio.blurRatio || ratio;
  68479. // Set up assets
  68480. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  68481. _this._createRandomTexture();
  68482. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  68483. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  68484. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  68485. _this._createSSAOPostProcess(1.0);
  68486. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  68487. _this._createSSAOCombinePostProcess(blurRatio);
  68488. // Set up pipeline
  68489. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  68490. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  68491. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  68492. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  68493. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  68494. // Finish
  68495. scene.postProcessRenderPipelineManager.addPipeline(_this);
  68496. if (cameras)
  68497. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  68498. return _this;
  68499. }
  68500. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  68501. get: function () {
  68502. return this._samples;
  68503. },
  68504. set: function (n) {
  68505. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  68506. this._samples = n;
  68507. this._sampleSphere = this._generateHemisphere();
  68508. this._firstUpdate = true;
  68509. },
  68510. enumerable: true,
  68511. configurable: true
  68512. });
  68513. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  68514. get: function () {
  68515. return this._expensiveBlur;
  68516. },
  68517. set: function (b) {
  68518. 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"]);
  68519. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  68520. this._expensiveBlur = b;
  68521. this._firstUpdate = true;
  68522. },
  68523. enumerable: true,
  68524. configurable: true
  68525. });
  68526. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  68527. /**
  68528. * Support test.
  68529. * @type {boolean}
  68530. */
  68531. get: function () {
  68532. var engine = BABYLON.Engine.LastCreatedEngine;
  68533. if (!engine) {
  68534. return false;
  68535. }
  68536. return engine.getCaps().drawBuffersExtension;
  68537. },
  68538. enumerable: true,
  68539. configurable: true
  68540. });
  68541. // Public Methods
  68542. /**
  68543. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  68544. */
  68545. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  68546. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  68547. for (var i = 0; i < this._scene.cameras.length; i++) {
  68548. var camera = this._scene.cameras[i];
  68549. this._originalColorPostProcess.dispose(camera);
  68550. this._ssaoPostProcess.dispose(camera);
  68551. this._blurHPostProcess.dispose(camera);
  68552. this._blurVPostProcess.dispose(camera);
  68553. this._ssaoCombinePostProcess.dispose(camera);
  68554. }
  68555. this._randomTexture.dispose();
  68556. if (disableGeometryBufferRenderer)
  68557. this._scene.disableGeometryBufferRenderer();
  68558. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  68559. _super.prototype.dispose.call(this);
  68560. };
  68561. // Private Methods
  68562. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  68563. var _this = this;
  68564. this._samplerOffsets = [];
  68565. var expensive = this.expensiveBlur;
  68566. for (var i = -8; i < 8; i++) {
  68567. this._samplerOffsets.push(i * 2 + 0.5);
  68568. }
  68569. 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");
  68570. this._blurHPostProcess.onApply = function (effect) {
  68571. if (!_this._scene.activeCamera) {
  68572. return;
  68573. }
  68574. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  68575. effect.setFloat("near", _this._scene.activeCamera.minZ);
  68576. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  68577. effect.setFloat("radius", _this.radius);
  68578. effect.setTexture("depthSampler", _this._depthTexture);
  68579. if (_this._firstUpdate) {
  68580. effect.setArray("samplerOffsets", _this._samplerOffsets);
  68581. }
  68582. };
  68583. 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");
  68584. this._blurVPostProcess.onApply = function (effect) {
  68585. if (!_this._scene.activeCamera) {
  68586. return;
  68587. }
  68588. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  68589. effect.setFloat("near", _this._scene.activeCamera.minZ);
  68590. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  68591. effect.setFloat("radius", _this.radius);
  68592. effect.setTexture("depthSampler", _this._depthTexture);
  68593. if (_this._firstUpdate) {
  68594. effect.setArray("samplerOffsets", _this._samplerOffsets);
  68595. _this._firstUpdate = false;
  68596. }
  68597. };
  68598. };
  68599. SSAO2RenderingPipeline.prototype._rebuild = function () {
  68600. this._firstUpdate = true;
  68601. _super.prototype._rebuild.call(this);
  68602. };
  68603. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  68604. var numSamples = this.samples;
  68605. var result = [];
  68606. var vector, scale;
  68607. var rand = function (min, max) {
  68608. return Math.random() * (max - min) + min;
  68609. };
  68610. var i = 0;
  68611. while (i < numSamples) {
  68612. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  68613. vector.normalize();
  68614. scale = i / numSamples;
  68615. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  68616. vector.scaleInPlace(scale);
  68617. result.push(vector.x, vector.y, vector.z);
  68618. i++;
  68619. }
  68620. return result;
  68621. };
  68622. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  68623. var _this = this;
  68624. var numSamples = this.samples;
  68625. this._sampleSphere = this._generateHemisphere();
  68626. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  68627. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  68628. "base", "range", "projection", "near", "far", "texelSize",
  68629. "xViewport", "yViewport", "maxZ", "minZAspect"
  68630. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  68631. this._ssaoPostProcess.onApply = function (effect) {
  68632. if (_this._firstUpdate) {
  68633. effect.setArray3("sampleSphere", _this._sampleSphere);
  68634. effect.setFloat("randTextureTiles", 4.0);
  68635. }
  68636. if (!_this._scene.activeCamera) {
  68637. return;
  68638. }
  68639. effect.setFloat("samplesFactor", 1 / _this.samples);
  68640. effect.setFloat("totalStrength", _this.totalStrength);
  68641. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  68642. effect.setFloat("radius", _this.radius);
  68643. effect.setFloat("maxZ", _this.maxZ);
  68644. effect.setFloat("minZAspect", _this.minZAspect);
  68645. effect.setFloat("base", _this.base);
  68646. effect.setFloat("near", _this._scene.activeCamera.minZ);
  68647. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  68648. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  68649. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  68650. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  68651. effect.setTexture("textureSampler", _this._depthTexture);
  68652. effect.setTexture("normalSampler", _this._normalTexture);
  68653. effect.setTexture("randomSampler", _this._randomTexture);
  68654. };
  68655. };
  68656. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  68657. var _this = this;
  68658. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  68659. this._ssaoCombinePostProcess.onApply = function (effect) {
  68660. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  68661. };
  68662. };
  68663. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  68664. var size = 512;
  68665. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  68666. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  68667. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  68668. var context = this._randomTexture.getContext();
  68669. var rand = function (min, max) {
  68670. return Math.random() * (max - min) + min;
  68671. };
  68672. var randVector = BABYLON.Vector3.Zero();
  68673. for (var x = 0; x < size; x++) {
  68674. for (var y = 0; y < size; y++) {
  68675. randVector.x = rand(0.0, 1.0);
  68676. randVector.y = rand(0.0, 1.0);
  68677. randVector.z = 0.0;
  68678. randVector.normalize();
  68679. randVector.scaleInPlace(255);
  68680. randVector.x = Math.floor(randVector.x);
  68681. randVector.y = Math.floor(randVector.y);
  68682. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  68683. context.fillRect(x, y, 1, 1);
  68684. }
  68685. }
  68686. this._randomTexture.update(false);
  68687. };
  68688. __decorate([
  68689. BABYLON.serialize()
  68690. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  68691. __decorate([
  68692. BABYLON.serialize()
  68693. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  68694. __decorate([
  68695. BABYLON.serialize()
  68696. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  68697. __decorate([
  68698. BABYLON.serialize("samples")
  68699. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  68700. __decorate([
  68701. BABYLON.serialize("expensiveBlur")
  68702. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  68703. __decorate([
  68704. BABYLON.serialize()
  68705. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  68706. __decorate([
  68707. BABYLON.serialize()
  68708. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  68709. return SSAO2RenderingPipeline;
  68710. }(BABYLON.PostProcessRenderPipeline));
  68711. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  68712. })(BABYLON || (BABYLON = {}));
  68713. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  68714. "use strict";
  68715. // BABYLON.JS Chromatic Aberration GLSL Shader
  68716. // Author: Olivier Guyot
  68717. // Separates very slightly R, G and B colors on the edges of the screen
  68718. // Inspired by Francois Tarlier & Martins Upitis
  68719. var BABYLON;
  68720. (function (BABYLON) {
  68721. var LensRenderingPipeline = /** @class */ (function (_super) {
  68722. __extends(LensRenderingPipeline, _super);
  68723. /**
  68724. * @constructor
  68725. *
  68726. * Effect parameters are as follow:
  68727. * {
  68728. * chromatic_aberration: number; // from 0 to x (1 for realism)
  68729. * edge_blur: number; // from 0 to x (1 for realism)
  68730. * distortion: number; // from 0 to x (1 for realism)
  68731. * grain_amount: number; // from 0 to 1
  68732. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  68733. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  68734. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  68735. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  68736. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  68737. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  68738. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  68739. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  68740. * }
  68741. * Note: if an effect parameter is unset, effect is disabled
  68742. *
  68743. * @param {string} name - The rendering pipeline name
  68744. * @param {object} parameters - An object containing all parameters (see above)
  68745. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  68746. * @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)
  68747. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  68748. */
  68749. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  68750. if (ratio === void 0) { ratio = 1.0; }
  68751. var _this = _super.call(this, scene.getEngine(), name) || this;
  68752. // Lens effects can be of the following:
  68753. // - chromatic aberration (slight shift of RGB colors)
  68754. // - blur on the edge of the lens
  68755. // - lens distortion
  68756. // - depth-of-field blur & highlights enhancing
  68757. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  68758. // - grain effect (noise or custom texture)
  68759. // Two additional texture samplers are needed:
  68760. // - depth map (for depth-of-field)
  68761. // - grain texture
  68762. /**
  68763. * The chromatic aberration PostProcess id in the pipeline
  68764. * @type {string}
  68765. */
  68766. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  68767. /**
  68768. * The highlights enhancing PostProcess id in the pipeline
  68769. * @type {string}
  68770. */
  68771. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  68772. /**
  68773. * The depth-of-field PostProcess id in the pipeline
  68774. * @type {string}
  68775. */
  68776. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  68777. _this._scene = scene;
  68778. // Fetch texture samplers
  68779. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  68780. if (parameters.grain_texture) {
  68781. _this._grainTexture = parameters.grain_texture;
  68782. }
  68783. else {
  68784. _this._createGrainTexture();
  68785. }
  68786. // save parameters
  68787. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  68788. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  68789. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  68790. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  68791. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  68792. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  68793. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  68794. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  68795. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  68796. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  68797. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  68798. // Create effects
  68799. _this._createChromaticAberrationPostProcess(ratio);
  68800. _this._createHighlightsPostProcess(ratio);
  68801. _this._createDepthOfFieldPostProcess(ratio / 4);
  68802. // Set up pipeline
  68803. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  68804. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  68805. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  68806. if (_this._highlightsGain === -1) {
  68807. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  68808. }
  68809. // Finish
  68810. scene.postProcessRenderPipelineManager.addPipeline(_this);
  68811. if (cameras) {
  68812. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  68813. }
  68814. return _this;
  68815. }
  68816. // public methods (self explanatory)
  68817. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  68818. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  68819. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  68820. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  68821. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  68822. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  68823. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  68824. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  68825. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  68826. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  68827. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  68828. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  68829. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  68830. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  68831. };
  68832. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  68833. this._highlightsPostProcess.updateEffect();
  68834. };
  68835. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  68836. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  68837. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  68838. this._highlightsGain = amount;
  68839. };
  68840. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  68841. if (this._highlightsGain === -1) {
  68842. this._highlightsGain = 1.0;
  68843. }
  68844. this._highlightsThreshold = amount;
  68845. };
  68846. LensRenderingPipeline.prototype.disableHighlights = function () {
  68847. this._highlightsGain = -1;
  68848. };
  68849. /**
  68850. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  68851. */
  68852. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  68853. if (disableDepthRender === void 0) { disableDepthRender = false; }
  68854. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  68855. this._chromaticAberrationPostProcess = null;
  68856. this._highlightsPostProcess = null;
  68857. this._depthOfFieldPostProcess = null;
  68858. this._grainTexture.dispose();
  68859. if (disableDepthRender)
  68860. this._scene.disableDepthRenderer();
  68861. };
  68862. // colors shifting and distortion
  68863. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  68864. var _this = this;
  68865. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  68866. [], // samplers
  68867. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  68868. this._chromaticAberrationPostProcess.onApply = function (effect) {
  68869. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  68870. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  68871. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  68872. effect.setFloat('radialIntensity', 1);
  68873. effect.setFloat2('direction', 17, 17);
  68874. effect.setFloat2('centerPosition', 0.5, 0.5);
  68875. };
  68876. };
  68877. // highlights enhancing
  68878. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  68879. var _this = this;
  68880. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  68881. [], // samplers
  68882. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  68883. this._highlightsPostProcess.onApply = function (effect) {
  68884. effect.setFloat('gain', _this._highlightsGain);
  68885. effect.setFloat('threshold', _this._highlightsThreshold);
  68886. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  68887. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  68888. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  68889. };
  68890. };
  68891. // colors shifting and distortion
  68892. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  68893. var _this = this;
  68894. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  68895. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  68896. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  68897. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  68898. this._depthOfFieldPostProcess.onApply = function (effect) {
  68899. effect.setTexture("depthSampler", _this._depthTexture);
  68900. effect.setTexture("grainSampler", _this._grainTexture);
  68901. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  68902. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  68903. effect.setFloat('grain_amount', _this._grainAmount);
  68904. effect.setBool('blur_noise', _this._blurNoise);
  68905. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  68906. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  68907. effect.setFloat('distortion', _this._distortion);
  68908. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  68909. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  68910. effect.setFloat('aperture', _this._dofAperture);
  68911. effect.setFloat('darken', _this._dofDarken);
  68912. effect.setFloat('edge_blur', _this._edgeBlur);
  68913. effect.setBool('highlights', (_this._highlightsGain !== -1));
  68914. if (_this._scene.activeCamera) {
  68915. effect.setFloat('near', _this._scene.activeCamera.minZ);
  68916. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  68917. }
  68918. };
  68919. };
  68920. // creates a black and white random noise texture, 512x512
  68921. LensRenderingPipeline.prototype._createGrainTexture = function () {
  68922. var size = 512;
  68923. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  68924. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  68925. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  68926. var context = this._grainTexture.getContext();
  68927. var rand = function (min, max) {
  68928. return Math.random() * (max - min) + min;
  68929. };
  68930. var value;
  68931. for (var x = 0; x < size; x++) {
  68932. for (var y = 0; y < size; y++) {
  68933. value = Math.floor(rand(0.42, 0.58) * 255);
  68934. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  68935. context.fillRect(x, y, 1, 1);
  68936. }
  68937. }
  68938. this._grainTexture.update(false);
  68939. };
  68940. return LensRenderingPipeline;
  68941. }(BABYLON.PostProcessRenderPipeline));
  68942. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  68943. })(BABYLON || (BABYLON = {}));
  68944. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  68945. "use strict";
  68946. var BABYLON;
  68947. (function (BABYLON) {
  68948. var StandardRenderingPipeline = /** @class */ (function (_super) {
  68949. __extends(StandardRenderingPipeline, _super);
  68950. /**
  68951. * @constructor
  68952. * @param {string} name - The rendering pipeline name
  68953. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  68954. * @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)
  68955. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  68956. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  68957. */
  68958. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  68959. if (originalPostProcess === void 0) { originalPostProcess = null; }
  68960. var _this = _super.call(this, scene.getEngine(), name) || this;
  68961. _this.downSampleX4PostProcess = null;
  68962. _this.brightPassPostProcess = null;
  68963. _this.blurHPostProcesses = [];
  68964. _this.blurVPostProcesses = [];
  68965. _this.textureAdderPostProcess = null;
  68966. _this.volumetricLightPostProcess = null;
  68967. _this.volumetricLightSmoothXPostProcess = null;
  68968. _this.volumetricLightSmoothYPostProcess = null;
  68969. _this.volumetricLightMergePostProces = null;
  68970. _this.volumetricLightFinalPostProcess = null;
  68971. _this.luminancePostProcess = null;
  68972. _this.luminanceDownSamplePostProcesses = [];
  68973. _this.hdrPostProcess = null;
  68974. _this.textureAdderFinalPostProcess = null;
  68975. _this.lensFlareFinalPostProcess = null;
  68976. _this.hdrFinalPostProcess = null;
  68977. _this.lensFlarePostProcess = null;
  68978. _this.lensFlareComposePostProcess = null;
  68979. _this.motionBlurPostProcess = null;
  68980. _this.depthOfFieldPostProcess = null;
  68981. // Values
  68982. _this.brightThreshold = 1.0;
  68983. _this.blurWidth = 512.0;
  68984. _this.horizontalBlur = false;
  68985. _this.exposure = 1.0;
  68986. _this.lensTexture = null;
  68987. _this.volumetricLightCoefficient = 0.2;
  68988. _this.volumetricLightPower = 4.0;
  68989. _this.volumetricLightBlurScale = 64.0;
  68990. _this.sourceLight = null;
  68991. _this.hdrMinimumLuminance = 1.0;
  68992. _this.hdrDecreaseRate = 0.5;
  68993. _this.hdrIncreaseRate = 0.5;
  68994. _this.lensColorTexture = null;
  68995. _this.lensFlareStrength = 20.0;
  68996. _this.lensFlareGhostDispersal = 1.4;
  68997. _this.lensFlareHaloWidth = 0.7;
  68998. _this.lensFlareDistortionStrength = 16.0;
  68999. _this.lensStarTexture = null;
  69000. _this.lensFlareDirtTexture = null;
  69001. _this.depthOfFieldDistance = 10.0;
  69002. _this.depthOfFieldBlurWidth = 64.0;
  69003. _this.motionStrength = 1.0;
  69004. // IAnimatable
  69005. _this.animations = [];
  69006. _this._currentDepthOfFieldSource = null;
  69007. _this._hdrCurrentLuminance = 1.0;
  69008. // Getters and setters
  69009. _this._bloomEnabled = true;
  69010. _this._depthOfFieldEnabled = false;
  69011. _this._vlsEnabled = false;
  69012. _this._lensFlareEnabled = false;
  69013. _this._hdrEnabled = false;
  69014. _this._motionBlurEnabled = false;
  69015. _this._motionBlurSamples = 64.0;
  69016. _this._volumetricLightStepsCount = 50.0;
  69017. _this._cameras = cameras || [];
  69018. // Initialize
  69019. _this._scene = scene;
  69020. _this._basePostProcess = originalPostProcess;
  69021. _this._ratio = ratio;
  69022. // Misc
  69023. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  69024. // Finish
  69025. scene.postProcessRenderPipelineManager.addPipeline(_this);
  69026. _this._buildPipeline();
  69027. return _this;
  69028. }
  69029. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  69030. get: function () {
  69031. return this._bloomEnabled;
  69032. },
  69033. set: function (enabled) {
  69034. if (this._bloomEnabled === enabled) {
  69035. return;
  69036. }
  69037. this._bloomEnabled = enabled;
  69038. this._buildPipeline();
  69039. },
  69040. enumerable: true,
  69041. configurable: true
  69042. });
  69043. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  69044. get: function () {
  69045. return this._depthOfFieldEnabled;
  69046. },
  69047. set: function (enabled) {
  69048. if (this._depthOfFieldEnabled === enabled) {
  69049. return;
  69050. }
  69051. this._depthOfFieldEnabled = enabled;
  69052. this._buildPipeline();
  69053. },
  69054. enumerable: true,
  69055. configurable: true
  69056. });
  69057. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  69058. get: function () {
  69059. return this._lensFlareEnabled;
  69060. },
  69061. set: function (enabled) {
  69062. if (this._lensFlareEnabled === enabled) {
  69063. return;
  69064. }
  69065. this._lensFlareEnabled = enabled;
  69066. this._buildPipeline();
  69067. },
  69068. enumerable: true,
  69069. configurable: true
  69070. });
  69071. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  69072. get: function () {
  69073. return this._hdrEnabled;
  69074. },
  69075. set: function (enabled) {
  69076. if (this._hdrEnabled === enabled) {
  69077. return;
  69078. }
  69079. this._hdrEnabled = enabled;
  69080. this._buildPipeline();
  69081. },
  69082. enumerable: true,
  69083. configurable: true
  69084. });
  69085. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  69086. get: function () {
  69087. return this._vlsEnabled;
  69088. },
  69089. set: function (enabled) {
  69090. if (this._vlsEnabled === enabled) {
  69091. return;
  69092. }
  69093. if (enabled) {
  69094. var geometry = this._scene.enableGeometryBufferRenderer();
  69095. if (!geometry) {
  69096. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  69097. return;
  69098. }
  69099. }
  69100. this._vlsEnabled = enabled;
  69101. this._buildPipeline();
  69102. },
  69103. enumerable: true,
  69104. configurable: true
  69105. });
  69106. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  69107. get: function () {
  69108. return this._motionBlurEnabled;
  69109. },
  69110. set: function (enabled) {
  69111. if (this._motionBlurEnabled === enabled) {
  69112. return;
  69113. }
  69114. this._motionBlurEnabled = enabled;
  69115. this._buildPipeline();
  69116. },
  69117. enumerable: true,
  69118. configurable: true
  69119. });
  69120. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  69121. get: function () {
  69122. return this._volumetricLightStepsCount;
  69123. },
  69124. set: function (count) {
  69125. if (this.volumetricLightPostProcess) {
  69126. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  69127. }
  69128. this._volumetricLightStepsCount = count;
  69129. },
  69130. enumerable: true,
  69131. configurable: true
  69132. });
  69133. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  69134. get: function () {
  69135. return this._motionBlurSamples;
  69136. },
  69137. set: function (samples) {
  69138. if (this.motionBlurPostProcess) {
  69139. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  69140. }
  69141. this._motionBlurSamples = samples;
  69142. },
  69143. enumerable: true,
  69144. configurable: true
  69145. });
  69146. StandardRenderingPipeline.prototype._buildPipeline = function () {
  69147. var _this = this;
  69148. var ratio = this._ratio;
  69149. var scene = this._scene;
  69150. this._disposePostProcesses();
  69151. this._reset();
  69152. // Create pass post-process
  69153. if (!this._basePostProcess) {
  69154. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  69155. this.originalPostProcess.onApply = function (effect) {
  69156. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  69157. };
  69158. }
  69159. else {
  69160. this.originalPostProcess = this._basePostProcess;
  69161. }
  69162. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  69163. this._currentDepthOfFieldSource = this.originalPostProcess;
  69164. if (this._vlsEnabled) {
  69165. // Create volumetric light
  69166. this._createVolumetricLightPostProcess(scene, ratio);
  69167. // Create volumetric light final post-process
  69168. 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);
  69169. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  69170. }
  69171. if (this._bloomEnabled) {
  69172. // Create down sample X4 post-process
  69173. this._createDownSampleX4PostProcess(scene, ratio / 2);
  69174. // Create bright pass post-process
  69175. this._createBrightPassPostProcess(scene, ratio / 2);
  69176. // Create gaussian blur post-processes (down sampling blurs)
  69177. this._createBlurPostProcesses(scene, ratio / 4, 1);
  69178. // Create texture adder post-process
  69179. this._createTextureAdderPostProcess(scene, ratio);
  69180. // Create depth-of-field source post-process
  69181. 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);
  69182. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  69183. }
  69184. if (this._lensFlareEnabled) {
  69185. // Create lens flare post-process
  69186. this._createLensFlarePostProcess(scene, ratio);
  69187. // Create depth-of-field source post-process post lens-flare and disable it now
  69188. 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);
  69189. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  69190. }
  69191. if (this._hdrEnabled) {
  69192. // Create luminance
  69193. this._createLuminancePostProcesses(scene, this._floatTextureType);
  69194. // Create HDR
  69195. this._createHdrPostProcess(scene, ratio);
  69196. // Create depth-of-field source post-process post hdr and disable it now
  69197. 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);
  69198. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  69199. }
  69200. if (this._depthOfFieldEnabled) {
  69201. // Create gaussian blur used by depth-of-field
  69202. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  69203. // Create depth-of-field post-process
  69204. this._createDepthOfFieldPostProcess(scene, ratio);
  69205. }
  69206. if (this._motionBlurEnabled) {
  69207. // Create motion blur post-process
  69208. this._createMotionBlurPostProcess(scene, ratio);
  69209. }
  69210. if (this._cameras !== null) {
  69211. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  69212. }
  69213. };
  69214. // Down Sample X4 Post-Processs
  69215. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  69216. var _this = this;
  69217. var downSampleX4Offsets = new Array(32);
  69218. 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);
  69219. this.downSampleX4PostProcess.onApply = function (effect) {
  69220. var id = 0;
  69221. var width = _this.downSampleX4PostProcess.width;
  69222. var height = _this.downSampleX4PostProcess.height;
  69223. for (var i = -2; i < 2; i++) {
  69224. for (var j = -2; j < 2; j++) {
  69225. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  69226. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  69227. id += 2;
  69228. }
  69229. }
  69230. effect.setArray2("dsOffsets", downSampleX4Offsets);
  69231. };
  69232. // Add to pipeline
  69233. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  69234. };
  69235. // Brightpass Post-Process
  69236. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  69237. var _this = this;
  69238. var brightOffsets = new Array(8);
  69239. 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);
  69240. this.brightPassPostProcess.onApply = function (effect) {
  69241. var sU = (1.0 / _this.brightPassPostProcess.width);
  69242. var sV = (1.0 / _this.brightPassPostProcess.height);
  69243. brightOffsets[0] = -0.5 * sU;
  69244. brightOffsets[1] = 0.5 * sV;
  69245. brightOffsets[2] = 0.5 * sU;
  69246. brightOffsets[3] = 0.5 * sV;
  69247. brightOffsets[4] = -0.5 * sU;
  69248. brightOffsets[5] = -0.5 * sV;
  69249. brightOffsets[6] = 0.5 * sU;
  69250. brightOffsets[7] = -0.5 * sV;
  69251. effect.setArray2("dsOffsets", brightOffsets);
  69252. effect.setFloat("brightThreshold", _this.brightThreshold);
  69253. };
  69254. // Add to pipeline
  69255. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  69256. };
  69257. // Create blur H&V post-processes
  69258. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  69259. var _this = this;
  69260. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  69261. var engine = scene.getEngine();
  69262. 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);
  69263. 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);
  69264. blurX.onActivateObservable.add(function () {
  69265. var dw = blurX.width / engine.getRenderWidth();
  69266. blurX.kernel = _this[blurWidthKey] * dw;
  69267. });
  69268. blurY.onActivateObservable.add(function () {
  69269. var dw = blurY.height / engine.getRenderHeight();
  69270. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  69271. });
  69272. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  69273. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  69274. this.blurHPostProcesses.push(blurX);
  69275. this.blurVPostProcesses.push(blurY);
  69276. };
  69277. // Create texture adder post-process
  69278. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  69279. var _this = this;
  69280. 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);
  69281. this.textureAdderPostProcess.onApply = function (effect) {
  69282. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  69283. effect.setTexture("lensSampler", _this.lensTexture);
  69284. effect.setFloat("exposure", _this.exposure);
  69285. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  69286. };
  69287. // Add to pipeline
  69288. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  69289. };
  69290. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  69291. var _this = this;
  69292. var geometryRenderer = scene.enableGeometryBufferRenderer();
  69293. geometryRenderer.enablePosition = true;
  69294. var geometry = geometryRenderer.getGBuffer();
  69295. // Base post-process
  69296. 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));
  69297. var depthValues = BABYLON.Vector2.Zero();
  69298. this.volumetricLightPostProcess.onApply = function (effect) {
  69299. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  69300. var generator = _this.sourceLight.getShadowGenerator();
  69301. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  69302. effect.setTexture("positionSampler", geometry.textures[2]);
  69303. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  69304. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  69305. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  69306. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  69307. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  69308. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  69309. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  69310. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  69311. effect.setVector2("depthValues", depthValues);
  69312. }
  69313. };
  69314. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  69315. // Smooth
  69316. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  69317. // Merge
  69318. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  69319. this.volumetricLightMergePostProces.onApply = function (effect) {
  69320. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  69321. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  69322. };
  69323. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  69324. };
  69325. // Create luminance
  69326. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  69327. var _this = this;
  69328. // Create luminance
  69329. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  69330. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  69331. var offsets = [];
  69332. this.luminancePostProcess.onApply = function (effect) {
  69333. var sU = (1.0 / _this.luminancePostProcess.width);
  69334. var sV = (1.0 / _this.luminancePostProcess.height);
  69335. offsets[0] = -0.5 * sU;
  69336. offsets[1] = 0.5 * sV;
  69337. offsets[2] = 0.5 * sU;
  69338. offsets[3] = 0.5 * sV;
  69339. offsets[4] = -0.5 * sU;
  69340. offsets[5] = -0.5 * sV;
  69341. offsets[6] = 0.5 * sU;
  69342. offsets[7] = -0.5 * sV;
  69343. effect.setArray2("lumOffsets", offsets);
  69344. };
  69345. // Add to pipeline
  69346. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  69347. // Create down sample luminance
  69348. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  69349. var size = Math.pow(3, i);
  69350. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  69351. if (i === 0) {
  69352. defines += "#define FINAL_DOWN_SAMPLER";
  69353. }
  69354. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  69355. this.luminanceDownSamplePostProcesses.push(postProcess);
  69356. }
  69357. // Create callbacks and add effects
  69358. var lastLuminance = this.luminancePostProcess;
  69359. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  69360. var downSampleOffsets = new Array(18);
  69361. pp.onApply = function (effect) {
  69362. if (!lastLuminance) {
  69363. return;
  69364. }
  69365. var id = 0;
  69366. for (var x = -1; x < 2; x++) {
  69367. for (var y = -1; y < 2; y++) {
  69368. downSampleOffsets[id] = x / lastLuminance.width;
  69369. downSampleOffsets[id + 1] = y / lastLuminance.height;
  69370. id += 2;
  69371. }
  69372. }
  69373. effect.setArray2("dsOffsets", downSampleOffsets);
  69374. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  69375. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  69376. lastLuminance = _this.luminancePostProcess;
  69377. }
  69378. else {
  69379. lastLuminance = pp;
  69380. }
  69381. };
  69382. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  69383. pp.onAfterRender = function (effect) {
  69384. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  69385. 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);
  69386. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  69387. };
  69388. }
  69389. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  69390. });
  69391. };
  69392. // Create HDR post-process
  69393. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  69394. var _this = this;
  69395. 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);
  69396. var outputLiminance = 1;
  69397. var time = 0;
  69398. var lastTime = 0;
  69399. this.hdrPostProcess.onApply = function (effect) {
  69400. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  69401. time += scene.getEngine().getDeltaTime();
  69402. if (outputLiminance < 0) {
  69403. outputLiminance = _this._hdrCurrentLuminance;
  69404. }
  69405. else {
  69406. var dt = (lastTime - time) / 1000.0;
  69407. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  69408. outputLiminance += _this.hdrDecreaseRate * dt;
  69409. }
  69410. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  69411. outputLiminance -= _this.hdrIncreaseRate * dt;
  69412. }
  69413. else {
  69414. outputLiminance = _this._hdrCurrentLuminance;
  69415. }
  69416. }
  69417. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  69418. effect.setFloat("averageLuminance", outputLiminance);
  69419. lastTime = time;
  69420. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  69421. };
  69422. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  69423. };
  69424. // Create lens flare post-process
  69425. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  69426. var _this = this;
  69427. 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);
  69428. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  69429. this._createBlurPostProcesses(scene, ratio / 4, 2);
  69430. 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);
  69431. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  69432. var resolution = new BABYLON.Vector2(0, 0);
  69433. // Lens flare
  69434. this.lensFlarePostProcess.onApply = function (effect) {
  69435. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  69436. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  69437. effect.setFloat("strength", _this.lensFlareStrength);
  69438. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  69439. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  69440. // Shift
  69441. resolution.x = _this.lensFlarePostProcess.width;
  69442. resolution.y = _this.lensFlarePostProcess.height;
  69443. effect.setVector2("resolution", resolution);
  69444. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  69445. };
  69446. // Compose
  69447. 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);
  69448. 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);
  69449. this.lensFlareComposePostProcess.onApply = function (effect) {
  69450. if (!_this._scene.activeCamera) {
  69451. return;
  69452. }
  69453. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  69454. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  69455. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  69456. // Lens start rotation matrix
  69457. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  69458. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  69459. 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));
  69460. camRot *= 4.0;
  69461. 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);
  69462. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  69463. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  69464. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  69465. };
  69466. };
  69467. // Create depth-of-field post-process
  69468. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  69469. var _this = this;
  69470. 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);
  69471. this.depthOfFieldPostProcess.onApply = function (effect) {
  69472. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  69473. effect.setTexture("depthSampler", _this._getDepthTexture());
  69474. effect.setFloat("distance", _this.depthOfFieldDistance);
  69475. };
  69476. // Add to pipeline
  69477. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  69478. };
  69479. // Create motion blur post-process
  69480. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  69481. var _this = this;
  69482. 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);
  69483. var motionScale = 0;
  69484. var prevViewProjection = BABYLON.Matrix.Identity();
  69485. var invViewProjection = BABYLON.Matrix.Identity();
  69486. var viewProjection = BABYLON.Matrix.Identity();
  69487. var screenSize = BABYLON.Vector2.Zero();
  69488. this.motionBlurPostProcess.onApply = function (effect) {
  69489. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  69490. viewProjection.invertToRef(invViewProjection);
  69491. effect.setMatrix("inverseViewProjection", invViewProjection);
  69492. effect.setMatrix("prevViewProjection", prevViewProjection);
  69493. prevViewProjection = viewProjection;
  69494. screenSize.x = _this.motionBlurPostProcess.width;
  69495. screenSize.y = _this.motionBlurPostProcess.height;
  69496. effect.setVector2("screenSize", screenSize);
  69497. motionScale = scene.getEngine().getFps() / 60.0;
  69498. effect.setFloat("motionScale", motionScale);
  69499. effect.setFloat("motionStrength", _this.motionStrength);
  69500. effect.setTexture("depthSampler", _this._getDepthTexture());
  69501. };
  69502. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  69503. };
  69504. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  69505. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  69506. var renderer = this._scene.enableGeometryBufferRenderer();
  69507. return renderer.getGBuffer().textures[0];
  69508. }
  69509. return this._scene.enableDepthRenderer().getDepthMap();
  69510. };
  69511. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  69512. for (var i = 0; i < this._cameras.length; i++) {
  69513. var camera = this._cameras[i];
  69514. if (this.originalPostProcess) {
  69515. this.originalPostProcess.dispose(camera);
  69516. }
  69517. if (this.downSampleX4PostProcess) {
  69518. this.downSampleX4PostProcess.dispose(camera);
  69519. }
  69520. if (this.brightPassPostProcess) {
  69521. this.brightPassPostProcess.dispose(camera);
  69522. }
  69523. if (this.textureAdderPostProcess) {
  69524. this.textureAdderPostProcess.dispose(camera);
  69525. }
  69526. if (this.textureAdderFinalPostProcess) {
  69527. this.textureAdderFinalPostProcess.dispose(camera);
  69528. }
  69529. if (this.volumetricLightPostProcess) {
  69530. this.volumetricLightPostProcess.dispose(camera);
  69531. }
  69532. if (this.volumetricLightSmoothXPostProcess) {
  69533. this.volumetricLightSmoothXPostProcess.dispose(camera);
  69534. }
  69535. if (this.volumetricLightSmoothYPostProcess) {
  69536. this.volumetricLightSmoothYPostProcess.dispose(camera);
  69537. }
  69538. if (this.volumetricLightMergePostProces) {
  69539. this.volumetricLightMergePostProces.dispose(camera);
  69540. }
  69541. if (this.volumetricLightFinalPostProcess) {
  69542. this.volumetricLightFinalPostProcess.dispose(camera);
  69543. }
  69544. if (this.lensFlarePostProcess) {
  69545. this.lensFlarePostProcess.dispose(camera);
  69546. }
  69547. if (this.lensFlareComposePostProcess) {
  69548. this.lensFlareComposePostProcess.dispose(camera);
  69549. }
  69550. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  69551. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  69552. }
  69553. if (this.luminancePostProcess) {
  69554. this.luminancePostProcess.dispose(camera);
  69555. }
  69556. if (this.hdrPostProcess) {
  69557. this.hdrPostProcess.dispose(camera);
  69558. }
  69559. if (this.hdrFinalPostProcess) {
  69560. this.hdrFinalPostProcess.dispose(camera);
  69561. }
  69562. if (this.depthOfFieldPostProcess) {
  69563. this.depthOfFieldPostProcess.dispose(camera);
  69564. }
  69565. if (this.motionBlurPostProcess) {
  69566. this.motionBlurPostProcess.dispose(camera);
  69567. }
  69568. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  69569. this.blurHPostProcesses[j].dispose(camera);
  69570. }
  69571. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  69572. this.blurVPostProcesses[j].dispose(camera);
  69573. }
  69574. }
  69575. this.originalPostProcess = null;
  69576. this.downSampleX4PostProcess = null;
  69577. this.brightPassPostProcess = null;
  69578. this.textureAdderPostProcess = null;
  69579. this.textureAdderFinalPostProcess = null;
  69580. this.volumetricLightPostProcess = null;
  69581. this.volumetricLightSmoothXPostProcess = null;
  69582. this.volumetricLightSmoothYPostProcess = null;
  69583. this.volumetricLightMergePostProces = null;
  69584. this.volumetricLightFinalPostProcess = null;
  69585. this.lensFlarePostProcess = null;
  69586. this.lensFlareComposePostProcess = null;
  69587. this.luminancePostProcess = null;
  69588. this.hdrPostProcess = null;
  69589. this.hdrFinalPostProcess = null;
  69590. this.depthOfFieldPostProcess = null;
  69591. this.motionBlurPostProcess = null;
  69592. this.luminanceDownSamplePostProcesses = [];
  69593. this.blurHPostProcesses = [];
  69594. this.blurVPostProcesses = [];
  69595. };
  69596. // Dispose
  69597. StandardRenderingPipeline.prototype.dispose = function () {
  69598. this._disposePostProcesses();
  69599. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  69600. _super.prototype.dispose.call(this);
  69601. };
  69602. // Serialize rendering pipeline
  69603. StandardRenderingPipeline.prototype.serialize = function () {
  69604. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  69605. serializationObject.customType = "StandardRenderingPipeline";
  69606. return serializationObject;
  69607. };
  69608. /**
  69609. * Static members
  69610. */
  69611. // Parse serialized pipeline
  69612. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  69613. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  69614. };
  69615. // Luminance steps
  69616. StandardRenderingPipeline.LuminanceSteps = 6;
  69617. __decorate([
  69618. BABYLON.serialize()
  69619. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  69620. __decorate([
  69621. BABYLON.serialize()
  69622. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  69623. __decorate([
  69624. BABYLON.serialize()
  69625. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  69626. __decorate([
  69627. BABYLON.serialize()
  69628. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  69629. __decorate([
  69630. BABYLON.serializeAsTexture("lensTexture")
  69631. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  69632. __decorate([
  69633. BABYLON.serialize()
  69634. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  69635. __decorate([
  69636. BABYLON.serialize()
  69637. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  69638. __decorate([
  69639. BABYLON.serialize()
  69640. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  69641. __decorate([
  69642. BABYLON.serialize()
  69643. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  69644. __decorate([
  69645. BABYLON.serialize()
  69646. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  69647. __decorate([
  69648. BABYLON.serialize()
  69649. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  69650. __decorate([
  69651. BABYLON.serializeAsTexture("lensColorTexture")
  69652. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  69653. __decorate([
  69654. BABYLON.serialize()
  69655. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  69656. __decorate([
  69657. BABYLON.serialize()
  69658. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  69659. __decorate([
  69660. BABYLON.serialize()
  69661. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  69662. __decorate([
  69663. BABYLON.serialize()
  69664. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  69665. __decorate([
  69666. BABYLON.serializeAsTexture("lensStarTexture")
  69667. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  69668. __decorate([
  69669. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  69670. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  69671. __decorate([
  69672. BABYLON.serialize()
  69673. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  69674. __decorate([
  69675. BABYLON.serialize()
  69676. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  69677. __decorate([
  69678. BABYLON.serialize()
  69679. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  69680. __decorate([
  69681. BABYLON.serialize()
  69682. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  69683. __decorate([
  69684. BABYLON.serialize()
  69685. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  69686. __decorate([
  69687. BABYLON.serialize()
  69688. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  69689. __decorate([
  69690. BABYLON.serialize()
  69691. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  69692. __decorate([
  69693. BABYLON.serialize()
  69694. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  69695. __decorate([
  69696. BABYLON.serialize()
  69697. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  69698. __decorate([
  69699. BABYLON.serialize()
  69700. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  69701. __decorate([
  69702. BABYLON.serialize()
  69703. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  69704. __decorate([
  69705. BABYLON.serialize()
  69706. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  69707. return StandardRenderingPipeline;
  69708. }(BABYLON.PostProcessRenderPipeline));
  69709. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  69710. })(BABYLON || (BABYLON = {}));
  69711. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  69712. "use strict";
  69713. var BABYLON;
  69714. (function (BABYLON) {
  69715. var FxaaPostProcess = /** @class */ (function (_super) {
  69716. __extends(FxaaPostProcess, _super);
  69717. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  69718. if (camera === void 0) { camera = null; }
  69719. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69720. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  69721. _this.onApplyObservable.add(function (effect) {
  69722. var texelSize = _this.texelSize;
  69723. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  69724. });
  69725. return _this;
  69726. }
  69727. return FxaaPostProcess;
  69728. }(BABYLON.PostProcess));
  69729. BABYLON.FxaaPostProcess = FxaaPostProcess;
  69730. })(BABYLON || (BABYLON = {}));
  69731. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  69732. "use strict";
  69733. var BABYLON;
  69734. (function (BABYLON) {
  69735. /**
  69736. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  69737. */
  69738. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  69739. __extends(ChromaticAberrationPostProcess, _super);
  69740. /**
  69741. * Creates a new instance of @see ChromaticAberrationPostProcess
  69742. * @param name The name of the effect.
  69743. * @param screenWidth The width of the screen to apply the effect on.
  69744. * @param screenHeight The height of the screen to apply the effect on.
  69745. * @param options The required width/height ratio to downsize to before computing the render pass.
  69746. * @param camera The camera to apply the render pass to.
  69747. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69748. * @param engine The engine which the post process will be applied. (default: current engine)
  69749. * @param reusable If the post process can be reused on the same frame. (default: false)
  69750. * @param textureType Type of textures used when performing the post process. (default: 0)
  69751. * @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)
  69752. */
  69753. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  69754. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69755. if (blockCompilation === void 0) { blockCompilation = false; }
  69756. 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;
  69757. /**
  69758. * The amount of seperation of rgb channels (default: 30)
  69759. */
  69760. _this.aberrationAmount = 30;
  69761. /**
  69762. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  69763. */
  69764. _this.radialIntensity = 0;
  69765. /**
  69766. * 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))
  69767. */
  69768. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  69769. /**
  69770. * 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))
  69771. */
  69772. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  69773. _this.onApplyObservable.add(function (effect) {
  69774. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  69775. effect.setFloat('screen_width', screenWidth);
  69776. effect.setFloat('screen_height', screenHeight);
  69777. effect.setFloat('radialIntensity', _this.radialIntensity);
  69778. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  69779. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  69780. });
  69781. return _this;
  69782. }
  69783. return ChromaticAberrationPostProcess;
  69784. }(BABYLON.PostProcess));
  69785. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  69786. })(BABYLON || (BABYLON = {}));
  69787. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  69788. "use strict";
  69789. var BABYLON;
  69790. (function (BABYLON) {
  69791. /**
  69792. * The SharpenPostProcess applies a sharpen kernel to every pixel
  69793. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  69794. */
  69795. var SharpenPostProcess = /** @class */ (function (_super) {
  69796. __extends(SharpenPostProcess, _super);
  69797. /**
  69798. * Creates a new instance of @see ConvolutionPostProcess
  69799. * @param name The name of the effect.
  69800. * @param options The required width/height ratio to downsize to before computing the render pass.
  69801. * @param camera The camera to apply the render pass to.
  69802. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69803. * @param engine The engine which the post process will be applied. (default: current engine)
  69804. * @param reusable If the post process can be reused on the same frame. (default: false)
  69805. * @param textureType Type of textures used when performing the post process. (default: 0)
  69806. * @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)
  69807. */
  69808. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  69809. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69810. if (blockCompilation === void 0) { blockCompilation = false; }
  69811. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  69812. /**
  69813. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  69814. */
  69815. _this.colorAmount = 1.0;
  69816. /**
  69817. * How much sharpness should be applied (default: 0.3)
  69818. */
  69819. _this.edgeAmount = 0.3;
  69820. _this.onApply = function (effect) {
  69821. effect.setFloat2("screenSize", _this.width, _this.height);
  69822. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  69823. };
  69824. return _this;
  69825. }
  69826. return SharpenPostProcess;
  69827. }(BABYLON.PostProcess));
  69828. BABYLON.SharpenPostProcess = SharpenPostProcess;
  69829. })(BABYLON || (BABYLON = {}));
  69830. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  69831. "use strict";
  69832. var BABYLON;
  69833. (function (BABYLON) {
  69834. /**
  69835. * The Blur Post Process which blurs an image based on a kernel and direction.
  69836. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  69837. */
  69838. var BlurPostProcess = /** @class */ (function (_super) {
  69839. __extends(BlurPostProcess, _super);
  69840. /**
  69841. * Creates a new instance of @see BlurPostProcess
  69842. * @param name The name of the effect.
  69843. * @param direction The direction in which to blur the image.
  69844. * @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.
  69845. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  69846. * @param camera The camera to apply the render pass to.
  69847. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69848. * @param engine The engine which the post process will be applied. (default: current engine)
  69849. * @param reusable If the post process can be reused on the same frame. (default: false)
  69850. * @param textureType Type of textures used when performing the post process. (default: 0)
  69851. * @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)
  69852. */
  69853. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  69854. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  69855. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69856. if (defines === void 0) { defines = ""; }
  69857. if (blockCompilation === void 0) { blockCompilation = false; }
  69858. 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;
  69859. _this.direction = direction;
  69860. _this.blockCompilation = blockCompilation;
  69861. _this._packedFloat = false;
  69862. _this._staticDefines = "";
  69863. _this._staticDefines = defines;
  69864. _this.onApplyObservable.add(function (effect) {
  69865. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  69866. });
  69867. _this.kernel = kernel;
  69868. return _this;
  69869. }
  69870. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  69871. /**
  69872. * Gets the length in pixels of the blur sample region
  69873. */
  69874. get: function () {
  69875. return this._idealKernel;
  69876. },
  69877. /**
  69878. * Sets the length in pixels of the blur sample region
  69879. */
  69880. set: function (v) {
  69881. if (this._idealKernel === v) {
  69882. return;
  69883. }
  69884. v = Math.max(v, 1);
  69885. this._idealKernel = v;
  69886. this._kernel = this._nearestBestKernel(v);
  69887. if (!this.blockCompilation) {
  69888. this._updateParameters();
  69889. }
  69890. },
  69891. enumerable: true,
  69892. configurable: true
  69893. });
  69894. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  69895. /**
  69896. * Gets wether or not the blur is unpacking/repacking floats
  69897. */
  69898. get: function () {
  69899. return this._packedFloat;
  69900. },
  69901. /**
  69902. * Sets wether or not the blur needs to unpack/repack floats
  69903. */
  69904. set: function (v) {
  69905. if (this._packedFloat === v) {
  69906. return;
  69907. }
  69908. this._packedFloat = v;
  69909. if (!this.blockCompilation) {
  69910. this._updateParameters();
  69911. }
  69912. },
  69913. enumerable: true,
  69914. configurable: true
  69915. });
  69916. /**
  69917. * Updates the effect with the current post process compile time values and recompiles the shader.
  69918. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  69919. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  69920. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  69921. * @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
  69922. * @param onCompiled Called when the shader has been compiled.
  69923. * @param onError Called if there is an error when compiling a shader.
  69924. */
  69925. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  69926. if (defines === void 0) { defines = null; }
  69927. if (uniforms === void 0) { uniforms = null; }
  69928. if (samplers === void 0) { samplers = null; }
  69929. this._updateParameters(onCompiled, onError);
  69930. };
  69931. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  69932. // Generate sampling offsets and weights
  69933. var N = this._kernel;
  69934. var centerIndex = (N - 1) / 2;
  69935. // Generate Gaussian sampling weights over kernel
  69936. var offsets = [];
  69937. var weights = [];
  69938. var totalWeight = 0;
  69939. for (var i = 0; i < N; i++) {
  69940. var u = i / (N - 1);
  69941. var w = this._gaussianWeight(u * 2.0 - 1);
  69942. offsets[i] = (i - centerIndex);
  69943. weights[i] = w;
  69944. totalWeight += w;
  69945. }
  69946. // Normalize weights
  69947. for (var i = 0; i < weights.length; i++) {
  69948. weights[i] /= totalWeight;
  69949. }
  69950. // Optimize: combine samples to take advantage of hardware linear sampling
  69951. // Walk from left to center, combining pairs (symmetrically)
  69952. var linearSamplingWeights = [];
  69953. var linearSamplingOffsets = [];
  69954. var linearSamplingMap = [];
  69955. for (var i = 0; i <= centerIndex; i += 2) {
  69956. var j = Math.min(i + 1, Math.floor(centerIndex));
  69957. var singleCenterSample = i === j;
  69958. if (singleCenterSample) {
  69959. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  69960. }
  69961. else {
  69962. var sharedCell = j === centerIndex;
  69963. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  69964. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  69965. if (offsetLinear === 0) {
  69966. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  69967. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  69968. }
  69969. else {
  69970. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  69971. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  69972. }
  69973. }
  69974. }
  69975. for (var i = 0; i < linearSamplingMap.length; i++) {
  69976. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  69977. linearSamplingWeights[i] = linearSamplingMap[i].w;
  69978. }
  69979. // Replace with optimized
  69980. offsets = linearSamplingOffsets;
  69981. weights = linearSamplingWeights;
  69982. // Generate shaders
  69983. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  69984. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  69985. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  69986. var defines = "";
  69987. defines += this._staticDefines;
  69988. for (var i = 0; i < varyingCount; i++) {
  69989. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  69990. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  69991. }
  69992. var depCount = 0;
  69993. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  69994. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  69995. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  69996. depCount++;
  69997. }
  69998. if (this.packedFloat) {
  69999. defines += "#define PACKEDFLOAT 1";
  70000. }
  70001. _super.prototype.updateEffect.call(this, defines, null, null, {
  70002. varyingCount: varyingCount,
  70003. depCount: depCount
  70004. }, onCompiled, onError);
  70005. };
  70006. /**
  70007. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  70008. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  70009. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  70010. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  70011. * The gaps between physical kernels are compensated for in the weighting of the samples
  70012. * @param idealKernel Ideal blur kernel.
  70013. * @return Nearest best kernel.
  70014. */
  70015. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  70016. var v = Math.round(idealKernel);
  70017. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  70018. var k = _a[_i];
  70019. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  70020. return Math.max(k, 3);
  70021. }
  70022. }
  70023. return Math.max(v, 3);
  70024. };
  70025. /**
  70026. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  70027. * @param x The point on the Gaussian distribution to sample.
  70028. * @return the value of the Gaussian function at x.
  70029. */
  70030. BlurPostProcess.prototype._gaussianWeight = function (x) {
  70031. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  70032. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  70033. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  70034. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  70035. // truncated at around 1.3% of peak strength.
  70036. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  70037. var sigma = (1 / 3);
  70038. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  70039. var exponent = -((x * x) / (2.0 * sigma * sigma));
  70040. var weight = (1.0 / denominator) * Math.exp(exponent);
  70041. return weight;
  70042. };
  70043. /**
  70044. * Generates a string that can be used as a floating point number in GLSL.
  70045. * @param x Value to print.
  70046. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  70047. * @return GLSL float string.
  70048. */
  70049. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  70050. if (decimalFigures === void 0) { decimalFigures = 8; }
  70051. return x.toFixed(decimalFigures).replace(/0+$/, '');
  70052. };
  70053. return BlurPostProcess;
  70054. }(BABYLON.PostProcess));
  70055. BABYLON.BlurPostProcess = BlurPostProcess;
  70056. })(BABYLON || (BABYLON = {}));
  70057. //# sourceMappingURL=babylon.blurPostProcess.js.map
  70058. "use strict";
  70059. var BABYLON;
  70060. (function (BABYLON) {
  70061. /**
  70062. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  70063. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  70064. * based on samples that have a large difference in distance than the center pixel.
  70065. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  70066. */
  70067. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  70068. __extends(DepthOfFieldBlurPostProcess, _super);
  70069. /**
  70070. * Creates a new instance of @see CircleOfConfusionPostProcess
  70071. * @param name The name of the effect.
  70072. * @param scene The scene the effect belongs to.
  70073. * @param direction The direction the blur should be applied.
  70074. * @param kernel The size of the kernel used to blur.
  70075. * @param options The required width/height ratio to downsize to before computing the render pass.
  70076. * @param camera The camera to apply the render pass to.
  70077. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  70078. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  70079. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  70080. * @param engine The engine which the post process will be applied. (default: current engine)
  70081. * @param reusable If the post process can be reused on the same frame. (default: false)
  70082. * @param textureType Type of textures used when performing the post process. (default: 0)
  70083. * @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)
  70084. */
  70085. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  70086. if (imageToBlur === void 0) { imageToBlur = null; }
  70087. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  70088. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70089. if (blockCompilation === void 0) { blockCompilation = false; }
  70090. 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;
  70091. _this.direction = direction;
  70092. _this.onApplyObservable.add(function (effect) {
  70093. if (imageToBlur != null) {
  70094. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  70095. }
  70096. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  70097. if (scene.activeCamera) {
  70098. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  70099. }
  70100. });
  70101. return _this;
  70102. }
  70103. return DepthOfFieldBlurPostProcess;
  70104. }(BABYLON.BlurPostProcess));
  70105. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  70106. })(BABYLON || (BABYLON = {}));
  70107. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  70108. "use strict";
  70109. var BABYLON;
  70110. (function (BABYLON) {
  70111. /**
  70112. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  70113. */
  70114. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  70115. __extends(DepthOfFieldMergePostProcess, _super);
  70116. /**
  70117. * Creates a new instance of @see CircleOfConfusionPostProcess
  70118. * @param name The name of the effect.
  70119. * @param original The non-blurred image to be modified
  70120. * @param circleOfConfusion The circle of confusion post process that will determine how blurred each pixel should become.
  70121. * @param blurSteps Incrimental bluring post processes.
  70122. * @param options The required width/height ratio to downsize to before computing the render pass.
  70123. * @param camera The camera to apply the render pass to.
  70124. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  70125. * @param engine The engine which the post process will be applied. (default: current engine)
  70126. * @param reusable If the post process can be reused on the same frame. (default: false)
  70127. * @param textureType Type of textures used when performing the post process. (default: 0)
  70128. * @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)
  70129. */
  70130. function DepthOfFieldMergePostProcess(name, original, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  70131. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70132. if (blockCompilation === void 0) { blockCompilation = false; }
  70133. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  70134. _this.blurSteps = blurSteps;
  70135. _this.onApplyObservable.add(function (effect) {
  70136. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  70137. effect.setTextureFromPostProcess("textureSampler", original);
  70138. blurSteps.forEach(function (step, index) {
  70139. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  70140. });
  70141. });
  70142. if (!blockCompilation) {
  70143. _this.updateEffect();
  70144. }
  70145. return _this;
  70146. }
  70147. /**
  70148. * Updates the effect with the current post process compile time values and recompiles the shader.
  70149. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  70150. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  70151. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  70152. * @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
  70153. * @param onCompiled Called when the shader has been compiled.
  70154. * @param onError Called if there is an error when compiling a shader.
  70155. */
  70156. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  70157. if (defines === void 0) { defines = null; }
  70158. if (uniforms === void 0) { uniforms = null; }
  70159. if (samplers === void 0) { samplers = null; }
  70160. _super.prototype.updateEffect.call(this, defines ? defines : "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n", uniforms, samplers, indexParameters, onCompiled, onError);
  70161. };
  70162. return DepthOfFieldMergePostProcess;
  70163. }(BABYLON.PostProcess));
  70164. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  70165. })(BABYLON || (BABYLON = {}));
  70166. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  70167. "use strict";
  70168. var BABYLON;
  70169. (function (BABYLON) {
  70170. /**
  70171. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  70172. */
  70173. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  70174. __extends(CircleOfConfusionPostProcess, _super);
  70175. /**
  70176. * Creates a new instance of @see CircleOfConfusionPostProcess
  70177. * @param name The name of the effect.
  70178. * @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.
  70179. * @param options The required width/height ratio to downsize to before computing the render pass.
  70180. * @param camera The camera to apply the render pass to.
  70181. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  70182. * @param engine The engine which the post process will be applied. (default: current engine)
  70183. * @param reusable If the post process can be reused on the same frame. (default: false)
  70184. * @param textureType Type of textures used when performing the post process. (default: 0)
  70185. * @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)
  70186. */
  70187. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  70188. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70189. if (blockCompilation === void 0) { blockCompilation = false; }
  70190. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  70191. /**
  70192. * 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.
  70193. */
  70194. _this.lensSize = 50;
  70195. /**
  70196. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  70197. */
  70198. _this.fStop = 1.4;
  70199. /**
  70200. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  70201. */
  70202. _this.focusDistance = 2000;
  70203. /**
  70204. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  70205. */
  70206. _this.focalLength = 50;
  70207. _this._depthTexture = null;
  70208. _this._depthTexture = depthTexture;
  70209. _this.onApplyObservable.add(function (effect) {
  70210. if (!_this._depthTexture) {
  70211. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  70212. return;
  70213. }
  70214. effect.setTexture("depthSampler", _this._depthTexture);
  70215. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  70216. var aperture = _this.lensSize / _this.fStop;
  70217. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  70218. effect.setFloat('focusDistance', _this.focusDistance);
  70219. effect.setFloat('cocPrecalculation', cocPrecalculation);
  70220. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  70221. });
  70222. return _this;
  70223. }
  70224. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  70225. /**
  70226. * 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.
  70227. */
  70228. set: function (value) {
  70229. this._depthTexture = value;
  70230. },
  70231. enumerable: true,
  70232. configurable: true
  70233. });
  70234. return CircleOfConfusionPostProcess;
  70235. }(BABYLON.PostProcess));
  70236. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  70237. })(BABYLON || (BABYLON = {}));
  70238. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  70239. "use strict";
  70240. var BABYLON;
  70241. (function (BABYLON) {
  70242. /**
  70243. * Specifies the level of max blur that should be applied when using the depth of field effect
  70244. */
  70245. var DepthOfFieldEffectBlurLevel;
  70246. (function (DepthOfFieldEffectBlurLevel) {
  70247. /**
  70248. * Subtle blur
  70249. */
  70250. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  70251. /**
  70252. * Medium blur
  70253. */
  70254. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  70255. /**
  70256. * Large blur
  70257. */
  70258. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  70259. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  70260. ;
  70261. /**
  70262. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  70263. */
  70264. var DepthOfFieldEffect = /** @class */ (function (_super) {
  70265. __extends(DepthOfFieldEffect, _super);
  70266. /**
  70267. * Creates a new instance of @see DepthOfFieldEffect
  70268. * @param scene The scene the effect belongs to.
  70269. * @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.
  70270. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  70271. * @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)
  70272. */
  70273. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  70274. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  70275. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  70276. if (blockCompilation === void 0) { blockCompilation = false; }
  70277. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  70278. return _this._effects;
  70279. }, true) || this;
  70280. _this._effects = [];
  70281. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  70282. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  70283. // 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)
  70284. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  70285. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  70286. _this._depthOfFieldBlurY = [];
  70287. _this._depthOfFieldBlurX = [];
  70288. var blurCount = 1;
  70289. var kernelSize = 15;
  70290. switch (blurLevel) {
  70291. case DepthOfFieldEffectBlurLevel.High: {
  70292. blurCount = 3;
  70293. kernelSize = 51;
  70294. break;
  70295. }
  70296. case DepthOfFieldEffectBlurLevel.Medium: {
  70297. blurCount = 2;
  70298. kernelSize = 31;
  70299. break;
  70300. }
  70301. default: {
  70302. kernelSize = 15;
  70303. blurCount = 1;
  70304. break;
  70305. }
  70306. }
  70307. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  70308. for (var i = 0; i < blurCount; i++) {
  70309. var blurY = new BABYLON.DepthOfFieldBlurPostProcess("verticle blur", scene, new BABYLON.Vector2(0, 1.0), adjustedKernelSize, 1.0 / Math.pow(2, i), null, _this._circleOfConfusion, i == 0 ? _this._circleOfConfusion : null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  70310. blurY.autoClear = false;
  70311. var blurX = new BABYLON.DepthOfFieldBlurPostProcess("horizontal blur", scene, new BABYLON.Vector2(1.0, 0), adjustedKernelSize, 1.0 / Math.pow(2, i), null, _this._circleOfConfusion, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  70312. blurX.autoClear = false;
  70313. _this._depthOfFieldBlurY.push(blurY);
  70314. _this._depthOfFieldBlurX.push(blurX);
  70315. }
  70316. // Merge blurred images with original image based on circleOfConfusion
  70317. _this._depthOfFieldMerge = new BABYLON.DepthOfFieldMergePostProcess("depthOfFieldMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  70318. _this._depthOfFieldMerge.autoClear = false;
  70319. // Set all post processes on the effect.
  70320. _this._effects = [_this._circleOfConfusion];
  70321. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  70322. _this._effects.push(_this._depthOfFieldBlurY[i]);
  70323. _this._effects.push(_this._depthOfFieldBlurX[i]);
  70324. }
  70325. _this._effects.push(_this._depthOfFieldMerge);
  70326. return _this;
  70327. }
  70328. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  70329. get: function () {
  70330. return this._circleOfConfusion.focalLength;
  70331. },
  70332. /**
  70333. * The focal the length of the camera used in the effect
  70334. */
  70335. set: function (value) {
  70336. this._circleOfConfusion.focalLength = value;
  70337. },
  70338. enumerable: true,
  70339. configurable: true
  70340. });
  70341. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  70342. get: function () {
  70343. return this._circleOfConfusion.fStop;
  70344. },
  70345. /**
  70346. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  70347. */
  70348. set: function (value) {
  70349. this._circleOfConfusion.fStop = value;
  70350. },
  70351. enumerable: true,
  70352. configurable: true
  70353. });
  70354. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  70355. get: function () {
  70356. return this._circleOfConfusion.focusDistance;
  70357. },
  70358. /**
  70359. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  70360. */
  70361. set: function (value) {
  70362. this._circleOfConfusion.focusDistance = value;
  70363. },
  70364. enumerable: true,
  70365. configurable: true
  70366. });
  70367. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  70368. get: function () {
  70369. return this._circleOfConfusion.lensSize;
  70370. },
  70371. /**
  70372. * 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.
  70373. */
  70374. set: function (value) {
  70375. this._circleOfConfusion.lensSize = value;
  70376. },
  70377. enumerable: true,
  70378. configurable: true
  70379. });
  70380. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  70381. /**
  70382. * 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.
  70383. */
  70384. set: function (value) {
  70385. this._circleOfConfusion.depthTexture = value;
  70386. },
  70387. enumerable: true,
  70388. configurable: true
  70389. });
  70390. /**
  70391. * Disposes each of the internal effects for a given camera.
  70392. * @param camera The camera to dispose the effect on.
  70393. */
  70394. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  70395. this._circleOfConfusion.dispose(camera);
  70396. this._depthOfFieldBlurX.forEach(function (element) {
  70397. element.dispose(camera);
  70398. });
  70399. this._depthOfFieldBlurY.forEach(function (element) {
  70400. element.dispose(camera);
  70401. });
  70402. this._depthOfFieldMerge.dispose(camera);
  70403. };
  70404. /**
  70405. * Internal
  70406. */
  70407. DepthOfFieldEffect.prototype._updateEffects = function () {
  70408. for (var effect in this._effects) {
  70409. this._effects[effect].updateEffect();
  70410. }
  70411. };
  70412. /**
  70413. * Internal
  70414. * @returns if all the contained post processes are ready.
  70415. */
  70416. DepthOfFieldEffect.prototype._isReady = function () {
  70417. for (var effect in this._effects) {
  70418. if (!this._effects[effect].isReady()) {
  70419. return false;
  70420. }
  70421. }
  70422. return true;
  70423. };
  70424. return DepthOfFieldEffect;
  70425. }(BABYLON.PostProcessRenderEffect));
  70426. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  70427. })(BABYLON || (BABYLON = {}));
  70428. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  70429. "use strict";
  70430. var BABYLON;
  70431. (function (BABYLON) {
  70432. /**
  70433. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  70434. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  70435. */
  70436. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  70437. __extends(DefaultRenderingPipeline, _super);
  70438. /**
  70439. * @constructor
  70440. * @param {string} name - The rendering pipeline name
  70441. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  70442. * @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)
  70443. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  70444. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  70445. */
  70446. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  70447. if (automaticBuild === void 0) { automaticBuild = true; }
  70448. var _this = _super.call(this, scene.getEngine(), name) || this;
  70449. _this._originalCameras = [];
  70450. /**
  70451. * ID of the sharpen post process,
  70452. */
  70453. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  70454. /**
  70455. * ID of the pass post process used for bloom,
  70456. */
  70457. _this.PassPostProcessId = "PassPostProcessEffect";
  70458. /**
  70459. * ID of the highlight post process used for bloom,
  70460. */
  70461. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  70462. /**
  70463. * ID of the blurX post process used for bloom,
  70464. */
  70465. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  70466. /**
  70467. * ID of the blurY post process used for bloom,
  70468. */
  70469. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  70470. /**
  70471. * ID of the copy back post process used for bloom,
  70472. */
  70473. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  70474. /**
  70475. * ID of the image processing post process;
  70476. */
  70477. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  70478. /**
  70479. * ID of the Fast Approximate Anti-Aliasing post process;
  70480. */
  70481. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  70482. /**
  70483. * ID of the final merge post process;
  70484. */
  70485. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  70486. /**
  70487. * ID of the chromatic aberration post process,
  70488. */
  70489. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  70490. /**
  70491. * Animations which can be used to tweak settings over a period of time
  70492. */
  70493. _this.animations = [];
  70494. // Values
  70495. _this._sharpenEnabled = false;
  70496. _this._bloomEnabled = false;
  70497. _this._depthOfFieldEnabled = false;
  70498. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  70499. _this._fxaaEnabled = false;
  70500. _this._msaaEnabled = false;
  70501. _this._imageProcessingEnabled = true;
  70502. _this._bloomScale = 0.6;
  70503. _this._chromaticAberrationEnabled = false;
  70504. _this._buildAllowed = true;
  70505. /**
  70506. * Specifies the size of the bloom blur kernel, relative to the final output size
  70507. */
  70508. _this.bloomKernel = 64;
  70509. /**
  70510. * Specifies the weight of the bloom in the final rendering
  70511. */
  70512. _this._bloomWeight = 0.15;
  70513. _this._prevPostProcess = null;
  70514. _this._prevPrevPostProcess = null;
  70515. _this._cameras = cameras || [];
  70516. _this._originalCameras = _this._cameras.slice();
  70517. _this._buildAllowed = automaticBuild;
  70518. // Initialize
  70519. _this._scene = scene;
  70520. var caps = _this._scene.getEngine().getCaps();
  70521. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  70522. // Misc
  70523. if (_this._hdr) {
  70524. if (caps.textureHalfFloatRender) {
  70525. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  70526. }
  70527. else if (caps.textureFloatRender) {
  70528. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  70529. }
  70530. }
  70531. else {
  70532. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  70533. }
  70534. // Attach
  70535. scene.postProcessRenderPipelineManager.addPipeline(_this);
  70536. var engine = _this._scene.getEngine();
  70537. // Create post processes before hand so they can be modified before enabled.
  70538. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  70539. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  70540. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  70541. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  70542. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  70543. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  70544. _this._buildPipeline();
  70545. return _this;
  70546. }
  70547. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  70548. get: function () {
  70549. return this._sharpenEnabled;
  70550. },
  70551. /**
  70552. * Enable or disable the sharpen process from the pipeline
  70553. */
  70554. set: function (enabled) {
  70555. if (this._sharpenEnabled === enabled) {
  70556. return;
  70557. }
  70558. this._sharpenEnabled = enabled;
  70559. this._buildPipeline();
  70560. },
  70561. enumerable: true,
  70562. configurable: true
  70563. });
  70564. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  70565. get: function () {
  70566. return this._bloomWeight;
  70567. },
  70568. /**
  70569. * The strength of the bloom.
  70570. */
  70571. set: function (value) {
  70572. if (this._bloomWeight === value) {
  70573. return;
  70574. }
  70575. this._bloomWeight = value;
  70576. if (this._hdr && this.copyBack) {
  70577. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  70578. }
  70579. },
  70580. enumerable: true,
  70581. configurable: true
  70582. });
  70583. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  70584. get: function () {
  70585. return this._bloomScale;
  70586. },
  70587. /**
  70588. * The scale of the bloom, lower value will provide better performance.
  70589. */
  70590. set: function (value) {
  70591. if (this._bloomScale === value) {
  70592. return;
  70593. }
  70594. this._bloomScale = value;
  70595. this._buildPipeline();
  70596. },
  70597. enumerable: true,
  70598. configurable: true
  70599. });
  70600. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  70601. get: function () {
  70602. return this._bloomEnabled;
  70603. },
  70604. /**
  70605. * Enable or disable the bloom from the pipeline
  70606. */
  70607. set: function (enabled) {
  70608. if (this._bloomEnabled === enabled) {
  70609. return;
  70610. }
  70611. this._bloomEnabled = enabled;
  70612. this._buildPipeline();
  70613. },
  70614. enumerable: true,
  70615. configurable: true
  70616. });
  70617. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  70618. /**
  70619. * If the depth of field is enabled.
  70620. */
  70621. get: function () {
  70622. return this._depthOfFieldEnabled;
  70623. },
  70624. set: function (enabled) {
  70625. if (this._depthOfFieldEnabled === enabled) {
  70626. return;
  70627. }
  70628. this._depthOfFieldEnabled = enabled;
  70629. this._buildPipeline();
  70630. },
  70631. enumerable: true,
  70632. configurable: true
  70633. });
  70634. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  70635. /**
  70636. * Blur level of the depth of field effect. (Higher blur will effect performance)
  70637. */
  70638. get: function () {
  70639. return this._depthOfFieldBlurLevel;
  70640. },
  70641. set: function (value) {
  70642. if (this._depthOfFieldBlurLevel === value) {
  70643. return;
  70644. }
  70645. this._depthOfFieldBlurLevel = value;
  70646. // recreate dof and dispose old as this setting is not dynamic
  70647. var oldDof = this.depthOfField;
  70648. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType);
  70649. this.depthOfField.focalLength = oldDof.focalLength;
  70650. this.depthOfField.focusDistance = oldDof.focusDistance;
  70651. this.depthOfField.fStop = oldDof.fStop;
  70652. this.depthOfField.lensSize = oldDof.lensSize;
  70653. for (var i = 0; i < this._cameras.length; i++) {
  70654. oldDof.disposeEffects(this._cameras[i]);
  70655. }
  70656. this._buildPipeline();
  70657. },
  70658. enumerable: true,
  70659. configurable: true
  70660. });
  70661. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  70662. get: function () {
  70663. return this._fxaaEnabled;
  70664. },
  70665. /**
  70666. * If the anti aliasing is enabled.
  70667. */
  70668. set: function (enabled) {
  70669. if (this._fxaaEnabled === enabled) {
  70670. return;
  70671. }
  70672. this._fxaaEnabled = enabled;
  70673. this._buildPipeline();
  70674. },
  70675. enumerable: true,
  70676. configurable: true
  70677. });
  70678. Object.defineProperty(DefaultRenderingPipeline.prototype, "msaaEnabled", {
  70679. get: function () {
  70680. return this._msaaEnabled;
  70681. },
  70682. /**
  70683. * If the multisample anti-aliasing is enabled.
  70684. */
  70685. set: function (enabled) {
  70686. if (this._msaaEnabled === enabled) {
  70687. return;
  70688. }
  70689. this._msaaEnabled = enabled;
  70690. this._buildPipeline();
  70691. },
  70692. enumerable: true,
  70693. configurable: true
  70694. });
  70695. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  70696. get: function () {
  70697. return this._imageProcessingEnabled;
  70698. },
  70699. /**
  70700. * If image processing is enabled.
  70701. */
  70702. set: function (enabled) {
  70703. if (this._imageProcessingEnabled === enabled) {
  70704. return;
  70705. }
  70706. this._imageProcessingEnabled = enabled;
  70707. this._buildPipeline();
  70708. },
  70709. enumerable: true,
  70710. configurable: true
  70711. });
  70712. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  70713. get: function () {
  70714. return this._chromaticAberrationEnabled;
  70715. },
  70716. /**
  70717. * Enable or disable the chromaticAberration process from the pipeline
  70718. */
  70719. set: function (enabled) {
  70720. if (this._chromaticAberrationEnabled === enabled) {
  70721. return;
  70722. }
  70723. this._chromaticAberrationEnabled = enabled;
  70724. this._buildPipeline();
  70725. },
  70726. enumerable: true,
  70727. configurable: true
  70728. });
  70729. /**
  70730. * Force the compilation of the entire pipeline.
  70731. */
  70732. DefaultRenderingPipeline.prototype.prepare = function () {
  70733. var previousState = this._buildAllowed;
  70734. this._buildAllowed = true;
  70735. this._buildPipeline();
  70736. this._buildAllowed = previousState;
  70737. };
  70738. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  70739. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  70740. if (this._prevPostProcess && this._prevPostProcess.autoClear) {
  70741. postProcess.autoClear = false;
  70742. }
  70743. else {
  70744. postProcess.autoClear = true;
  70745. }
  70746. if (!skipTextureSharing) {
  70747. if (this._prevPrevPostProcess) {
  70748. postProcess.shareOutputWith(this._prevPrevPostProcess);
  70749. }
  70750. else {
  70751. postProcess.useOwnOutput();
  70752. }
  70753. if (this._prevPostProcess) {
  70754. this._prevPrevPostProcess = this._prevPostProcess;
  70755. }
  70756. this._prevPostProcess = postProcess;
  70757. }
  70758. };
  70759. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  70760. var _this = this;
  70761. if (!this._buildAllowed) {
  70762. return;
  70763. }
  70764. var engine = this._scene.getEngine();
  70765. this._disposePostProcesses();
  70766. if (this._cameras !== null) {
  70767. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  70768. // get back cameras to be used to reattach pipeline
  70769. this._cameras = this._originalCameras.slice();
  70770. }
  70771. this._reset();
  70772. this._prevPostProcess = null;
  70773. this._prevPrevPostProcess = null;
  70774. if (this.sharpenEnabled) {
  70775. if (!this.sharpen.isReady()) {
  70776. this.sharpen.updateEffect();
  70777. }
  70778. this.addEffect(this._sharpenEffect);
  70779. this._setAutoClearAndTextureSharing(this.sharpen);
  70780. }
  70781. if (this.depthOfFieldEnabled) {
  70782. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  70783. this.depthOfField.depthTexture = depthTexture;
  70784. if (!this.depthOfField._isReady()) {
  70785. this.depthOfField._updateEffects();
  70786. }
  70787. this.addEffect(this.depthOfField);
  70788. this._setAutoClearAndTextureSharing(this.depthOfField._depthOfFieldMerge);
  70789. }
  70790. if (this.bloomEnabled) {
  70791. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  70792. this._setAutoClearAndTextureSharing(this.pass, true);
  70793. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  70794. if (!this._hdr) {
  70795. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  70796. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  70797. this.highlights.autoClear = false;
  70798. this.highlights.alwaysForcePOT = true;
  70799. }
  70800. this.blurX = new BABYLON.BlurPostProcess("horizontal blur", new BABYLON.Vector2(1.0, 0), 10.0, this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  70801. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  70802. this.blurX.alwaysForcePOT = true;
  70803. this.blurX.autoClear = false;
  70804. this.blurX.onActivateObservable.add(function () {
  70805. var dw = _this.blurX.width / engine.getRenderWidth(true);
  70806. _this.blurX.kernel = _this.bloomKernel * dw;
  70807. });
  70808. this.blurY = new BABYLON.BlurPostProcess("vertical blur", new BABYLON.Vector2(0, 1.0), 10.0, this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  70809. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  70810. this.blurY.alwaysForcePOT = true;
  70811. this.blurY.autoClear = false;
  70812. this.blurY.onActivateObservable.add(function () {
  70813. var dh = _this.blurY.height / engine.getRenderHeight(true);
  70814. _this.blurY.kernel = _this.bloomKernel * dh;
  70815. });
  70816. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  70817. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  70818. this.copyBack.alwaysForcePOT = true;
  70819. if (this._hdr) {
  70820. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  70821. var w = this.bloomWeight;
  70822. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  70823. }
  70824. else {
  70825. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  70826. }
  70827. this.copyBack.autoClear = false;
  70828. }
  70829. if (this._imageProcessingEnabled) {
  70830. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  70831. if (this._hdr) {
  70832. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  70833. }
  70834. else {
  70835. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  70836. }
  70837. }
  70838. if (this._hdr && this.imageProcessing) {
  70839. this.finalMerge = this.imageProcessing;
  70840. }
  70841. else {
  70842. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  70843. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  70844. this._setAutoClearAndTextureSharing(this.finalMerge, true);
  70845. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  70846. }
  70847. if (this.bloomEnabled) {
  70848. if (this._hdr) {
  70849. this.copyBack.shareOutputWith(this.blurX);
  70850. if (this.imageProcessing) {
  70851. this.imageProcessing.shareOutputWith(this.pass);
  70852. this.imageProcessing.autoClear = false;
  70853. }
  70854. else {
  70855. this.finalMerge.shareOutputWith(this.pass);
  70856. }
  70857. }
  70858. else {
  70859. this.finalMerge.shareOutputWith(this.pass);
  70860. }
  70861. }
  70862. if (this.fxaaEnabled) {
  70863. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  70864. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  70865. this._setAutoClearAndTextureSharing(this.fxaa);
  70866. }
  70867. if (this.chromaticAberrationEnabled) {
  70868. if (!this.chromaticAberration.isReady()) {
  70869. this.chromaticAberration.updateEffect();
  70870. }
  70871. this.addEffect(this._chromaticAberrationEffect);
  70872. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  70873. }
  70874. if (this._cameras !== null) {
  70875. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  70876. }
  70877. if (this.msaaEnabled) {
  70878. if (!this._enableMSAAOnFirstPostProcess()) {
  70879. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  70880. }
  70881. }
  70882. };
  70883. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  70884. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  70885. for (var i = 0; i < this._cameras.length; i++) {
  70886. var camera = this._cameras[i];
  70887. if (this.pass) {
  70888. this.pass.dispose(camera);
  70889. }
  70890. if (this.highlights) {
  70891. this.highlights.dispose(camera);
  70892. }
  70893. if (this.blurX) {
  70894. this.blurX.dispose(camera);
  70895. }
  70896. if (this.blurY) {
  70897. this.blurY.dispose(camera);
  70898. }
  70899. if (this.copyBack) {
  70900. this.copyBack.dispose(camera);
  70901. }
  70902. if (this.imageProcessing) {
  70903. this.imageProcessing.dispose(camera);
  70904. }
  70905. if (this.fxaa) {
  70906. this.fxaa.dispose(camera);
  70907. }
  70908. if (this.finalMerge) {
  70909. this.finalMerge.dispose(camera);
  70910. }
  70911. // These are created in the constructor and should not be disposed on every pipeline change
  70912. if (disposeNonRecreated) {
  70913. if (this.sharpen) {
  70914. this.sharpen.dispose(camera);
  70915. }
  70916. if (this.depthOfField) {
  70917. this.depthOfField.disposeEffects(camera);
  70918. }
  70919. if (this.chromaticAberration) {
  70920. this.chromaticAberration.dispose(camera);
  70921. }
  70922. }
  70923. }
  70924. this.pass = null;
  70925. this.highlights = null;
  70926. this.blurX = null;
  70927. this.blurY = null;
  70928. this.copyBack = null;
  70929. this.imageProcessing = null;
  70930. this.fxaa = null;
  70931. this.finalMerge = null;
  70932. if (disposeNonRecreated) {
  70933. this.sharpen = null;
  70934. this.depthOfField = null;
  70935. this.chromaticAberration = null;
  70936. }
  70937. };
  70938. /**
  70939. * Dispose of the pipeline and stop all post processes
  70940. */
  70941. DefaultRenderingPipeline.prototype.dispose = function () {
  70942. this._disposePostProcesses(true);
  70943. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  70944. _super.prototype.dispose.call(this);
  70945. };
  70946. /**
  70947. * Serialize the rendering pipeline (Used when exporting)
  70948. * @returns the serialized object
  70949. */
  70950. DefaultRenderingPipeline.prototype.serialize = function () {
  70951. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  70952. serializationObject.customType = "DefaultRenderingPipeline";
  70953. return serializationObject;
  70954. };
  70955. /**
  70956. * Parse the serialized pipeline
  70957. * @param source Source pipeline.
  70958. * @param scene The scene to load the pipeline to.
  70959. * @param rootUrl The URL of the serialized pipeline.
  70960. * @returns An instantiated pipeline from the serialized object.
  70961. */
  70962. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  70963. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  70964. };
  70965. __decorate([
  70966. BABYLON.serialize()
  70967. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  70968. __decorate([
  70969. BABYLON.serialize()
  70970. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  70971. __decorate([
  70972. BABYLON.serialize()
  70973. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  70974. __decorate([
  70975. BABYLON.serialize()
  70976. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  70977. __decorate([
  70978. BABYLON.serialize()
  70979. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  70980. __decorate([
  70981. BABYLON.serialize()
  70982. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  70983. __decorate([
  70984. BABYLON.serialize()
  70985. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  70986. __decorate([
  70987. BABYLON.serialize()
  70988. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  70989. __decorate([
  70990. BABYLON.serialize()
  70991. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  70992. __decorate([
  70993. BABYLON.serialize()
  70994. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  70995. __decorate([
  70996. BABYLON.serialize()
  70997. ], DefaultRenderingPipeline.prototype, "msaaEnabled", null);
  70998. __decorate([
  70999. BABYLON.serialize()
  71000. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  71001. __decorate([
  71002. BABYLON.serialize()
  71003. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  71004. return DefaultRenderingPipeline;
  71005. }(BABYLON.PostProcessRenderPipeline));
  71006. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  71007. })(BABYLON || (BABYLON = {}));
  71008. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  71009. "use strict";
  71010. var BABYLON;
  71011. (function (BABYLON) {
  71012. /**
  71013. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  71014. */
  71015. var GeometryBufferRenderer = /** @class */ (function () {
  71016. /**
  71017. * Creates a new G Buffer for the scene. @see GeometryBufferRenderer
  71018. * @param scene The scene the buffer belongs to
  71019. * @param ratio How big is the buffer related to the main canvas.
  71020. */
  71021. function GeometryBufferRenderer(scene, ratio) {
  71022. if (ratio === void 0) { ratio = 1; }
  71023. this._enablePosition = false;
  71024. this._scene = scene;
  71025. this._ratio = ratio;
  71026. // Render target
  71027. this._createRenderTargets();
  71028. }
  71029. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  71030. /**
  71031. * Set the render list (meshes to be rendered) used in the G buffer.
  71032. */
  71033. set: function (meshes) {
  71034. this._multiRenderTarget.renderList = meshes;
  71035. },
  71036. enumerable: true,
  71037. configurable: true
  71038. });
  71039. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  71040. /**
  71041. * Gets wether or not G buffer are supported by the running hardware.
  71042. * This requires draw buffer supports
  71043. */
  71044. get: function () {
  71045. return this._multiRenderTarget.isSupported;
  71046. },
  71047. enumerable: true,
  71048. configurable: true
  71049. });
  71050. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  71051. /**
  71052. * Gets wether or not position are enabled for the G buffer.
  71053. */
  71054. get: function () {
  71055. return this._enablePosition;
  71056. },
  71057. /**
  71058. * Sets wether or not position are enabled for the G buffer.
  71059. */
  71060. set: function (enable) {
  71061. this._enablePosition = enable;
  71062. this.dispose();
  71063. this._createRenderTargets();
  71064. },
  71065. enumerable: true,
  71066. configurable: true
  71067. });
  71068. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  71069. /**
  71070. * Gets the scene associated with the buffer.
  71071. */
  71072. get: function () {
  71073. return this._scene;
  71074. },
  71075. enumerable: true,
  71076. configurable: true
  71077. });
  71078. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  71079. /**
  71080. * Gets the ratio used by the buffer during its creation.
  71081. * How big is the buffer related to the main canvas.
  71082. */
  71083. get: function () {
  71084. return this._ratio;
  71085. },
  71086. enumerable: true,
  71087. configurable: true
  71088. });
  71089. /**
  71090. * Checks wether everything is ready to render a submesh to the G buffer.
  71091. * @param subMesh the submesh to check readiness for
  71092. * @param useInstances is the mesh drawn using instance or not
  71093. * @returns true if ready otherwise false
  71094. */
  71095. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  71096. var material = subMesh.getMaterial();
  71097. if (material && material.disableDepthWrite) {
  71098. return false;
  71099. }
  71100. var defines = [];
  71101. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  71102. var mesh = subMesh.getMesh();
  71103. // Alpha test
  71104. if (material && material.needAlphaTesting()) {
  71105. defines.push("#define ALPHATEST");
  71106. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  71107. attribs.push(BABYLON.VertexBuffer.UVKind);
  71108. defines.push("#define UV1");
  71109. }
  71110. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  71111. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  71112. defines.push("#define UV2");
  71113. }
  71114. }
  71115. // Buffers
  71116. if (this._enablePosition) {
  71117. defines.push("#define POSITION");
  71118. }
  71119. // Bones
  71120. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  71121. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  71122. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  71123. if (mesh.numBoneInfluencers > 4) {
  71124. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  71125. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  71126. }
  71127. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  71128. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  71129. }
  71130. else {
  71131. defines.push("#define NUM_BONE_INFLUENCERS 0");
  71132. }
  71133. // Instances
  71134. if (useInstances) {
  71135. defines.push("#define INSTANCES");
  71136. attribs.push("world0");
  71137. attribs.push("world1");
  71138. attribs.push("world2");
  71139. attribs.push("world3");
  71140. }
  71141. // Get correct effect
  71142. var join = defines.join("\n");
  71143. if (this._cachedDefines !== join) {
  71144. this._cachedDefines = join;
  71145. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  71146. }
  71147. return this._effect.isReady();
  71148. };
  71149. /**
  71150. * Gets the current underlying G Buffer.
  71151. * @returns the buffer
  71152. */
  71153. GeometryBufferRenderer.prototype.getGBuffer = function () {
  71154. return this._multiRenderTarget;
  71155. };
  71156. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  71157. /**
  71158. * Gets the number of samples used to render the buffer (anti aliasing).
  71159. */
  71160. get: function () {
  71161. return this._multiRenderTarget.samples;
  71162. },
  71163. /**
  71164. * Sets the number of samples used to render the buffer (anti aliasing).
  71165. */
  71166. set: function (value) {
  71167. this._multiRenderTarget.samples = value;
  71168. },
  71169. enumerable: true,
  71170. configurable: true
  71171. });
  71172. /**
  71173. * Disposes the renderer and frees up associated resources.
  71174. */
  71175. GeometryBufferRenderer.prototype.dispose = function () {
  71176. this.getGBuffer().dispose();
  71177. };
  71178. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  71179. var _this = this;
  71180. var engine = this._scene.getEngine();
  71181. var count = this._enablePosition ? 3 : 2;
  71182. 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 });
  71183. if (!this.isSupported) {
  71184. return;
  71185. }
  71186. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71187. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71188. this._multiRenderTarget.refreshRate = 1;
  71189. this._multiRenderTarget.renderParticles = false;
  71190. this._multiRenderTarget.renderList = null;
  71191. // set default depth value to 1.0 (far away)
  71192. this._multiRenderTarget.onClearObservable.add(function (engine) {
  71193. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  71194. });
  71195. // Custom render function
  71196. var renderSubMesh = function (subMesh) {
  71197. var mesh = subMesh.getRenderingMesh();
  71198. var scene = _this._scene;
  71199. var engine = scene.getEngine();
  71200. var material = subMesh.getMaterial();
  71201. if (!material) {
  71202. return;
  71203. }
  71204. // Culling
  71205. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  71206. // Managing instances
  71207. var batch = mesh._getInstancesRenderList(subMesh._id);
  71208. if (batch.mustReturn) {
  71209. return;
  71210. }
  71211. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  71212. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  71213. engine.enableEffect(_this._effect);
  71214. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  71215. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  71216. _this._effect.setMatrix("view", scene.getViewMatrix());
  71217. // Alpha test
  71218. if (material && material.needAlphaTesting()) {
  71219. var alphaTexture = material.getAlphaTestTexture();
  71220. if (alphaTexture) {
  71221. _this._effect.setTexture("diffuseSampler", alphaTexture);
  71222. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  71223. }
  71224. }
  71225. // Bones
  71226. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  71227. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  71228. }
  71229. // Draw
  71230. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  71231. }
  71232. };
  71233. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  71234. var index;
  71235. if (depthOnlySubMeshes.length) {
  71236. engine.setColorWrite(false);
  71237. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  71238. renderSubMesh(depthOnlySubMeshes.data[index]);
  71239. }
  71240. engine.setColorWrite(true);
  71241. }
  71242. for (index = 0; index < opaqueSubMeshes.length; index++) {
  71243. renderSubMesh(opaqueSubMeshes.data[index]);
  71244. }
  71245. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  71246. renderSubMesh(alphaTestSubMeshes.data[index]);
  71247. }
  71248. };
  71249. };
  71250. return GeometryBufferRenderer;
  71251. }());
  71252. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  71253. })(BABYLON || (BABYLON = {}));
  71254. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  71255. "use strict";
  71256. var BABYLON;
  71257. (function (BABYLON) {
  71258. var RefractionPostProcess = /** @class */ (function (_super) {
  71259. __extends(RefractionPostProcess, _super);
  71260. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  71261. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  71262. _this.color = color;
  71263. _this.depth = depth;
  71264. _this.colorLevel = colorLevel;
  71265. _this._ownRefractionTexture = true;
  71266. _this.onActivateObservable.add(function (cam) {
  71267. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  71268. });
  71269. _this.onApplyObservable.add(function (effect) {
  71270. effect.setColor3("baseColor", _this.color);
  71271. effect.setFloat("depth", _this.depth);
  71272. effect.setFloat("colorLevel", _this.colorLevel);
  71273. effect.setTexture("refractionSampler", _this._refTexture);
  71274. });
  71275. return _this;
  71276. }
  71277. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  71278. /**
  71279. * Gets or sets the refraction texture
  71280. * Please note that you are responsible for disposing the texture if you set it manually
  71281. */
  71282. get: function () {
  71283. return this._refTexture;
  71284. },
  71285. set: function (value) {
  71286. if (this._refTexture && this._ownRefractionTexture) {
  71287. this._refTexture.dispose();
  71288. }
  71289. this._refTexture = value;
  71290. this._ownRefractionTexture = false;
  71291. },
  71292. enumerable: true,
  71293. configurable: true
  71294. });
  71295. // Methods
  71296. RefractionPostProcess.prototype.dispose = function (camera) {
  71297. if (this._refTexture && this._ownRefractionTexture) {
  71298. this._refTexture.dispose();
  71299. this._refTexture = null;
  71300. }
  71301. _super.prototype.dispose.call(this, camera);
  71302. };
  71303. return RefractionPostProcess;
  71304. }(BABYLON.PostProcess));
  71305. BABYLON.RefractionPostProcess = RefractionPostProcess;
  71306. })(BABYLON || (BABYLON = {}));
  71307. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  71308. "use strict";
  71309. var BABYLON;
  71310. (function (BABYLON) {
  71311. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  71312. __extends(BlackAndWhitePostProcess, _super);
  71313. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  71314. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  71315. _this.degree = 1;
  71316. _this.onApplyObservable.add(function (effect) {
  71317. effect.setFloat("degree", _this.degree);
  71318. });
  71319. return _this;
  71320. }
  71321. return BlackAndWhitePostProcess;
  71322. }(BABYLON.PostProcess));
  71323. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  71324. })(BABYLON || (BABYLON = {}));
  71325. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  71326. "use strict";
  71327. var BABYLON;
  71328. (function (BABYLON) {
  71329. /**
  71330. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  71331. * input texture to perform effects such as edge detection or sharpening
  71332. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  71333. */
  71334. var ConvolutionPostProcess = /** @class */ (function (_super) {
  71335. __extends(ConvolutionPostProcess, _super);
  71336. /**
  71337. * Creates a new instance of @see ConvolutionPostProcess
  71338. * @param name The name of the effect.
  71339. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  71340. * @param options The required width/height ratio to downsize to before computing the render pass.
  71341. * @param camera The camera to apply the render pass to.
  71342. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  71343. * @param engine The engine which the post process will be applied. (default: current engine)
  71344. * @param reusable If the post process can be reused on the same frame. (default: false)
  71345. * @param textureType Type of textures used when performing the post process. (default: 0)
  71346. */
  71347. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  71348. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71349. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  71350. _this.kernel = kernel;
  71351. _this.onApply = function (effect) {
  71352. effect.setFloat2("screenSize", _this.width, _this.height);
  71353. effect.setArray("kernel", _this.kernel);
  71354. };
  71355. return _this;
  71356. }
  71357. // Statics
  71358. /**
  71359. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  71360. */
  71361. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  71362. /**
  71363. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  71364. */
  71365. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  71366. /**
  71367. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  71368. */
  71369. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  71370. /**
  71371. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  71372. */
  71373. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  71374. /**
  71375. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  71376. */
  71377. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  71378. /**
  71379. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  71380. */
  71381. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  71382. return ConvolutionPostProcess;
  71383. }(BABYLON.PostProcess));
  71384. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  71385. })(BABYLON || (BABYLON = {}));
  71386. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  71387. "use strict";
  71388. var BABYLON;
  71389. (function (BABYLON) {
  71390. var FilterPostProcess = /** @class */ (function (_super) {
  71391. __extends(FilterPostProcess, _super);
  71392. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  71393. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  71394. _this.kernelMatrix = kernelMatrix;
  71395. _this.onApply = function (effect) {
  71396. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  71397. };
  71398. return _this;
  71399. }
  71400. return FilterPostProcess;
  71401. }(BABYLON.PostProcess));
  71402. BABYLON.FilterPostProcess = FilterPostProcess;
  71403. })(BABYLON || (BABYLON = {}));
  71404. //# sourceMappingURL=babylon.filterPostProcess.js.map
  71405. "use strict";
  71406. var BABYLON;
  71407. (function (BABYLON) {
  71408. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  71409. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  71410. __extends(VolumetricLightScatteringPostProcess, _super);
  71411. /**
  71412. * @constructor
  71413. * @param {string} name - The post-process name
  71414. * @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)
  71415. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  71416. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  71417. * @param {number} samples - The post-process quality, default 100
  71418. * @param {number} samplingMode - The post-process filtering mode
  71419. * @param {BABYLON.Engine} engine - The babylon engine
  71420. * @param {boolean} reusable - If the post-process is reusable
  71421. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  71422. */
  71423. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  71424. if (samples === void 0) { samples = 100; }
  71425. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  71426. 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;
  71427. _this._screenCoordinates = BABYLON.Vector2.Zero();
  71428. /**
  71429. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  71430. * @type {Vector3}
  71431. */
  71432. _this.customMeshPosition = BABYLON.Vector3.Zero();
  71433. /**
  71434. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  71435. * @type {boolean}
  71436. */
  71437. _this.useCustomMeshPosition = false;
  71438. /**
  71439. * If the post-process should inverse the light scattering direction
  71440. * @type {boolean}
  71441. */
  71442. _this.invert = true;
  71443. /**
  71444. * Array containing the excluded meshes not rendered in the internal pass
  71445. */
  71446. _this.excludedMeshes = new Array();
  71447. /**
  71448. * Controls the overall intensity of the post-process
  71449. * @type {number}
  71450. */
  71451. _this.exposure = 0.3;
  71452. /**
  71453. * Dissipates each sample's contribution in range [0, 1]
  71454. * @type {number}
  71455. */
  71456. _this.decay = 0.96815;
  71457. /**
  71458. * Controls the overall intensity of each sample
  71459. * @type {number}
  71460. */
  71461. _this.weight = 0.58767;
  71462. /**
  71463. * Controls the density of each sample
  71464. * @type {number}
  71465. */
  71466. _this.density = 0.926;
  71467. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  71468. engine = scene.getEngine();
  71469. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  71470. // Configure mesh
  71471. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  71472. // Configure
  71473. _this._createPass(scene, ratio.passRatio || ratio);
  71474. _this.onActivate = function (camera) {
  71475. if (!_this.isSupported) {
  71476. _this.dispose(camera);
  71477. }
  71478. _this.onActivate = null;
  71479. };
  71480. _this.onApplyObservable.add(function (effect) {
  71481. _this._updateMeshScreenCoordinates(scene);
  71482. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  71483. effect.setFloat("exposure", _this.exposure);
  71484. effect.setFloat("decay", _this.decay);
  71485. effect.setFloat("weight", _this.weight);
  71486. effect.setFloat("density", _this.density);
  71487. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  71488. });
  71489. return _this;
  71490. }
  71491. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  71492. get: function () {
  71493. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  71494. return false;
  71495. },
  71496. set: function (useDiffuseColor) {
  71497. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  71498. },
  71499. enumerable: true,
  71500. configurable: true
  71501. });
  71502. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  71503. return "VolumetricLightScatteringPostProcess";
  71504. };
  71505. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  71506. var mesh = subMesh.getMesh();
  71507. // Render this.mesh as default
  71508. if (mesh === this.mesh && mesh.material) {
  71509. return mesh.material.isReady(mesh);
  71510. }
  71511. var defines = [];
  71512. var attribs = [BABYLON.VertexBuffer.PositionKind];
  71513. var material = subMesh.getMaterial();
  71514. // Alpha test
  71515. if (material) {
  71516. if (material.needAlphaTesting()) {
  71517. defines.push("#define ALPHATEST");
  71518. }
  71519. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  71520. attribs.push(BABYLON.VertexBuffer.UVKind);
  71521. defines.push("#define UV1");
  71522. }
  71523. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  71524. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  71525. defines.push("#define UV2");
  71526. }
  71527. }
  71528. // Bones
  71529. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  71530. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  71531. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  71532. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  71533. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  71534. }
  71535. else {
  71536. defines.push("#define NUM_BONE_INFLUENCERS 0");
  71537. }
  71538. // Instances
  71539. if (useInstances) {
  71540. defines.push("#define INSTANCES");
  71541. attribs.push("world0");
  71542. attribs.push("world1");
  71543. attribs.push("world2");
  71544. attribs.push("world3");
  71545. }
  71546. // Get correct effect
  71547. var join = defines.join("\n");
  71548. if (this._cachedDefines !== join) {
  71549. this._cachedDefines = join;
  71550. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  71551. }
  71552. return this._volumetricLightScatteringPass.isReady();
  71553. };
  71554. /**
  71555. * Sets the new light position for light scattering effect
  71556. * @param {BABYLON.Vector3} The new custom light position
  71557. */
  71558. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  71559. this.customMeshPosition = position;
  71560. };
  71561. /**
  71562. * Returns the light position for light scattering effect
  71563. * @return {BABYLON.Vector3} The custom light position
  71564. */
  71565. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  71566. return this.customMeshPosition;
  71567. };
  71568. /**
  71569. * Disposes the internal assets and detaches the post-process from the camera
  71570. */
  71571. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  71572. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  71573. if (rttIndex !== -1) {
  71574. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  71575. }
  71576. this._volumetricLightScatteringRTT.dispose();
  71577. _super.prototype.dispose.call(this, camera);
  71578. };
  71579. /**
  71580. * Returns the render target texture used by the post-process
  71581. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  71582. */
  71583. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  71584. return this._volumetricLightScatteringRTT;
  71585. };
  71586. // Private methods
  71587. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  71588. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  71589. return true;
  71590. }
  71591. return false;
  71592. };
  71593. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  71594. var _this = this;
  71595. var engine = scene.getEngine();
  71596. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  71597. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71598. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71599. this._volumetricLightScatteringRTT.renderList = null;
  71600. this._volumetricLightScatteringRTT.renderParticles = false;
  71601. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  71602. var camera = this.getCamera();
  71603. if (camera) {
  71604. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  71605. }
  71606. else {
  71607. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  71608. }
  71609. // Custom render function for submeshes
  71610. var renderSubMesh = function (subMesh) {
  71611. var mesh = subMesh.getRenderingMesh();
  71612. if (_this._meshExcluded(mesh)) {
  71613. return;
  71614. }
  71615. var material = subMesh.getMaterial();
  71616. if (!material) {
  71617. return;
  71618. }
  71619. var scene = mesh.getScene();
  71620. var engine = scene.getEngine();
  71621. // Culling
  71622. engine.setState(material.backFaceCulling);
  71623. // Managing instances
  71624. var batch = mesh._getInstancesRenderList(subMesh._id);
  71625. if (batch.mustReturn) {
  71626. return;
  71627. }
  71628. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  71629. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  71630. var effect = _this._volumetricLightScatteringPass;
  71631. if (mesh === _this.mesh) {
  71632. if (subMesh.effect) {
  71633. effect = subMesh.effect;
  71634. }
  71635. else {
  71636. effect = material.getEffect();
  71637. }
  71638. }
  71639. engine.enableEffect(effect);
  71640. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  71641. if (mesh === _this.mesh) {
  71642. material.bind(mesh.getWorldMatrix(), mesh);
  71643. }
  71644. else {
  71645. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  71646. // Alpha test
  71647. if (material && material.needAlphaTesting()) {
  71648. var alphaTexture = material.getAlphaTestTexture();
  71649. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  71650. if (alphaTexture) {
  71651. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  71652. }
  71653. }
  71654. // Bones
  71655. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  71656. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  71657. }
  71658. }
  71659. // Draw
  71660. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  71661. }
  71662. };
  71663. // Render target texture callbacks
  71664. var savedSceneClearColor;
  71665. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  71666. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  71667. savedSceneClearColor = scene.clearColor;
  71668. scene.clearColor = sceneClearColor;
  71669. });
  71670. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  71671. scene.clearColor = savedSceneClearColor;
  71672. });
  71673. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  71674. var engine = scene.getEngine();
  71675. var index;
  71676. if (depthOnlySubMeshes.length) {
  71677. engine.setColorWrite(false);
  71678. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  71679. renderSubMesh(depthOnlySubMeshes.data[index]);
  71680. }
  71681. engine.setColorWrite(true);
  71682. }
  71683. for (index = 0; index < opaqueSubMeshes.length; index++) {
  71684. renderSubMesh(opaqueSubMeshes.data[index]);
  71685. }
  71686. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  71687. renderSubMesh(alphaTestSubMeshes.data[index]);
  71688. }
  71689. if (transparentSubMeshes.length) {
  71690. // Sort sub meshes
  71691. for (index = 0; index < transparentSubMeshes.length; index++) {
  71692. var submesh = transparentSubMeshes.data[index];
  71693. var boundingInfo = submesh.getBoundingInfo();
  71694. if (boundingInfo && scene.activeCamera) {
  71695. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  71696. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  71697. }
  71698. }
  71699. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  71700. sortedArray.sort(function (a, b) {
  71701. // Alpha index first
  71702. if (a._alphaIndex > b._alphaIndex) {
  71703. return 1;
  71704. }
  71705. if (a._alphaIndex < b._alphaIndex) {
  71706. return -1;
  71707. }
  71708. // Then distance to camera
  71709. if (a._distanceToCamera < b._distanceToCamera) {
  71710. return 1;
  71711. }
  71712. if (a._distanceToCamera > b._distanceToCamera) {
  71713. return -1;
  71714. }
  71715. return 0;
  71716. });
  71717. // Render sub meshes
  71718. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  71719. for (index = 0; index < sortedArray.length; index++) {
  71720. renderSubMesh(sortedArray[index]);
  71721. }
  71722. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  71723. }
  71724. };
  71725. };
  71726. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  71727. var transform = scene.getTransformMatrix();
  71728. var meshPosition;
  71729. if (this.useCustomMeshPosition) {
  71730. meshPosition = this.customMeshPosition;
  71731. }
  71732. else if (this.attachedNode) {
  71733. meshPosition = this.attachedNode.position;
  71734. }
  71735. else {
  71736. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  71737. }
  71738. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  71739. this._screenCoordinates.x = pos.x / this._viewPort.width;
  71740. this._screenCoordinates.y = pos.y / this._viewPort.height;
  71741. if (this.invert)
  71742. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  71743. };
  71744. // Static methods
  71745. /**
  71746. * Creates a default mesh for the Volumeric Light Scattering post-process
  71747. * @param {string} The mesh name
  71748. * @param {BABYLON.Scene} The scene where to create the mesh
  71749. * @return {BABYLON.Mesh} the default mesh
  71750. */
  71751. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  71752. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  71753. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  71754. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  71755. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  71756. mesh.material = material;
  71757. return mesh;
  71758. };
  71759. __decorate([
  71760. BABYLON.serializeAsVector3()
  71761. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  71762. __decorate([
  71763. BABYLON.serialize()
  71764. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  71765. __decorate([
  71766. BABYLON.serialize()
  71767. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  71768. __decorate([
  71769. BABYLON.serializeAsMeshReference()
  71770. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  71771. __decorate([
  71772. BABYLON.serialize()
  71773. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  71774. __decorate([
  71775. BABYLON.serialize()
  71776. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  71777. __decorate([
  71778. BABYLON.serialize()
  71779. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  71780. __decorate([
  71781. BABYLON.serialize()
  71782. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  71783. __decorate([
  71784. BABYLON.serialize()
  71785. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  71786. return VolumetricLightScatteringPostProcess;
  71787. }(BABYLON.PostProcess));
  71788. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  71789. })(BABYLON || (BABYLON = {}));
  71790. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  71791. "use strict";
  71792. //
  71793. // This post-process allows the modification of rendered colors by using
  71794. // a 'look-up table' (LUT). This effect is also called Color Grading.
  71795. //
  71796. // The object needs to be provided an url to a texture containing the color
  71797. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  71798. // Use an image editing software to tweak the LUT to match your needs.
  71799. //
  71800. // For an example of a color LUT, see here:
  71801. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  71802. // For explanations on color grading, see here:
  71803. // http://udn.epicgames.com/Three/ColorGrading.html
  71804. //
  71805. var BABYLON;
  71806. (function (BABYLON) {
  71807. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  71808. __extends(ColorCorrectionPostProcess, _super);
  71809. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  71810. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  71811. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  71812. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  71813. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71814. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71815. _this.onApply = function (effect) {
  71816. effect.setTexture("colorTable", _this._colorTableTexture);
  71817. };
  71818. return _this;
  71819. }
  71820. return ColorCorrectionPostProcess;
  71821. }(BABYLON.PostProcess));
  71822. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  71823. })(BABYLON || (BABYLON = {}));
  71824. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  71825. "use strict";
  71826. var BABYLON;
  71827. (function (BABYLON) {
  71828. var TonemappingOperator;
  71829. (function (TonemappingOperator) {
  71830. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  71831. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  71832. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  71833. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  71834. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  71835. ;
  71836. var TonemapPostProcess = /** @class */ (function (_super) {
  71837. __extends(TonemapPostProcess, _super);
  71838. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  71839. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  71840. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71841. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  71842. _this._operator = _operator;
  71843. _this.exposureAdjustment = exposureAdjustment;
  71844. var defines = "#define ";
  71845. if (_this._operator === TonemappingOperator.Hable)
  71846. defines += "HABLE_TONEMAPPING";
  71847. else if (_this._operator === TonemappingOperator.Reinhard)
  71848. defines += "REINHARD_TONEMAPPING";
  71849. else if (_this._operator === TonemappingOperator.HejiDawson)
  71850. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  71851. else if (_this._operator === TonemappingOperator.Photographic)
  71852. defines += "PHOTOGRAPHIC_TONEMAPPING";
  71853. //sadly a second call to create the effect.
  71854. _this.updateEffect(defines);
  71855. _this.onApply = function (effect) {
  71856. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  71857. };
  71858. return _this;
  71859. }
  71860. return TonemapPostProcess;
  71861. }(BABYLON.PostProcess));
  71862. BABYLON.TonemapPostProcess = TonemapPostProcess;
  71863. })(BABYLON || (BABYLON = {}));
  71864. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  71865. "use strict";
  71866. var BABYLON;
  71867. (function (BABYLON) {
  71868. var DisplayPassPostProcess = /** @class */ (function (_super) {
  71869. __extends(DisplayPassPostProcess, _super);
  71870. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  71871. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  71872. }
  71873. return DisplayPassPostProcess;
  71874. }(BABYLON.PostProcess));
  71875. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  71876. })(BABYLON || (BABYLON = {}));
  71877. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  71878. "use strict";
  71879. var BABYLON;
  71880. (function (BABYLON) {
  71881. var HighlightsPostProcess = /** @class */ (function (_super) {
  71882. __extends(HighlightsPostProcess, _super);
  71883. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  71884. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71885. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  71886. }
  71887. return HighlightsPostProcess;
  71888. }(BABYLON.PostProcess));
  71889. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  71890. })(BABYLON || (BABYLON = {}));
  71891. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  71892. "use strict";
  71893. var BABYLON;
  71894. (function (BABYLON) {
  71895. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  71896. __extends(ImageProcessingPostProcess, _super);
  71897. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  71898. if (camera === void 0) { camera = null; }
  71899. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71900. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  71901. _this._fromLinearSpace = true;
  71902. /**
  71903. * Defines cache preventing GC.
  71904. */
  71905. _this._defines = {
  71906. IMAGEPROCESSING: false,
  71907. VIGNETTE: false,
  71908. VIGNETTEBLENDMODEMULTIPLY: false,
  71909. VIGNETTEBLENDMODEOPAQUE: false,
  71910. TONEMAPPING: false,
  71911. CONTRAST: false,
  71912. COLORCURVES: false,
  71913. COLORGRADING: false,
  71914. COLORGRADING3D: false,
  71915. FROMLINEARSPACE: false,
  71916. SAMPLER3DGREENDEPTH: false,
  71917. SAMPLER3DBGRMAP: false,
  71918. IMAGEPROCESSINGPOSTPROCESS: false,
  71919. EXPOSURE: false,
  71920. GRAIN: false,
  71921. };
  71922. // Setup the configuration as forced by the constructor. This would then not force the
  71923. // scene materials output in linear space and let untouched the default forward pass.
  71924. if (imageProcessingConfiguration) {
  71925. imageProcessingConfiguration.applyByPostProcess = true;
  71926. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  71927. // This will cause the shader to be compiled
  71928. _this.fromLinearSpace = false;
  71929. }
  71930. else {
  71931. _this._attachImageProcessingConfiguration(null, true);
  71932. _this.imageProcessingConfiguration.applyByPostProcess = true;
  71933. }
  71934. _this.onApply = function (effect) {
  71935. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  71936. };
  71937. return _this;
  71938. }
  71939. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  71940. /**
  71941. * Gets the image processing configuration used either in this material.
  71942. */
  71943. get: function () {
  71944. return this._imageProcessingConfiguration;
  71945. },
  71946. /**
  71947. * Sets the Default image processing configuration used either in the this material.
  71948. *
  71949. * If sets to null, the scene one is in use.
  71950. */
  71951. set: function (value) {
  71952. this._attachImageProcessingConfiguration(value);
  71953. },
  71954. enumerable: true,
  71955. configurable: true
  71956. });
  71957. /**
  71958. * Attaches a new image processing configuration to the PBR Material.
  71959. * @param configuration
  71960. */
  71961. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  71962. var _this = this;
  71963. if (doNotBuild === void 0) { doNotBuild = false; }
  71964. if (configuration === this._imageProcessingConfiguration) {
  71965. return;
  71966. }
  71967. // Detaches observer.
  71968. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  71969. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  71970. }
  71971. // Pick the scene configuration if needed.
  71972. if (!configuration) {
  71973. var scene = null;
  71974. var engine = this.getEngine();
  71975. var camera = this.getCamera();
  71976. if (camera) {
  71977. scene = camera.getScene();
  71978. }
  71979. else if (engine && engine.scenes) {
  71980. var scenes = engine.scenes;
  71981. scene = scenes[scenes.length - 1];
  71982. }
  71983. else {
  71984. scene = BABYLON.Engine.LastCreatedScene;
  71985. }
  71986. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  71987. }
  71988. else {
  71989. this._imageProcessingConfiguration = configuration;
  71990. }
  71991. // Attaches observer.
  71992. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  71993. _this._updateParameters();
  71994. });
  71995. // Ensure the effect will be rebuilt.
  71996. if (!doNotBuild) {
  71997. this._updateParameters();
  71998. }
  71999. };
  72000. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  72001. /**
  72002. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  72003. */
  72004. get: function () {
  72005. return this.imageProcessingConfiguration.colorCurves;
  72006. },
  72007. /**
  72008. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  72009. */
  72010. set: function (value) {
  72011. this.imageProcessingConfiguration.colorCurves = value;
  72012. },
  72013. enumerable: true,
  72014. configurable: true
  72015. });
  72016. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  72017. /**
  72018. * Gets wether the color curves effect is enabled.
  72019. */
  72020. get: function () {
  72021. return this.imageProcessingConfiguration.colorCurvesEnabled;
  72022. },
  72023. /**
  72024. * Sets wether the color curves effect is enabled.
  72025. */
  72026. set: function (value) {
  72027. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  72028. },
  72029. enumerable: true,
  72030. configurable: true
  72031. });
  72032. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  72033. /**
  72034. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  72035. */
  72036. get: function () {
  72037. return this.imageProcessingConfiguration.colorGradingTexture;
  72038. },
  72039. /**
  72040. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  72041. */
  72042. set: function (value) {
  72043. this.imageProcessingConfiguration.colorGradingTexture = value;
  72044. },
  72045. enumerable: true,
  72046. configurable: true
  72047. });
  72048. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  72049. /**
  72050. * Gets wether the color grading effect is enabled.
  72051. */
  72052. get: function () {
  72053. return this.imageProcessingConfiguration.colorGradingEnabled;
  72054. },
  72055. /**
  72056. * Gets wether the color grading effect is enabled.
  72057. */
  72058. set: function (value) {
  72059. this.imageProcessingConfiguration.colorGradingEnabled = value;
  72060. },
  72061. enumerable: true,
  72062. configurable: true
  72063. });
  72064. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  72065. /**
  72066. * Gets exposure used in the effect.
  72067. */
  72068. get: function () {
  72069. return this.imageProcessingConfiguration.exposure;
  72070. },
  72071. /**
  72072. * Sets exposure used in the effect.
  72073. */
  72074. set: function (value) {
  72075. this.imageProcessingConfiguration.exposure = value;
  72076. },
  72077. enumerable: true,
  72078. configurable: true
  72079. });
  72080. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  72081. /**
  72082. * Gets wether tonemapping is enabled or not.
  72083. */
  72084. get: function () {
  72085. return this._imageProcessingConfiguration.toneMappingEnabled;
  72086. },
  72087. /**
  72088. * Sets wether tonemapping is enabled or not
  72089. */
  72090. set: function (value) {
  72091. this._imageProcessingConfiguration.toneMappingEnabled = value;
  72092. },
  72093. enumerable: true,
  72094. configurable: true
  72095. });
  72096. ;
  72097. ;
  72098. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  72099. /**
  72100. * Gets contrast used in the effect.
  72101. */
  72102. get: function () {
  72103. return this.imageProcessingConfiguration.contrast;
  72104. },
  72105. /**
  72106. * Sets contrast used in the effect.
  72107. */
  72108. set: function (value) {
  72109. this.imageProcessingConfiguration.contrast = value;
  72110. },
  72111. enumerable: true,
  72112. configurable: true
  72113. });
  72114. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  72115. /**
  72116. * Gets Vignette stretch size.
  72117. */
  72118. get: function () {
  72119. return this.imageProcessingConfiguration.vignetteStretch;
  72120. },
  72121. /**
  72122. * Sets Vignette stretch size.
  72123. */
  72124. set: function (value) {
  72125. this.imageProcessingConfiguration.vignetteStretch = value;
  72126. },
  72127. enumerable: true,
  72128. configurable: true
  72129. });
  72130. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  72131. /**
  72132. * Gets Vignette centre X Offset.
  72133. */
  72134. get: function () {
  72135. return this.imageProcessingConfiguration.vignetteCentreX;
  72136. },
  72137. /**
  72138. * Sets Vignette centre X Offset.
  72139. */
  72140. set: function (value) {
  72141. this.imageProcessingConfiguration.vignetteCentreX = value;
  72142. },
  72143. enumerable: true,
  72144. configurable: true
  72145. });
  72146. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  72147. /**
  72148. * Gets Vignette centre Y Offset.
  72149. */
  72150. get: function () {
  72151. return this.imageProcessingConfiguration.vignetteCentreY;
  72152. },
  72153. /**
  72154. * Sets Vignette centre Y Offset.
  72155. */
  72156. set: function (value) {
  72157. this.imageProcessingConfiguration.vignetteCentreY = value;
  72158. },
  72159. enumerable: true,
  72160. configurable: true
  72161. });
  72162. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  72163. /**
  72164. * Gets Vignette weight or intensity of the vignette effect.
  72165. */
  72166. get: function () {
  72167. return this.imageProcessingConfiguration.vignetteWeight;
  72168. },
  72169. /**
  72170. * Sets Vignette weight or intensity of the vignette effect.
  72171. */
  72172. set: function (value) {
  72173. this.imageProcessingConfiguration.vignetteWeight = value;
  72174. },
  72175. enumerable: true,
  72176. configurable: true
  72177. });
  72178. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  72179. /**
  72180. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  72181. * if vignetteEnabled is set to true.
  72182. */
  72183. get: function () {
  72184. return this.imageProcessingConfiguration.vignetteColor;
  72185. },
  72186. /**
  72187. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  72188. * if vignetteEnabled is set to true.
  72189. */
  72190. set: function (value) {
  72191. this.imageProcessingConfiguration.vignetteColor = value;
  72192. },
  72193. enumerable: true,
  72194. configurable: true
  72195. });
  72196. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  72197. /**
  72198. * Gets Camera field of view used by the Vignette effect.
  72199. */
  72200. get: function () {
  72201. return this.imageProcessingConfiguration.vignetteCameraFov;
  72202. },
  72203. /**
  72204. * Sets Camera field of view used by the Vignette effect.
  72205. */
  72206. set: function (value) {
  72207. this.imageProcessingConfiguration.vignetteCameraFov = value;
  72208. },
  72209. enumerable: true,
  72210. configurable: true
  72211. });
  72212. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  72213. /**
  72214. * Gets the vignette blend mode allowing different kind of effect.
  72215. */
  72216. get: function () {
  72217. return this.imageProcessingConfiguration.vignetteBlendMode;
  72218. },
  72219. /**
  72220. * Sets the vignette blend mode allowing different kind of effect.
  72221. */
  72222. set: function (value) {
  72223. this.imageProcessingConfiguration.vignetteBlendMode = value;
  72224. },
  72225. enumerable: true,
  72226. configurable: true
  72227. });
  72228. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  72229. /**
  72230. * Gets wether the vignette effect is enabled.
  72231. */
  72232. get: function () {
  72233. return this.imageProcessingConfiguration.vignetteEnabled;
  72234. },
  72235. /**
  72236. * Sets wether the vignette effect is enabled.
  72237. */
  72238. set: function (value) {
  72239. this.imageProcessingConfiguration.vignetteEnabled = value;
  72240. },
  72241. enumerable: true,
  72242. configurable: true
  72243. });
  72244. Object.defineProperty(ImageProcessingPostProcess.prototype, "grainEnabled", {
  72245. /**
  72246. * Gets wether the grain effect is enabled.
  72247. */
  72248. get: function () {
  72249. return this.imageProcessingConfiguration.grainEnabled;
  72250. },
  72251. /**
  72252. * Sets wether the grain effect is enabled.
  72253. */
  72254. set: function (value) {
  72255. this.imageProcessingConfiguration.grainEnabled = value;
  72256. },
  72257. enumerable: true,
  72258. configurable: true
  72259. });
  72260. Object.defineProperty(ImageProcessingPostProcess.prototype, "grainIntensity", {
  72261. /**
  72262. * Gets the grain effect's intensity.
  72263. */
  72264. get: function () {
  72265. return this.imageProcessingConfiguration.grainIntensity;
  72266. },
  72267. /**
  72268. * Sets the grain effect's intensity.
  72269. */
  72270. set: function (value) {
  72271. this.imageProcessingConfiguration.grainIntensity = value;
  72272. },
  72273. enumerable: true,
  72274. configurable: true
  72275. });
  72276. Object.defineProperty(ImageProcessingPostProcess.prototype, "grainAnimated", {
  72277. /**
  72278. * Gets wether the grain effect is animated.
  72279. */
  72280. get: function () {
  72281. return this.imageProcessingConfiguration.grainAnimated;
  72282. },
  72283. /**
  72284. * Sets wether the grain effect is animated.
  72285. */
  72286. set: function (value) {
  72287. this.imageProcessingConfiguration.grainAnimated = value;
  72288. },
  72289. enumerable: true,
  72290. configurable: true
  72291. });
  72292. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  72293. /**
  72294. * Gets wether the input of the processing is in Gamma or Linear Space.
  72295. */
  72296. get: function () {
  72297. return this._fromLinearSpace;
  72298. },
  72299. /**
  72300. * Sets wether the input of the processing is in Gamma or Linear Space.
  72301. */
  72302. set: function (value) {
  72303. if (this._fromLinearSpace === value) {
  72304. return;
  72305. }
  72306. this._fromLinearSpace = value;
  72307. this._updateParameters();
  72308. },
  72309. enumerable: true,
  72310. configurable: true
  72311. });
  72312. ImageProcessingPostProcess.prototype.getClassName = function () {
  72313. return "ImageProcessingPostProcess";
  72314. };
  72315. ImageProcessingPostProcess.prototype._updateParameters = function () {
  72316. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  72317. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  72318. var defines = "";
  72319. for (var define in this._defines) {
  72320. if (this._defines[define]) {
  72321. defines += "#define " + define + ";\r\n";
  72322. }
  72323. }
  72324. var samplers = ["textureSampler"];
  72325. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  72326. var uniforms = ["scale"];
  72327. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  72328. this.updateEffect(defines, uniforms, samplers);
  72329. };
  72330. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  72331. _super.prototype.dispose.call(this, camera);
  72332. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  72333. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  72334. }
  72335. this.imageProcessingConfiguration.applyByPostProcess = false;
  72336. };
  72337. __decorate([
  72338. BABYLON.serialize()
  72339. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  72340. return ImageProcessingPostProcess;
  72341. }(BABYLON.PostProcess));
  72342. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  72343. })(BABYLON || (BABYLON = {}));
  72344. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  72345. "use strict";
  72346. var BABYLON;
  72347. (function (BABYLON) {
  72348. var Bone = /** @class */ (function (_super) {
  72349. __extends(Bone, _super);
  72350. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  72351. if (parentBone === void 0) { parentBone = null; }
  72352. if (localMatrix === void 0) { localMatrix = null; }
  72353. if (restPose === void 0) { restPose = null; }
  72354. if (baseMatrix === void 0) { baseMatrix = null; }
  72355. if (index === void 0) { index = null; }
  72356. var _this = _super.call(this, name, skeleton.getScene()) || this;
  72357. _this.name = name;
  72358. _this.children = new Array();
  72359. _this.animations = new Array();
  72360. // Set this value to map this bone to a different index in the transform matrices.
  72361. // Set this value to -1 to exclude the bone from the transform matrices.
  72362. _this._index = null;
  72363. _this._worldTransform = new BABYLON.Matrix();
  72364. _this._absoluteTransform = new BABYLON.Matrix();
  72365. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  72366. _this._scaleMatrix = BABYLON.Matrix.Identity();
  72367. _this._scaleVector = BABYLON.Vector3.One();
  72368. _this._negateScaleChildren = BABYLON.Vector3.One();
  72369. _this._scalingDeterminant = 1;
  72370. _this._skeleton = skeleton;
  72371. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  72372. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  72373. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  72374. _this._index = index;
  72375. skeleton.bones.push(_this);
  72376. _this.setParent(parentBone, false);
  72377. _this._updateDifferenceMatrix();
  72378. return _this;
  72379. }
  72380. Object.defineProperty(Bone.prototype, "_matrix", {
  72381. get: function () {
  72382. return this._localMatrix;
  72383. },
  72384. set: function (val) {
  72385. if (this._localMatrix) {
  72386. this._localMatrix.copyFrom(val);
  72387. }
  72388. else {
  72389. this._localMatrix = val;
  72390. }
  72391. },
  72392. enumerable: true,
  72393. configurable: true
  72394. });
  72395. // Members
  72396. Bone.prototype.getSkeleton = function () {
  72397. return this._skeleton;
  72398. };
  72399. Bone.prototype.getParent = function () {
  72400. return this._parent;
  72401. };
  72402. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  72403. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  72404. if (this._parent === parent) {
  72405. return;
  72406. }
  72407. if (this._parent) {
  72408. var index = this._parent.children.indexOf(this);
  72409. if (index !== -1) {
  72410. this._parent.children.splice(index, 1);
  72411. }
  72412. }
  72413. this._parent = parent;
  72414. if (this._parent) {
  72415. this._parent.children.push(this);
  72416. }
  72417. if (updateDifferenceMatrix) {
  72418. this._updateDifferenceMatrix();
  72419. }
  72420. };
  72421. Bone.prototype.getLocalMatrix = function () {
  72422. return this._localMatrix;
  72423. };
  72424. Bone.prototype.getBaseMatrix = function () {
  72425. return this._baseMatrix;
  72426. };
  72427. Bone.prototype.getRestPose = function () {
  72428. return this._restPose;
  72429. };
  72430. Bone.prototype.returnToRest = function () {
  72431. this.updateMatrix(this._restPose.clone());
  72432. };
  72433. Bone.prototype.getWorldMatrix = function () {
  72434. return this._worldTransform;
  72435. };
  72436. Bone.prototype.getInvertedAbsoluteTransform = function () {
  72437. return this._invertedAbsoluteTransform;
  72438. };
  72439. Bone.prototype.getAbsoluteTransform = function () {
  72440. return this._absoluteTransform;
  72441. };
  72442. Object.defineProperty(Bone.prototype, "position", {
  72443. // Properties (matches AbstractMesh properties)
  72444. get: function () {
  72445. return this.getPosition();
  72446. },
  72447. set: function (newPosition) {
  72448. this.setPosition(newPosition);
  72449. },
  72450. enumerable: true,
  72451. configurable: true
  72452. });
  72453. Object.defineProperty(Bone.prototype, "rotation", {
  72454. get: function () {
  72455. return this.getRotation();
  72456. },
  72457. set: function (newRotation) {
  72458. this.setRotation(newRotation);
  72459. },
  72460. enumerable: true,
  72461. configurable: true
  72462. });
  72463. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  72464. get: function () {
  72465. return this.getRotationQuaternion();
  72466. },
  72467. set: function (newRotation) {
  72468. this.setRotationQuaternion(newRotation);
  72469. },
  72470. enumerable: true,
  72471. configurable: true
  72472. });
  72473. Object.defineProperty(Bone.prototype, "scaling", {
  72474. get: function () {
  72475. return this.getScale();
  72476. },
  72477. set: function (newScaling) {
  72478. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  72479. },
  72480. enumerable: true,
  72481. configurable: true
  72482. });
  72483. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  72484. /**
  72485. * Gets the animation properties override
  72486. */
  72487. get: function () {
  72488. return this._skeleton.animationPropertiesOverride;
  72489. },
  72490. enumerable: true,
  72491. configurable: true
  72492. });
  72493. // Methods
  72494. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  72495. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  72496. this._baseMatrix = matrix.clone();
  72497. this._localMatrix = matrix.clone();
  72498. this._skeleton._markAsDirty();
  72499. if (updateDifferenceMatrix) {
  72500. this._updateDifferenceMatrix();
  72501. }
  72502. };
  72503. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  72504. if (!rootMatrix) {
  72505. rootMatrix = this._baseMatrix;
  72506. }
  72507. if (this._parent) {
  72508. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  72509. }
  72510. else {
  72511. this._absoluteTransform.copyFrom(rootMatrix);
  72512. }
  72513. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  72514. for (var index = 0; index < this.children.length; index++) {
  72515. this.children[index]._updateDifferenceMatrix();
  72516. }
  72517. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  72518. };
  72519. Bone.prototype.markAsDirty = function () {
  72520. this._currentRenderId++;
  72521. this._skeleton._markAsDirty();
  72522. };
  72523. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  72524. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  72525. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  72526. // all animation may be coming from a library skeleton, so may need to create animation
  72527. if (this.animations.length === 0) {
  72528. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  72529. this.animations[0].setKeys([]);
  72530. }
  72531. // get animation info / verify there is such a range from the source bone
  72532. var sourceRange = source.animations[0].getRange(rangeName);
  72533. if (!sourceRange) {
  72534. return false;
  72535. }
  72536. var from = sourceRange.from;
  72537. var to = sourceRange.to;
  72538. var sourceKeys = source.animations[0].getKeys();
  72539. // rescaling prep
  72540. var sourceBoneLength = source.length;
  72541. var sourceParent = source.getParent();
  72542. var parent = this.getParent();
  72543. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  72544. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  72545. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  72546. var destKeys = this.animations[0].getKeys();
  72547. // loop vars declaration
  72548. var orig;
  72549. var origTranslation;
  72550. var mat;
  72551. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  72552. orig = sourceKeys[key];
  72553. if (orig.frame >= from && orig.frame <= to) {
  72554. if (rescaleAsRequired) {
  72555. mat = orig.value.clone();
  72556. // scale based on parent ratio, when bone has parent
  72557. if (parentScalingReqd) {
  72558. origTranslation = mat.getTranslation();
  72559. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  72560. // scale based on skeleton dimension ratio when root bone, and value is passed
  72561. }
  72562. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  72563. origTranslation = mat.getTranslation();
  72564. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  72565. // use original when root bone, and no data for skelDimensionsRatio
  72566. }
  72567. else {
  72568. mat = orig.value;
  72569. }
  72570. }
  72571. else {
  72572. mat = orig.value;
  72573. }
  72574. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  72575. }
  72576. }
  72577. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  72578. return true;
  72579. };
  72580. /**
  72581. * Translate the bone in local or world space.
  72582. * @param vec The amount to translate the bone.
  72583. * @param space The space that the translation is in.
  72584. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72585. */
  72586. Bone.prototype.translate = function (vec, space, mesh) {
  72587. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72588. var lm = this.getLocalMatrix();
  72589. if (space == BABYLON.Space.LOCAL) {
  72590. lm.m[12] += vec.x;
  72591. lm.m[13] += vec.y;
  72592. lm.m[14] += vec.z;
  72593. }
  72594. else {
  72595. var wm = null;
  72596. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  72597. if (mesh) {
  72598. wm = mesh.getWorldMatrix();
  72599. }
  72600. this._skeleton.computeAbsoluteTransforms();
  72601. var tmat = Bone._tmpMats[0];
  72602. var tvec = Bone._tmpVecs[0];
  72603. if (this._parent) {
  72604. if (mesh && wm) {
  72605. tmat.copyFrom(this._parent.getAbsoluteTransform());
  72606. tmat.multiplyToRef(wm, tmat);
  72607. }
  72608. else {
  72609. tmat.copyFrom(this._parent.getAbsoluteTransform());
  72610. }
  72611. }
  72612. tmat.m[12] = 0;
  72613. tmat.m[13] = 0;
  72614. tmat.m[14] = 0;
  72615. tmat.invert();
  72616. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  72617. lm.m[12] += tvec.x;
  72618. lm.m[13] += tvec.y;
  72619. lm.m[14] += tvec.z;
  72620. }
  72621. this.markAsDirty();
  72622. };
  72623. /**
  72624. * Set the postion of the bone in local or world space.
  72625. * @param position The position to set the bone.
  72626. * @param space The space that the position is in.
  72627. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72628. */
  72629. Bone.prototype.setPosition = function (position, space, mesh) {
  72630. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72631. var lm = this.getLocalMatrix();
  72632. if (space == BABYLON.Space.LOCAL) {
  72633. lm.m[12] = position.x;
  72634. lm.m[13] = position.y;
  72635. lm.m[14] = position.z;
  72636. }
  72637. else {
  72638. var wm = null;
  72639. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  72640. if (mesh) {
  72641. wm = mesh.getWorldMatrix();
  72642. }
  72643. this._skeleton.computeAbsoluteTransforms();
  72644. var tmat = Bone._tmpMats[0];
  72645. var vec = Bone._tmpVecs[0];
  72646. if (this._parent) {
  72647. if (mesh && wm) {
  72648. tmat.copyFrom(this._parent.getAbsoluteTransform());
  72649. tmat.multiplyToRef(wm, tmat);
  72650. }
  72651. else {
  72652. tmat.copyFrom(this._parent.getAbsoluteTransform());
  72653. }
  72654. }
  72655. tmat.invert();
  72656. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  72657. lm.m[12] = vec.x;
  72658. lm.m[13] = vec.y;
  72659. lm.m[14] = vec.z;
  72660. }
  72661. this.markAsDirty();
  72662. };
  72663. /**
  72664. * Set the absolute postion of the bone (world space).
  72665. * @param position The position to set the bone.
  72666. * @param mesh The mesh that this bone is attached to.
  72667. */
  72668. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  72669. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  72670. };
  72671. /**
  72672. * Set the scale of the bone on the x, y and z axes.
  72673. * @param x The scale of the bone on the x axis.
  72674. * @param x The scale of the bone on the y axis.
  72675. * @param z The scale of the bone on the z axis.
  72676. * @param scaleChildren Set this to true if children of the bone should be scaled.
  72677. */
  72678. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  72679. if (scaleChildren === void 0) { scaleChildren = false; }
  72680. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  72681. if (!scaleChildren) {
  72682. this._negateScaleChildren.x = 1 / x;
  72683. this._negateScaleChildren.y = 1 / y;
  72684. this._negateScaleChildren.z = 1 / z;
  72685. }
  72686. this._syncScaleVector();
  72687. }
  72688. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  72689. };
  72690. /**
  72691. * Scale the bone on the x, y and z axes.
  72692. * @param x The amount to scale the bone on the x axis.
  72693. * @param x The amount to scale the bone on the y axis.
  72694. * @param z The amount to scale the bone on the z axis.
  72695. * @param scaleChildren Set this to true if children of the bone should be scaled.
  72696. */
  72697. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  72698. if (scaleChildren === void 0) { scaleChildren = false; }
  72699. var locMat = this.getLocalMatrix();
  72700. var origLocMat = Bone._tmpMats[0];
  72701. origLocMat.copyFrom(locMat);
  72702. var origLocMatInv = Bone._tmpMats[1];
  72703. origLocMatInv.copyFrom(origLocMat);
  72704. origLocMatInv.invert();
  72705. var scaleMat = Bone._tmpMats[2];
  72706. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  72707. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  72708. this._scaleVector.x *= x;
  72709. this._scaleVector.y *= y;
  72710. this._scaleVector.z *= z;
  72711. locMat.multiplyToRef(origLocMatInv, locMat);
  72712. locMat.multiplyToRef(scaleMat, locMat);
  72713. locMat.multiplyToRef(origLocMat, locMat);
  72714. var parent = this.getParent();
  72715. if (parent) {
  72716. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  72717. }
  72718. else {
  72719. this.getAbsoluteTransform().copyFrom(locMat);
  72720. }
  72721. var len = this.children.length;
  72722. scaleMat.invert();
  72723. for (var i = 0; i < len; i++) {
  72724. var child = this.children[i];
  72725. var cm = child.getLocalMatrix();
  72726. cm.multiplyToRef(scaleMat, cm);
  72727. var lm = child.getLocalMatrix();
  72728. lm.m[12] *= x;
  72729. lm.m[13] *= y;
  72730. lm.m[14] *= z;
  72731. }
  72732. this.computeAbsoluteTransforms();
  72733. if (scaleChildren) {
  72734. for (var i = 0; i < len; i++) {
  72735. this.children[i].scale(x, y, z, scaleChildren);
  72736. }
  72737. }
  72738. this.markAsDirty();
  72739. };
  72740. /**
  72741. * Set the yaw, pitch, and roll of the bone in local or world space.
  72742. * @param yaw The rotation of the bone on the y axis.
  72743. * @param pitch The rotation of the bone on the x axis.
  72744. * @param roll The rotation of the bone on the z axis.
  72745. * @param space The space that the axes of rotation are in.
  72746. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72747. */
  72748. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  72749. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72750. var rotMat = Bone._tmpMats[0];
  72751. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  72752. var rotMatInv = Bone._tmpMats[1];
  72753. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  72754. rotMatInv.multiplyToRef(rotMat, rotMat);
  72755. this._rotateWithMatrix(rotMat, space, mesh);
  72756. };
  72757. /**
  72758. * Rotate the bone on an axis in local or world space.
  72759. * @param axis The axis to rotate the bone on.
  72760. * @param amount The amount to rotate the bone.
  72761. * @param space The space that the axis is in.
  72762. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72763. */
  72764. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  72765. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72766. var rmat = Bone._tmpMats[0];
  72767. rmat.m[12] = 0;
  72768. rmat.m[13] = 0;
  72769. rmat.m[14] = 0;
  72770. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  72771. this._rotateWithMatrix(rmat, space, mesh);
  72772. };
  72773. /**
  72774. * Set the rotation of the bone to a particular axis angle in local or world space.
  72775. * @param axis The axis to rotate the bone on.
  72776. * @param angle The angle that the bone should be rotated to.
  72777. * @param space The space that the axis is in.
  72778. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72779. */
  72780. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  72781. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72782. var rotMat = Bone._tmpMats[0];
  72783. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  72784. var rotMatInv = Bone._tmpMats[1];
  72785. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  72786. rotMatInv.multiplyToRef(rotMat, rotMat);
  72787. this._rotateWithMatrix(rotMat, space, mesh);
  72788. };
  72789. /**
  72790. * Set the euler rotation of the bone in local of world space.
  72791. * @param rotation The euler rotation that the bone should be set to.
  72792. * @param space The space that the rotation is in.
  72793. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72794. */
  72795. Bone.prototype.setRotation = function (rotation, space, mesh) {
  72796. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72797. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  72798. };
  72799. /**
  72800. * Set the quaternion rotation of the bone in local of world space.
  72801. * @param quat The quaternion rotation that the bone should be set to.
  72802. * @param space The space that the rotation is in.
  72803. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72804. */
  72805. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  72806. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72807. var rotMatInv = Bone._tmpMats[0];
  72808. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  72809. var rotMat = Bone._tmpMats[1];
  72810. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  72811. rotMatInv.multiplyToRef(rotMat, rotMat);
  72812. this._rotateWithMatrix(rotMat, space, mesh);
  72813. };
  72814. /**
  72815. * Set the rotation matrix of the bone in local of world space.
  72816. * @param rotMat The rotation matrix that the bone should be set to.
  72817. * @param space The space that the rotation is in.
  72818. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72819. */
  72820. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  72821. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72822. var rotMatInv = Bone._tmpMats[0];
  72823. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  72824. var rotMat2 = Bone._tmpMats[1];
  72825. rotMat2.copyFrom(rotMat);
  72826. rotMatInv.multiplyToRef(rotMat, rotMat2);
  72827. this._rotateWithMatrix(rotMat2, space, mesh);
  72828. };
  72829. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  72830. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72831. var lmat = this.getLocalMatrix();
  72832. var lx = lmat.m[12];
  72833. var ly = lmat.m[13];
  72834. var lz = lmat.m[14];
  72835. var parent = this.getParent();
  72836. var parentScale = Bone._tmpMats[3];
  72837. var parentScaleInv = Bone._tmpMats[4];
  72838. if (parent) {
  72839. if (space == BABYLON.Space.WORLD) {
  72840. if (mesh) {
  72841. parentScale.copyFrom(mesh.getWorldMatrix());
  72842. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  72843. }
  72844. else {
  72845. parentScale.copyFrom(parent.getAbsoluteTransform());
  72846. }
  72847. }
  72848. else {
  72849. parentScale = parent._scaleMatrix;
  72850. }
  72851. parentScaleInv.copyFrom(parentScale);
  72852. parentScaleInv.invert();
  72853. lmat.multiplyToRef(parentScale, lmat);
  72854. lmat.multiplyToRef(rmat, lmat);
  72855. lmat.multiplyToRef(parentScaleInv, lmat);
  72856. }
  72857. else {
  72858. if (space == BABYLON.Space.WORLD && mesh) {
  72859. parentScale.copyFrom(mesh.getWorldMatrix());
  72860. parentScaleInv.copyFrom(parentScale);
  72861. parentScaleInv.invert();
  72862. lmat.multiplyToRef(parentScale, lmat);
  72863. lmat.multiplyToRef(rmat, lmat);
  72864. lmat.multiplyToRef(parentScaleInv, lmat);
  72865. }
  72866. else {
  72867. lmat.multiplyToRef(rmat, lmat);
  72868. }
  72869. }
  72870. lmat.m[12] = lx;
  72871. lmat.m[13] = ly;
  72872. lmat.m[14] = lz;
  72873. this.computeAbsoluteTransforms();
  72874. this.markAsDirty();
  72875. };
  72876. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  72877. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72878. if (space == BABYLON.Space.WORLD) {
  72879. var scaleMatrix = Bone._tmpMats[2];
  72880. scaleMatrix.copyFrom(this._scaleMatrix);
  72881. rotMatInv.copyFrom(this.getAbsoluteTransform());
  72882. if (mesh) {
  72883. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  72884. var meshScale = Bone._tmpMats[3];
  72885. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  72886. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  72887. }
  72888. rotMatInv.invert();
  72889. scaleMatrix.m[0] *= this._scalingDeterminant;
  72890. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  72891. }
  72892. else {
  72893. rotMatInv.copyFrom(this.getLocalMatrix());
  72894. rotMatInv.invert();
  72895. var scaleMatrix = Bone._tmpMats[2];
  72896. scaleMatrix.copyFrom(this._scaleMatrix);
  72897. if (this._parent) {
  72898. var pscaleMatrix = Bone._tmpMats[3];
  72899. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  72900. pscaleMatrix.invert();
  72901. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  72902. }
  72903. else {
  72904. scaleMatrix.m[0] *= this._scalingDeterminant;
  72905. }
  72906. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  72907. }
  72908. };
  72909. /**
  72910. * Get the scale of the bone
  72911. * @returns the scale of the bone
  72912. */
  72913. Bone.prototype.getScale = function () {
  72914. return this._scaleVector.clone();
  72915. };
  72916. /**
  72917. * Copy the scale of the bone to a vector3.
  72918. * @param result The vector3 to copy the scale to
  72919. */
  72920. Bone.prototype.getScaleToRef = function (result) {
  72921. result.copyFrom(this._scaleVector);
  72922. };
  72923. /**
  72924. * Get the position of the bone in local or world space.
  72925. * @param space The space that the returned position is in.
  72926. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72927. * @returns The position of the bone
  72928. */
  72929. Bone.prototype.getPosition = function (space, mesh) {
  72930. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72931. if (mesh === void 0) { mesh = null; }
  72932. var pos = BABYLON.Vector3.Zero();
  72933. this.getPositionToRef(space, mesh, pos);
  72934. return pos;
  72935. };
  72936. /**
  72937. * Copy the position of the bone to a vector3 in local or world space.
  72938. * @param space The space that the returned position is in.
  72939. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72940. * @param result The vector3 to copy the position to.
  72941. */
  72942. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  72943. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72944. if (space == BABYLON.Space.LOCAL) {
  72945. var lm = this.getLocalMatrix();
  72946. result.x = lm.m[12];
  72947. result.y = lm.m[13];
  72948. result.z = lm.m[14];
  72949. }
  72950. else {
  72951. var wm = null;
  72952. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  72953. if (mesh) {
  72954. wm = mesh.getWorldMatrix();
  72955. }
  72956. this._skeleton.computeAbsoluteTransforms();
  72957. var tmat = Bone._tmpMats[0];
  72958. if (mesh && wm) {
  72959. tmat.copyFrom(this.getAbsoluteTransform());
  72960. tmat.multiplyToRef(wm, tmat);
  72961. }
  72962. else {
  72963. tmat = this.getAbsoluteTransform();
  72964. }
  72965. result.x = tmat.m[12];
  72966. result.y = tmat.m[13];
  72967. result.z = tmat.m[14];
  72968. }
  72969. };
  72970. /**
  72971. * Get the absolute position of the bone (world space).
  72972. * @param mesh The mesh that this bone is attached to.
  72973. * @returns The absolute position of the bone
  72974. */
  72975. Bone.prototype.getAbsolutePosition = function (mesh) {
  72976. if (mesh === void 0) { mesh = null; }
  72977. var pos = BABYLON.Vector3.Zero();
  72978. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  72979. return pos;
  72980. };
  72981. /**
  72982. * Copy the absolute position of the bone (world space) to the result param.
  72983. * @param mesh The mesh that this bone is attached to.
  72984. * @param result The vector3 to copy the absolute position to.
  72985. */
  72986. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  72987. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  72988. };
  72989. /**
  72990. * Compute the absolute transforms of this bone and its children.
  72991. */
  72992. Bone.prototype.computeAbsoluteTransforms = function () {
  72993. if (this._parent) {
  72994. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  72995. }
  72996. else {
  72997. this._absoluteTransform.copyFrom(this._localMatrix);
  72998. var poseMatrix = this._skeleton.getPoseMatrix();
  72999. if (poseMatrix) {
  73000. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  73001. }
  73002. }
  73003. var children = this.children;
  73004. var len = children.length;
  73005. for (var i = 0; i < len; i++) {
  73006. children[i].computeAbsoluteTransforms();
  73007. }
  73008. };
  73009. Bone.prototype._syncScaleVector = function () {
  73010. var lm = this.getLocalMatrix();
  73011. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  73012. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  73013. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  73014. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  73015. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  73016. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  73017. this._scaleVector.x = xs * Math.sqrt(xsq);
  73018. this._scaleVector.y = ys * Math.sqrt(ysq);
  73019. this._scaleVector.z = zs * Math.sqrt(zsq);
  73020. if (this._parent) {
  73021. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  73022. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  73023. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  73024. }
  73025. 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);
  73026. };
  73027. /**
  73028. * Get the world direction from an axis that is in the local space of the bone.
  73029. * @param localAxis The local direction that is used to compute the world direction.
  73030. * @param mesh The mesh that this bone is attached to.
  73031. * @returns The world direction
  73032. */
  73033. Bone.prototype.getDirection = function (localAxis, mesh) {
  73034. if (mesh === void 0) { mesh = null; }
  73035. var result = BABYLON.Vector3.Zero();
  73036. this.getDirectionToRef(localAxis, mesh, result);
  73037. return result;
  73038. };
  73039. /**
  73040. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  73041. * @param localAxis The local direction that is used to compute the world direction.
  73042. * @param mesh The mesh that this bone is attached to.
  73043. * @param result The vector3 that the world direction will be copied to.
  73044. */
  73045. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  73046. if (mesh === void 0) { mesh = null; }
  73047. var wm = null;
  73048. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  73049. if (mesh) {
  73050. wm = mesh.getWorldMatrix();
  73051. }
  73052. this._skeleton.computeAbsoluteTransforms();
  73053. var mat = Bone._tmpMats[0];
  73054. mat.copyFrom(this.getAbsoluteTransform());
  73055. if (mesh && wm) {
  73056. mat.multiplyToRef(wm, mat);
  73057. }
  73058. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  73059. result.normalize();
  73060. };
  73061. /**
  73062. * Get the euler rotation of the bone in local or world space.
  73063. * @param space The space that the rotation should be in.
  73064. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73065. * @returns The euler rotation
  73066. */
  73067. Bone.prototype.getRotation = function (space, mesh) {
  73068. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73069. if (mesh === void 0) { mesh = null; }
  73070. var result = BABYLON.Vector3.Zero();
  73071. this.getRotationToRef(space, mesh, result);
  73072. return result;
  73073. };
  73074. /**
  73075. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  73076. * @param space The space that the rotation should be in.
  73077. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73078. * @param result The vector3 that the rotation should be copied to.
  73079. */
  73080. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  73081. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73082. if (mesh === void 0) { mesh = null; }
  73083. var quat = Bone._tmpQuat;
  73084. this.getRotationQuaternionToRef(space, mesh, quat);
  73085. quat.toEulerAnglesToRef(result);
  73086. };
  73087. /**
  73088. * Get the quaternion rotation of the bone in either local or world space.
  73089. * @param space The space that the rotation should be in.
  73090. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73091. * @returns The quaternion rotation
  73092. */
  73093. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  73094. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73095. if (mesh === void 0) { mesh = null; }
  73096. var result = BABYLON.Quaternion.Identity();
  73097. this.getRotationQuaternionToRef(space, mesh, result);
  73098. return result;
  73099. };
  73100. /**
  73101. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  73102. * @param space The space that the rotation should be in.
  73103. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73104. * @param result The quaternion that the rotation should be copied to.
  73105. */
  73106. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  73107. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73108. if (mesh === void 0) { mesh = null; }
  73109. if (space == BABYLON.Space.LOCAL) {
  73110. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  73111. }
  73112. else {
  73113. var mat = Bone._tmpMats[0];
  73114. var amat = this.getAbsoluteTransform();
  73115. if (mesh) {
  73116. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  73117. }
  73118. else {
  73119. mat.copyFrom(amat);
  73120. }
  73121. mat.m[0] *= this._scalingDeterminant;
  73122. mat.m[1] *= this._scalingDeterminant;
  73123. mat.m[2] *= this._scalingDeterminant;
  73124. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  73125. }
  73126. };
  73127. /**
  73128. * Get the rotation matrix of the bone in local or world space.
  73129. * @param space The space that the rotation should be in.
  73130. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73131. * @returns The rotation matrix
  73132. */
  73133. Bone.prototype.getRotationMatrix = function (space, mesh) {
  73134. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73135. var result = BABYLON.Matrix.Identity();
  73136. this.getRotationMatrixToRef(space, mesh, result);
  73137. return result;
  73138. };
  73139. /**
  73140. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  73141. * @param space The space that the rotation should be in.
  73142. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73143. * @param result The quaternion that the rotation should be copied to.
  73144. */
  73145. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  73146. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73147. if (space == BABYLON.Space.LOCAL) {
  73148. this.getLocalMatrix().getRotationMatrixToRef(result);
  73149. }
  73150. else {
  73151. var mat = Bone._tmpMats[0];
  73152. var amat = this.getAbsoluteTransform();
  73153. if (mesh) {
  73154. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  73155. }
  73156. else {
  73157. mat.copyFrom(amat);
  73158. }
  73159. mat.m[0] *= this._scalingDeterminant;
  73160. mat.m[1] *= this._scalingDeterminant;
  73161. mat.m[2] *= this._scalingDeterminant;
  73162. mat.getRotationMatrixToRef(result);
  73163. }
  73164. };
  73165. /**
  73166. * Get the world position of a point that is in the local space of the bone.
  73167. * @param position The local position
  73168. * @param mesh The mesh that this bone is attached to.
  73169. * @returns The world position
  73170. */
  73171. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  73172. if (mesh === void 0) { mesh = null; }
  73173. var result = BABYLON.Vector3.Zero();
  73174. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  73175. return result;
  73176. };
  73177. /**
  73178. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  73179. * @param position The local position
  73180. * @param mesh The mesh that this bone is attached to.
  73181. * @param result The vector3 that the world position should be copied to.
  73182. */
  73183. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  73184. if (mesh === void 0) { mesh = null; }
  73185. var wm = null;
  73186. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  73187. if (mesh) {
  73188. wm = mesh.getWorldMatrix();
  73189. }
  73190. this._skeleton.computeAbsoluteTransforms();
  73191. var tmat = Bone._tmpMats[0];
  73192. if (mesh && wm) {
  73193. tmat.copyFrom(this.getAbsoluteTransform());
  73194. tmat.multiplyToRef(wm, tmat);
  73195. }
  73196. else {
  73197. tmat = this.getAbsoluteTransform();
  73198. }
  73199. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  73200. };
  73201. /**
  73202. * Get the local position of a point that is in world space.
  73203. * @param position The world position
  73204. * @param mesh The mesh that this bone is attached to.
  73205. * @returns The local position
  73206. */
  73207. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  73208. if (mesh === void 0) { mesh = null; }
  73209. var result = BABYLON.Vector3.Zero();
  73210. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  73211. return result;
  73212. };
  73213. /**
  73214. * Get the local position of a point that is in world space and copy it to the result param.
  73215. * @param position The world position
  73216. * @param mesh The mesh that this bone is attached to.
  73217. * @param result The vector3 that the local position should be copied to.
  73218. */
  73219. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  73220. if (mesh === void 0) { mesh = null; }
  73221. var wm = null;
  73222. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  73223. if (mesh) {
  73224. wm = mesh.getWorldMatrix();
  73225. }
  73226. this._skeleton.computeAbsoluteTransforms();
  73227. var tmat = Bone._tmpMats[0];
  73228. tmat.copyFrom(this.getAbsoluteTransform());
  73229. if (mesh && wm) {
  73230. tmat.multiplyToRef(wm, tmat);
  73231. }
  73232. tmat.invert();
  73233. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  73234. };
  73235. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  73236. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  73237. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  73238. return Bone;
  73239. }(BABYLON.Node));
  73240. BABYLON.Bone = Bone;
  73241. })(BABYLON || (BABYLON = {}));
  73242. //# sourceMappingURL=babylon.bone.js.map
  73243. "use strict";
  73244. var BABYLON;
  73245. (function (BABYLON) {
  73246. var BoneIKController = /** @class */ (function () {
  73247. function BoneIKController(mesh, bone, options) {
  73248. this.targetPosition = BABYLON.Vector3.Zero();
  73249. this.poleTargetPosition = BABYLON.Vector3.Zero();
  73250. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  73251. this.poleAngle = 0;
  73252. this.slerpAmount = 1;
  73253. this._bone1Quat = BABYLON.Quaternion.Identity();
  73254. this._bone1Mat = BABYLON.Matrix.Identity();
  73255. this._bone2Ang = Math.PI;
  73256. this._maxAngle = Math.PI;
  73257. this._rightHandedSystem = false;
  73258. this._bendAxis = BABYLON.Vector3.Right();
  73259. this._slerping = false;
  73260. this._adjustRoll = 0;
  73261. this._bone2 = bone;
  73262. this._bone1 = bone.getParent();
  73263. if (!this._bone1) {
  73264. return;
  73265. }
  73266. this.mesh = mesh;
  73267. var bonePos = bone.getPosition();
  73268. if (bone.getAbsoluteTransform().determinant() > 0) {
  73269. this._rightHandedSystem = true;
  73270. this._bendAxis.x = 0;
  73271. this._bendAxis.y = 0;
  73272. this._bendAxis.z = -1;
  73273. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  73274. this._adjustRoll = Math.PI * .5;
  73275. this._bendAxis.z = 1;
  73276. }
  73277. }
  73278. if (this._bone1.length) {
  73279. var boneScale1 = this._bone1.getScale();
  73280. var boneScale2 = this._bone2.getScale();
  73281. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  73282. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  73283. }
  73284. else if (this._bone1.children[0]) {
  73285. mesh.computeWorldMatrix(true);
  73286. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  73287. var pos2 = this._bone2.getAbsolutePosition(mesh);
  73288. var pos3 = this._bone1.getAbsolutePosition(mesh);
  73289. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  73290. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  73291. }
  73292. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  73293. this.maxAngle = Math.PI;
  73294. if (options) {
  73295. if (options.targetMesh) {
  73296. this.targetMesh = options.targetMesh;
  73297. this.targetMesh.computeWorldMatrix(true);
  73298. }
  73299. if (options.poleTargetMesh) {
  73300. this.poleTargetMesh = options.poleTargetMesh;
  73301. this.poleTargetMesh.computeWorldMatrix(true);
  73302. }
  73303. else if (options.poleTargetBone) {
  73304. this.poleTargetBone = options.poleTargetBone;
  73305. }
  73306. else if (this._bone1.getParent()) {
  73307. this.poleTargetBone = this._bone1.getParent();
  73308. }
  73309. if (options.poleTargetLocalOffset) {
  73310. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  73311. }
  73312. if (options.poleAngle) {
  73313. this.poleAngle = options.poleAngle;
  73314. }
  73315. if (options.bendAxis) {
  73316. this._bendAxis.copyFrom(options.bendAxis);
  73317. }
  73318. if (options.maxAngle) {
  73319. this.maxAngle = options.maxAngle;
  73320. }
  73321. if (options.slerpAmount) {
  73322. this.slerpAmount = options.slerpAmount;
  73323. }
  73324. }
  73325. }
  73326. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  73327. get: function () {
  73328. return this._maxAngle;
  73329. },
  73330. set: function (value) {
  73331. this._setMaxAngle(value);
  73332. },
  73333. enumerable: true,
  73334. configurable: true
  73335. });
  73336. BoneIKController.prototype._setMaxAngle = function (ang) {
  73337. if (ang < 0) {
  73338. ang = 0;
  73339. }
  73340. if (ang > Math.PI || ang == undefined) {
  73341. ang = Math.PI;
  73342. }
  73343. this._maxAngle = ang;
  73344. var a = this._bone1Length;
  73345. var b = this._bone2Length;
  73346. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  73347. };
  73348. BoneIKController.prototype.update = function () {
  73349. var bone1 = this._bone1;
  73350. if (!bone1) {
  73351. return;
  73352. }
  73353. var target = this.targetPosition;
  73354. var poleTarget = this.poleTargetPosition;
  73355. var mat1 = BoneIKController._tmpMats[0];
  73356. var mat2 = BoneIKController._tmpMats[1];
  73357. if (this.targetMesh) {
  73358. target.copyFrom(this.targetMesh.getAbsolutePosition());
  73359. }
  73360. if (this.poleTargetBone) {
  73361. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  73362. }
  73363. else if (this.poleTargetMesh) {
  73364. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  73365. }
  73366. var bonePos = BoneIKController._tmpVecs[0];
  73367. var zaxis = BoneIKController._tmpVecs[1];
  73368. var xaxis = BoneIKController._tmpVecs[2];
  73369. var yaxis = BoneIKController._tmpVecs[3];
  73370. var upAxis = BoneIKController._tmpVecs[4];
  73371. var _tmpQuat = BoneIKController._tmpQuat;
  73372. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  73373. poleTarget.subtractToRef(bonePos, upAxis);
  73374. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  73375. upAxis.y = 1;
  73376. }
  73377. else {
  73378. upAxis.normalize();
  73379. }
  73380. target.subtractToRef(bonePos, yaxis);
  73381. yaxis.normalize();
  73382. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  73383. zaxis.normalize();
  73384. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  73385. xaxis.normalize();
  73386. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  73387. var a = this._bone1Length;
  73388. var b = this._bone2Length;
  73389. var c = BABYLON.Vector3.Distance(bonePos, target);
  73390. if (this._maxReach > 0) {
  73391. c = Math.min(this._maxReach, c);
  73392. }
  73393. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  73394. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  73395. if (acosa > 1) {
  73396. acosa = 1;
  73397. }
  73398. if (acosb > 1) {
  73399. acosb = 1;
  73400. }
  73401. if (acosa < -1) {
  73402. acosa = -1;
  73403. }
  73404. if (acosb < -1) {
  73405. acosb = -1;
  73406. }
  73407. var angA = Math.acos(acosa);
  73408. var angB = Math.acos(acosb);
  73409. var angC = -angA - angB;
  73410. if (this._rightHandedSystem) {
  73411. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  73412. mat2.multiplyToRef(mat1, mat1);
  73413. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  73414. mat2.multiplyToRef(mat1, mat1);
  73415. }
  73416. else {
  73417. var _tmpVec = BoneIKController._tmpVecs[5];
  73418. _tmpVec.copyFrom(this._bendAxis);
  73419. _tmpVec.x *= -1;
  73420. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  73421. mat2.multiplyToRef(mat1, mat1);
  73422. }
  73423. if (this.poleAngle) {
  73424. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  73425. mat1.multiplyToRef(mat2, mat1);
  73426. }
  73427. if (this._bone1) {
  73428. if (this.slerpAmount < 1) {
  73429. if (!this._slerping) {
  73430. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  73431. }
  73432. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  73433. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  73434. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  73435. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  73436. this._slerping = true;
  73437. }
  73438. else {
  73439. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  73440. this._bone1Mat.copyFrom(mat1);
  73441. this._slerping = false;
  73442. }
  73443. }
  73444. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  73445. this._bone2Ang = angC;
  73446. };
  73447. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  73448. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  73449. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  73450. return BoneIKController;
  73451. }());
  73452. BABYLON.BoneIKController = BoneIKController;
  73453. })(BABYLON || (BABYLON = {}));
  73454. //# sourceMappingURL=babylon.boneIKController.js.map
  73455. "use strict";
  73456. var BABYLON;
  73457. (function (BABYLON) {
  73458. var BoneLookController = /** @class */ (function () {
  73459. /**
  73460. * Create a BoneLookController
  73461. * @param mesh the mesh that the bone belongs to
  73462. * @param bone the bone that will be looking to the target
  73463. * @param target the target Vector3 to look at
  73464. * @param settings optional settings:
  73465. * - maxYaw: the maximum angle the bone will yaw to
  73466. * - minYaw: the minimum angle the bone will yaw to
  73467. * - maxPitch: the maximum angle the bone will pitch to
  73468. * - minPitch: the minimum angle the bone will yaw to
  73469. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  73470. * - upAxis: the up axis of the coordinate system
  73471. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  73472. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  73473. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  73474. * - adjustYaw: used to make an adjustment to the yaw of the bone
  73475. * - adjustPitch: used to make an adjustment to the pitch of the bone
  73476. * - adjustRoll: used to make an adjustment to the roll of the bone
  73477. **/
  73478. function BoneLookController(mesh, bone, target, options) {
  73479. /**
  73480. * The up axis of the coordinate system that is used when the bone is rotated.
  73481. */
  73482. this.upAxis = BABYLON.Vector3.Up();
  73483. /**
  73484. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  73485. */
  73486. this.upAxisSpace = BABYLON.Space.LOCAL;
  73487. /**
  73488. * Used to make an adjustment to the yaw of the bone.
  73489. */
  73490. this.adjustYaw = 0;
  73491. /**
  73492. * Used to make an adjustment to the pitch of the bone.
  73493. */
  73494. this.adjustPitch = 0;
  73495. /**
  73496. * Used to make an adjustment to the roll of the bone.
  73497. */
  73498. this.adjustRoll = 0;
  73499. /**
  73500. * 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).
  73501. */
  73502. this.slerpAmount = 1;
  73503. this._boneQuat = BABYLON.Quaternion.Identity();
  73504. this._slerping = false;
  73505. this._firstFrameSkipped = false;
  73506. this._fowardAxis = BABYLON.Vector3.Forward();
  73507. this.mesh = mesh;
  73508. this.bone = bone;
  73509. this.target = target;
  73510. if (options) {
  73511. if (options.adjustYaw) {
  73512. this.adjustYaw = options.adjustYaw;
  73513. }
  73514. if (options.adjustPitch) {
  73515. this.adjustPitch = options.adjustPitch;
  73516. }
  73517. if (options.adjustRoll) {
  73518. this.adjustRoll = options.adjustRoll;
  73519. }
  73520. if (options.maxYaw != null) {
  73521. this.maxYaw = options.maxYaw;
  73522. }
  73523. else {
  73524. this.maxYaw = Math.PI;
  73525. }
  73526. if (options.minYaw != null) {
  73527. this.minYaw = options.minYaw;
  73528. }
  73529. else {
  73530. this.minYaw = -Math.PI;
  73531. }
  73532. if (options.maxPitch != null) {
  73533. this.maxPitch = options.maxPitch;
  73534. }
  73535. else {
  73536. this.maxPitch = Math.PI;
  73537. }
  73538. if (options.minPitch != null) {
  73539. this.minPitch = options.minPitch;
  73540. }
  73541. else {
  73542. this.minPitch = -Math.PI;
  73543. }
  73544. if (options.slerpAmount != null) {
  73545. this.slerpAmount = options.slerpAmount;
  73546. }
  73547. if (options.upAxis != null) {
  73548. this.upAxis = options.upAxis;
  73549. }
  73550. if (options.upAxisSpace != null) {
  73551. this.upAxisSpace = options.upAxisSpace;
  73552. }
  73553. if (options.yawAxis != null || options.pitchAxis != null) {
  73554. var newYawAxis = BABYLON.Axis.Y;
  73555. var newPitchAxis = BABYLON.Axis.X;
  73556. if (options.yawAxis != null) {
  73557. newYawAxis = options.yawAxis.clone();
  73558. newYawAxis.normalize();
  73559. }
  73560. if (options.pitchAxis != null) {
  73561. newPitchAxis = options.pitchAxis.clone();
  73562. newPitchAxis.normalize();
  73563. }
  73564. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  73565. this._transformYawPitch = BABYLON.Matrix.Identity();
  73566. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  73567. this._transformYawPitchInv = this._transformYawPitch.clone();
  73568. this._transformYawPitch.invert();
  73569. }
  73570. }
  73571. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  73572. this.upAxisSpace = BABYLON.Space.LOCAL;
  73573. }
  73574. }
  73575. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  73576. /**
  73577. * Get/set the minimum yaw angle that the bone can look to.
  73578. */
  73579. get: function () {
  73580. return this._minYaw;
  73581. },
  73582. set: function (value) {
  73583. this._minYaw = value;
  73584. this._minYawSin = Math.sin(value);
  73585. this._minYawCos = Math.cos(value);
  73586. if (this._maxYaw != null) {
  73587. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  73588. this._yawRange = this._maxYaw - this._minYaw;
  73589. }
  73590. },
  73591. enumerable: true,
  73592. configurable: true
  73593. });
  73594. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  73595. /**
  73596. * Get/set the maximum yaw angle that the bone can look to.
  73597. */
  73598. get: function () {
  73599. return this._maxYaw;
  73600. },
  73601. set: function (value) {
  73602. this._maxYaw = value;
  73603. this._maxYawSin = Math.sin(value);
  73604. this._maxYawCos = Math.cos(value);
  73605. if (this._minYaw != null) {
  73606. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  73607. this._yawRange = this._maxYaw - this._minYaw;
  73608. }
  73609. },
  73610. enumerable: true,
  73611. configurable: true
  73612. });
  73613. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  73614. /**
  73615. * Get/set the minimum pitch angle that the bone can look to.
  73616. */
  73617. get: function () {
  73618. return this._minPitch;
  73619. },
  73620. set: function (value) {
  73621. this._minPitch = value;
  73622. this._minPitchTan = Math.tan(value);
  73623. },
  73624. enumerable: true,
  73625. configurable: true
  73626. });
  73627. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  73628. /**
  73629. * Get/set the maximum pitch angle that the bone can look to.
  73630. */
  73631. get: function () {
  73632. return this._maxPitch;
  73633. },
  73634. set: function (value) {
  73635. this._maxPitch = value;
  73636. this._maxPitchTan = Math.tan(value);
  73637. },
  73638. enumerable: true,
  73639. configurable: true
  73640. });
  73641. /**
  73642. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  73643. */
  73644. BoneLookController.prototype.update = function () {
  73645. //skip the first frame when slerping so that the mesh rotation is correct
  73646. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  73647. this._firstFrameSkipped = true;
  73648. return;
  73649. }
  73650. var bone = this.bone;
  73651. var bonePos = BoneLookController._tmpVecs[0];
  73652. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  73653. var target = this.target;
  73654. var _tmpMat1 = BoneLookController._tmpMats[0];
  73655. var _tmpMat2 = BoneLookController._tmpMats[1];
  73656. var mesh = this.mesh;
  73657. var parentBone = bone.getParent();
  73658. var upAxis = BoneLookController._tmpVecs[1];
  73659. upAxis.copyFrom(this.upAxis);
  73660. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  73661. if (this._transformYawPitch) {
  73662. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  73663. }
  73664. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  73665. }
  73666. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  73667. mesh.getDirectionToRef(upAxis, upAxis);
  73668. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  73669. upAxis.normalize();
  73670. }
  73671. }
  73672. var checkYaw = false;
  73673. var checkPitch = false;
  73674. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  73675. checkYaw = true;
  73676. }
  73677. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  73678. checkPitch = true;
  73679. }
  73680. if (checkYaw || checkPitch) {
  73681. var spaceMat = BoneLookController._tmpMats[2];
  73682. var spaceMatInv = BoneLookController._tmpMats[3];
  73683. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  73684. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  73685. }
  73686. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  73687. spaceMat.copyFrom(mesh.getWorldMatrix());
  73688. }
  73689. else {
  73690. var forwardAxis = BoneLookController._tmpVecs[2];
  73691. forwardAxis.copyFrom(this._fowardAxis);
  73692. if (this._transformYawPitch) {
  73693. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  73694. }
  73695. if (parentBone) {
  73696. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  73697. }
  73698. else {
  73699. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  73700. }
  73701. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  73702. rightAxis.normalize();
  73703. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  73704. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  73705. }
  73706. spaceMat.invertToRef(spaceMatInv);
  73707. var xzlen = null;
  73708. if (checkPitch) {
  73709. var localTarget = BoneLookController._tmpVecs[3];
  73710. target.subtractToRef(bonePos, localTarget);
  73711. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  73712. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  73713. var pitch = Math.atan2(localTarget.y, xzlen);
  73714. var newPitch = pitch;
  73715. if (pitch > this._maxPitch) {
  73716. localTarget.y = this._maxPitchTan * xzlen;
  73717. newPitch = this._maxPitch;
  73718. }
  73719. else if (pitch < this._minPitch) {
  73720. localTarget.y = this._minPitchTan * xzlen;
  73721. newPitch = this._minPitch;
  73722. }
  73723. if (pitch != newPitch) {
  73724. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  73725. localTarget.addInPlace(bonePos);
  73726. target = localTarget;
  73727. }
  73728. }
  73729. if (checkYaw) {
  73730. var localTarget = BoneLookController._tmpVecs[4];
  73731. target.subtractToRef(bonePos, localTarget);
  73732. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  73733. var yaw = Math.atan2(localTarget.x, localTarget.z);
  73734. var newYaw = yaw;
  73735. if (yaw > this._maxYaw || yaw < this._minYaw) {
  73736. if (xzlen == null) {
  73737. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  73738. }
  73739. if (this._yawRange > Math.PI) {
  73740. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  73741. localTarget.z = this._maxYawCos * xzlen;
  73742. localTarget.x = this._maxYawSin * xzlen;
  73743. newYaw = this._maxYaw;
  73744. }
  73745. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  73746. localTarget.z = this._minYawCos * xzlen;
  73747. localTarget.x = this._minYawSin * xzlen;
  73748. newYaw = this._minYaw;
  73749. }
  73750. }
  73751. else {
  73752. if (yaw > this._maxYaw) {
  73753. localTarget.z = this._maxYawCos * xzlen;
  73754. localTarget.x = this._maxYawSin * xzlen;
  73755. newYaw = this._maxYaw;
  73756. }
  73757. else if (yaw < this._minYaw) {
  73758. localTarget.z = this._minYawCos * xzlen;
  73759. localTarget.x = this._minYawSin * xzlen;
  73760. newYaw = this._minYaw;
  73761. }
  73762. }
  73763. }
  73764. if (this._slerping && this._yawRange > Math.PI) {
  73765. //are we going to be crossing into the min/max region?
  73766. var boneFwd = BoneLookController._tmpVecs[8];
  73767. boneFwd.copyFrom(BABYLON.Axis.Z);
  73768. if (this._transformYawPitch) {
  73769. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  73770. }
  73771. var boneRotMat = BoneLookController._tmpMats[4];
  73772. this._boneQuat.toRotationMatrix(boneRotMat);
  73773. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  73774. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  73775. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  73776. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  73777. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  73778. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  73779. if (angBtwTar > angBtwMidYaw) {
  73780. if (xzlen == null) {
  73781. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  73782. }
  73783. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  73784. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  73785. if (angBtwMin < angBtwMax) {
  73786. newYaw = boneYaw + Math.PI * .75;
  73787. localTarget.z = Math.cos(newYaw) * xzlen;
  73788. localTarget.x = Math.sin(newYaw) * xzlen;
  73789. }
  73790. else {
  73791. newYaw = boneYaw - Math.PI * .75;
  73792. localTarget.z = Math.cos(newYaw) * xzlen;
  73793. localTarget.x = Math.sin(newYaw) * xzlen;
  73794. }
  73795. }
  73796. }
  73797. if (yaw != newYaw) {
  73798. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  73799. localTarget.addInPlace(bonePos);
  73800. target = localTarget;
  73801. }
  73802. }
  73803. }
  73804. var zaxis = BoneLookController._tmpVecs[5];
  73805. var xaxis = BoneLookController._tmpVecs[6];
  73806. var yaxis = BoneLookController._tmpVecs[7];
  73807. var _tmpQuat = BoneLookController._tmpQuat;
  73808. target.subtractToRef(bonePos, zaxis);
  73809. zaxis.normalize();
  73810. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  73811. xaxis.normalize();
  73812. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  73813. yaxis.normalize();
  73814. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  73815. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  73816. return;
  73817. }
  73818. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  73819. return;
  73820. }
  73821. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  73822. return;
  73823. }
  73824. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  73825. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  73826. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  73827. }
  73828. if (this.slerpAmount < 1) {
  73829. if (!this._slerping) {
  73830. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  73831. }
  73832. if (this._transformYawPitch) {
  73833. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  73834. }
  73835. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  73836. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  73837. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  73838. this._slerping = true;
  73839. }
  73840. else {
  73841. if (this._transformYawPitch) {
  73842. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  73843. }
  73844. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  73845. this._slerping = false;
  73846. }
  73847. };
  73848. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  73849. var angDiff = ang2 - ang1;
  73850. angDiff %= Math.PI * 2;
  73851. if (angDiff > Math.PI) {
  73852. angDiff -= Math.PI * 2;
  73853. }
  73854. else if (angDiff < -Math.PI) {
  73855. angDiff += Math.PI * 2;
  73856. }
  73857. return angDiff;
  73858. };
  73859. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  73860. ang1 %= (2 * Math.PI);
  73861. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  73862. ang2 %= (2 * Math.PI);
  73863. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  73864. var ab = 0;
  73865. if (ang1 < ang2) {
  73866. ab = ang2 - ang1;
  73867. }
  73868. else {
  73869. ab = ang1 - ang2;
  73870. }
  73871. if (ab > Math.PI) {
  73872. ab = Math.PI * 2 - ab;
  73873. }
  73874. return ab;
  73875. };
  73876. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  73877. ang %= (2 * Math.PI);
  73878. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  73879. ang1 %= (2 * Math.PI);
  73880. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  73881. ang2 %= (2 * Math.PI);
  73882. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  73883. if (ang1 < ang2) {
  73884. if (ang > ang1 && ang < ang2) {
  73885. return true;
  73886. }
  73887. }
  73888. else {
  73889. if (ang > ang2 && ang < ang1) {
  73890. return true;
  73891. }
  73892. }
  73893. return false;
  73894. };
  73895. 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()];
  73896. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  73897. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  73898. return BoneLookController;
  73899. }());
  73900. BABYLON.BoneLookController = BoneLookController;
  73901. })(BABYLON || (BABYLON = {}));
  73902. //# sourceMappingURL=babylon.boneLookController.js.map
  73903. "use strict";
  73904. var BABYLON;
  73905. (function (BABYLON) {
  73906. var Skeleton = /** @class */ (function () {
  73907. function Skeleton(name, id, scene) {
  73908. this.name = name;
  73909. this.id = id;
  73910. this.bones = new Array();
  73911. this.needInitialSkinMatrix = false;
  73912. this._isDirty = true;
  73913. this._meshesWithPoseMatrix = new Array();
  73914. this._identity = BABYLON.Matrix.Identity();
  73915. this._ranges = {};
  73916. this._lastAbsoluteTransformsUpdateId = -1;
  73917. /**
  73918. * Specifies if the skeleton should be serialized.
  73919. */
  73920. this.doNotSerialize = false;
  73921. // Events
  73922. /**
  73923. * An event triggered before computing the skeleton's matrices
  73924. * @type {BABYLON.Observable}
  73925. */
  73926. this.onBeforeComputeObservable = new BABYLON.Observable();
  73927. this.bones = [];
  73928. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  73929. scene.skeletons.push(this);
  73930. //make sure it will recalculate the matrix next time prepare is called.
  73931. this._isDirty = true;
  73932. }
  73933. // Members
  73934. Skeleton.prototype.getTransformMatrices = function (mesh) {
  73935. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  73936. return mesh._bonesTransformMatrices;
  73937. }
  73938. if (!this._transformMatrices) {
  73939. this.prepare();
  73940. }
  73941. return this._transformMatrices;
  73942. };
  73943. Skeleton.prototype.getScene = function () {
  73944. return this._scene;
  73945. };
  73946. // Methods
  73947. /**
  73948. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  73949. */
  73950. Skeleton.prototype.toString = function (fullDetails) {
  73951. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  73952. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  73953. if (fullDetails) {
  73954. ret += ", Ranges: {";
  73955. var first = true;
  73956. for (var name_1 in this._ranges) {
  73957. if (first) {
  73958. ret += ", ";
  73959. first = false;
  73960. }
  73961. ret += name_1;
  73962. }
  73963. ret += "}";
  73964. }
  73965. return ret;
  73966. };
  73967. /**
  73968. * Get bone's index searching by name
  73969. * @param {string} name is bone's name to search for
  73970. * @return {number} Indice of the bone. Returns -1 if not found
  73971. */
  73972. Skeleton.prototype.getBoneIndexByName = function (name) {
  73973. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  73974. if (this.bones[boneIndex].name === name) {
  73975. return boneIndex;
  73976. }
  73977. }
  73978. return -1;
  73979. };
  73980. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  73981. // check name not already in use
  73982. if (!this._ranges[name]) {
  73983. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  73984. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  73985. if (this.bones[i].animations[0]) {
  73986. this.bones[i].animations[0].createRange(name, from, to);
  73987. }
  73988. }
  73989. }
  73990. };
  73991. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  73992. if (deleteFrames === void 0) { deleteFrames = true; }
  73993. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  73994. if (this.bones[i].animations[0]) {
  73995. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  73996. }
  73997. }
  73998. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  73999. };
  74000. Skeleton.prototype.getAnimationRange = function (name) {
  74001. return this._ranges[name];
  74002. };
  74003. /**
  74004. * Returns as an Array, all AnimationRanges defined on this skeleton
  74005. */
  74006. Skeleton.prototype.getAnimationRanges = function () {
  74007. var animationRanges = [];
  74008. var name;
  74009. var i = 0;
  74010. for (name in this._ranges) {
  74011. animationRanges[i] = this._ranges[name];
  74012. i++;
  74013. }
  74014. return animationRanges;
  74015. };
  74016. /**
  74017. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  74018. */
  74019. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  74020. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  74021. if (this._ranges[name] || !source.getAnimationRange(name)) {
  74022. return false;
  74023. }
  74024. var ret = true;
  74025. var frameOffset = this._getHighestAnimationFrame() + 1;
  74026. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  74027. var boneDict = {};
  74028. var sourceBones = source.bones;
  74029. var nBones;
  74030. var i;
  74031. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  74032. boneDict[sourceBones[i].name] = sourceBones[i];
  74033. }
  74034. if (this.bones.length !== sourceBones.length) {
  74035. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  74036. ret = false;
  74037. }
  74038. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  74039. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  74040. var boneName = this.bones[i].name;
  74041. var sourceBone = boneDict[boneName];
  74042. if (sourceBone) {
  74043. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  74044. }
  74045. else {
  74046. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  74047. ret = false;
  74048. }
  74049. }
  74050. // do not call createAnimationRange(), since it also is done to bones, which was already done
  74051. var range = source.getAnimationRange(name);
  74052. if (range) {
  74053. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  74054. }
  74055. return ret;
  74056. };
  74057. Skeleton.prototype.returnToRest = function () {
  74058. for (var index = 0; index < this.bones.length; index++) {
  74059. this.bones[index].returnToRest();
  74060. }
  74061. };
  74062. Skeleton.prototype._getHighestAnimationFrame = function () {
  74063. var ret = 0;
  74064. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  74065. if (this.bones[i].animations[0]) {
  74066. var highest = this.bones[i].animations[0].getHighestFrame();
  74067. if (ret < highest) {
  74068. ret = highest;
  74069. }
  74070. }
  74071. }
  74072. return ret;
  74073. };
  74074. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  74075. var range = this.getAnimationRange(name);
  74076. if (!range) {
  74077. return null;
  74078. }
  74079. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  74080. };
  74081. Skeleton.prototype._markAsDirty = function () {
  74082. this._isDirty = true;
  74083. };
  74084. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  74085. this._meshesWithPoseMatrix.push(mesh);
  74086. };
  74087. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  74088. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  74089. if (index > -1) {
  74090. this._meshesWithPoseMatrix.splice(index, 1);
  74091. }
  74092. };
  74093. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  74094. this.onBeforeComputeObservable.notifyObservers(this);
  74095. for (var index = 0; index < this.bones.length; index++) {
  74096. var bone = this.bones[index];
  74097. var parentBone = bone.getParent();
  74098. if (parentBone) {
  74099. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  74100. }
  74101. else {
  74102. if (initialSkinMatrix) {
  74103. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  74104. }
  74105. else {
  74106. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  74107. }
  74108. }
  74109. if (bone._index !== -1) {
  74110. var mappedIndex = bone._index === null ? index : bone._index;
  74111. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  74112. }
  74113. }
  74114. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  74115. };
  74116. Skeleton.prototype.prepare = function () {
  74117. if (!this._isDirty) {
  74118. return;
  74119. }
  74120. if (this.needInitialSkinMatrix) {
  74121. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  74122. var mesh = this._meshesWithPoseMatrix[index];
  74123. var poseMatrix = mesh.getPoseMatrix();
  74124. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  74125. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  74126. }
  74127. if (this._synchronizedWithMesh !== mesh) {
  74128. this._synchronizedWithMesh = mesh;
  74129. // Prepare bones
  74130. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  74131. var bone = this.bones[boneIndex];
  74132. if (!bone.getParent()) {
  74133. var matrix = bone.getBaseMatrix();
  74134. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  74135. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  74136. }
  74137. }
  74138. }
  74139. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  74140. }
  74141. }
  74142. else {
  74143. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  74144. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  74145. }
  74146. this._computeTransformMatrices(this._transformMatrices, null);
  74147. }
  74148. this._isDirty = false;
  74149. this._scene._activeBones.addCount(this.bones.length, false);
  74150. };
  74151. Skeleton.prototype.getAnimatables = function () {
  74152. if (!this._animatables || this._animatables.length !== this.bones.length) {
  74153. this._animatables = [];
  74154. for (var index = 0; index < this.bones.length; index++) {
  74155. this._animatables.push(this.bones[index]);
  74156. }
  74157. }
  74158. return this._animatables;
  74159. };
  74160. Skeleton.prototype.clone = function (name, id) {
  74161. var result = new Skeleton(name, id || name, this._scene);
  74162. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  74163. for (var index = 0; index < this.bones.length; index++) {
  74164. var source = this.bones[index];
  74165. var parentBone = null;
  74166. var parent_1 = source.getParent();
  74167. if (parent_1) {
  74168. var parentIndex = this.bones.indexOf(parent_1);
  74169. parentBone = result.bones[parentIndex];
  74170. }
  74171. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  74172. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  74173. }
  74174. if (this._ranges) {
  74175. result._ranges = {};
  74176. for (var rangeName in this._ranges) {
  74177. var range = this._ranges[rangeName];
  74178. if (range) {
  74179. result._ranges[rangeName] = range.clone();
  74180. }
  74181. }
  74182. }
  74183. this._isDirty = true;
  74184. return result;
  74185. };
  74186. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  74187. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  74188. this.bones.forEach(function (bone) {
  74189. bone.animations.forEach(function (animation) {
  74190. animation.enableBlending = true;
  74191. animation.blendingSpeed = blendingSpeed;
  74192. });
  74193. });
  74194. };
  74195. Skeleton.prototype.dispose = function () {
  74196. this._meshesWithPoseMatrix = [];
  74197. // Animations
  74198. this.getScene().stopAnimation(this);
  74199. // Remove from scene
  74200. this.getScene().removeSkeleton(this);
  74201. };
  74202. Skeleton.prototype.serialize = function () {
  74203. var serializationObject = {};
  74204. serializationObject.name = this.name;
  74205. serializationObject.id = this.id;
  74206. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  74207. serializationObject.bones = [];
  74208. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  74209. for (var index = 0; index < this.bones.length; index++) {
  74210. var bone = this.bones[index];
  74211. var parent_2 = bone.getParent();
  74212. var serializedBone = {
  74213. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  74214. name: bone.name,
  74215. matrix: bone.getBaseMatrix().toArray(),
  74216. rest: bone.getRestPose().toArray()
  74217. };
  74218. serializationObject.bones.push(serializedBone);
  74219. if (bone.length) {
  74220. serializedBone.length = bone.length;
  74221. }
  74222. if (bone.animations && bone.animations.length > 0) {
  74223. serializedBone.animation = bone.animations[0].serialize();
  74224. }
  74225. serializationObject.ranges = [];
  74226. for (var name in this._ranges) {
  74227. var source = this._ranges[name];
  74228. if (!source) {
  74229. continue;
  74230. }
  74231. var range = {};
  74232. range.name = name;
  74233. range.from = source.from;
  74234. range.to = source.to;
  74235. serializationObject.ranges.push(range);
  74236. }
  74237. }
  74238. return serializationObject;
  74239. };
  74240. Skeleton.Parse = function (parsedSkeleton, scene) {
  74241. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  74242. if (parsedSkeleton.dimensionsAtRest) {
  74243. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  74244. }
  74245. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  74246. var index;
  74247. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  74248. var parsedBone = parsedSkeleton.bones[index];
  74249. var parentBone = null;
  74250. if (parsedBone.parentBoneIndex > -1) {
  74251. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  74252. }
  74253. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  74254. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  74255. if (parsedBone.length) {
  74256. bone.length = parsedBone.length;
  74257. }
  74258. if (parsedBone.animation) {
  74259. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  74260. }
  74261. }
  74262. // placed after bones, so createAnimationRange can cascade down
  74263. if (parsedSkeleton.ranges) {
  74264. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  74265. var data = parsedSkeleton.ranges[index];
  74266. skeleton.createAnimationRange(data.name, data.from, data.to);
  74267. }
  74268. }
  74269. return skeleton;
  74270. };
  74271. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  74272. if (forceUpdate === void 0) { forceUpdate = false; }
  74273. var renderId = this._scene.getRenderId();
  74274. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  74275. this.bones[0].computeAbsoluteTransforms();
  74276. this._lastAbsoluteTransformsUpdateId = renderId;
  74277. }
  74278. };
  74279. Skeleton.prototype.getPoseMatrix = function () {
  74280. var poseMatrix = null;
  74281. if (this._meshesWithPoseMatrix.length > 0) {
  74282. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  74283. }
  74284. return poseMatrix;
  74285. };
  74286. Skeleton.prototype.sortBones = function () {
  74287. var bones = new Array();
  74288. var visited = new Array(this.bones.length);
  74289. for (var index = 0; index < this.bones.length; index++) {
  74290. this._sortBones(index, bones, visited);
  74291. }
  74292. this.bones = bones;
  74293. };
  74294. Skeleton.prototype._sortBones = function (index, bones, visited) {
  74295. if (visited[index]) {
  74296. return;
  74297. }
  74298. visited[index] = true;
  74299. var bone = this.bones[index];
  74300. if (bone._index === undefined) {
  74301. bone._index = index;
  74302. }
  74303. var parentBone = bone.getParent();
  74304. if (parentBone) {
  74305. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  74306. }
  74307. bones.push(bone);
  74308. };
  74309. return Skeleton;
  74310. }());
  74311. BABYLON.Skeleton = Skeleton;
  74312. })(BABYLON || (BABYLON = {}));
  74313. //# sourceMappingURL=babylon.skeleton.js.map
  74314. "use strict";
  74315. var BABYLON;
  74316. (function (BABYLON) {
  74317. var SphericalPolynomial = /** @class */ (function () {
  74318. function SphericalPolynomial() {
  74319. this.x = BABYLON.Vector3.Zero();
  74320. this.y = BABYLON.Vector3.Zero();
  74321. this.z = BABYLON.Vector3.Zero();
  74322. this.xx = BABYLON.Vector3.Zero();
  74323. this.yy = BABYLON.Vector3.Zero();
  74324. this.zz = BABYLON.Vector3.Zero();
  74325. this.xy = BABYLON.Vector3.Zero();
  74326. this.yz = BABYLON.Vector3.Zero();
  74327. this.zx = BABYLON.Vector3.Zero();
  74328. }
  74329. SphericalPolynomial.prototype.addAmbient = function (color) {
  74330. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  74331. this.xx = this.xx.add(colorVector);
  74332. this.yy = this.yy.add(colorVector);
  74333. this.zz = this.zz.add(colorVector);
  74334. };
  74335. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  74336. var result = new SphericalPolynomial();
  74337. result.x = harmonics.L11.scale(1.02333);
  74338. result.y = harmonics.L1_1.scale(1.02333);
  74339. result.z = harmonics.L10.scale(1.02333);
  74340. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  74341. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  74342. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  74343. result.yz = harmonics.L2_1.scale(0.858086);
  74344. result.zx = harmonics.L21.scale(0.858086);
  74345. result.xy = harmonics.L2_2.scale(0.858086);
  74346. result.scale(1.0 / Math.PI);
  74347. return result;
  74348. };
  74349. SphericalPolynomial.prototype.scale = function (scale) {
  74350. this.x = this.x.scale(scale);
  74351. this.y = this.y.scale(scale);
  74352. this.z = this.z.scale(scale);
  74353. this.xx = this.xx.scale(scale);
  74354. this.yy = this.yy.scale(scale);
  74355. this.zz = this.zz.scale(scale);
  74356. this.yz = this.yz.scale(scale);
  74357. this.zx = this.zx.scale(scale);
  74358. this.xy = this.xy.scale(scale);
  74359. };
  74360. return SphericalPolynomial;
  74361. }());
  74362. BABYLON.SphericalPolynomial = SphericalPolynomial;
  74363. var SphericalHarmonics = /** @class */ (function () {
  74364. function SphericalHarmonics() {
  74365. this.L00 = BABYLON.Vector3.Zero();
  74366. this.L1_1 = BABYLON.Vector3.Zero();
  74367. this.L10 = BABYLON.Vector3.Zero();
  74368. this.L11 = BABYLON.Vector3.Zero();
  74369. this.L2_2 = BABYLON.Vector3.Zero();
  74370. this.L2_1 = BABYLON.Vector3.Zero();
  74371. this.L20 = BABYLON.Vector3.Zero();
  74372. this.L21 = BABYLON.Vector3.Zero();
  74373. this.L22 = BABYLON.Vector3.Zero();
  74374. }
  74375. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  74376. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  74377. var c = colorVector.scale(deltaSolidAngle);
  74378. this.L00 = this.L00.add(c.scale(0.282095));
  74379. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  74380. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  74381. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  74382. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  74383. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  74384. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  74385. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  74386. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  74387. };
  74388. SphericalHarmonics.prototype.scale = function (scale) {
  74389. this.L00 = this.L00.scale(scale);
  74390. this.L1_1 = this.L1_1.scale(scale);
  74391. this.L10 = this.L10.scale(scale);
  74392. this.L11 = this.L11.scale(scale);
  74393. this.L2_2 = this.L2_2.scale(scale);
  74394. this.L2_1 = this.L2_1.scale(scale);
  74395. this.L20 = this.L20.scale(scale);
  74396. this.L21 = this.L21.scale(scale);
  74397. this.L22 = this.L22.scale(scale);
  74398. };
  74399. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  74400. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  74401. //
  74402. // E_lm = A_l * L_lm
  74403. //
  74404. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  74405. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  74406. // the scaling factors are given in equation 9.
  74407. // Constant (Band 0)
  74408. this.L00 = this.L00.scale(3.141593);
  74409. // Linear (Band 1)
  74410. this.L1_1 = this.L1_1.scale(2.094395);
  74411. this.L10 = this.L10.scale(2.094395);
  74412. this.L11 = this.L11.scale(2.094395);
  74413. // Quadratic (Band 2)
  74414. this.L2_2 = this.L2_2.scale(0.785398);
  74415. this.L2_1 = this.L2_1.scale(0.785398);
  74416. this.L20 = this.L20.scale(0.785398);
  74417. this.L21 = this.L21.scale(0.785398);
  74418. this.L22 = this.L22.scale(0.785398);
  74419. };
  74420. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  74421. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  74422. // L = (1/pi) * E * rho
  74423. //
  74424. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  74425. this.scale(1.0 / Math.PI);
  74426. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  74427. // (The pixel shader must apply albedo after texture fetches, etc).
  74428. };
  74429. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  74430. var result = new SphericalHarmonics();
  74431. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  74432. result.L1_1 = polynomial.y.scale(0.977204);
  74433. result.L10 = polynomial.z.scale(0.977204);
  74434. result.L11 = polynomial.x.scale(0.977204);
  74435. result.L2_2 = polynomial.xy.scale(1.16538);
  74436. result.L2_1 = polynomial.yz.scale(1.16538);
  74437. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  74438. result.L21 = polynomial.zx.scale(1.16538);
  74439. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  74440. result.scale(Math.PI);
  74441. return result;
  74442. };
  74443. return SphericalHarmonics;
  74444. }());
  74445. BABYLON.SphericalHarmonics = SphericalHarmonics;
  74446. })(BABYLON || (BABYLON = {}));
  74447. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  74448. "use strict";
  74449. var BABYLON;
  74450. (function (BABYLON) {
  74451. var FileFaceOrientation = /** @class */ (function () {
  74452. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  74453. this.name = name;
  74454. this.worldAxisForNormal = worldAxisForNormal;
  74455. this.worldAxisForFileX = worldAxisForFileX;
  74456. this.worldAxisForFileY = worldAxisForFileY;
  74457. }
  74458. return FileFaceOrientation;
  74459. }());
  74460. ;
  74461. /**
  74462. * Helper class dealing with the extraction of spherical polynomial dataArray
  74463. * from a cube map.
  74464. */
  74465. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  74466. function CubeMapToSphericalPolynomialTools() {
  74467. }
  74468. /**
  74469. * Converts a texture to the according Spherical Polynomial data.
  74470. * This extracts the first 3 orders only as they are the only one used in the lighting.
  74471. *
  74472. * @param texture The texture to extract the information from.
  74473. * @return The Spherical Polynomial data.
  74474. */
  74475. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  74476. if (!texture.isCube) {
  74477. // Only supports cube Textures currently.
  74478. return null;
  74479. }
  74480. var size = texture.getSize().width;
  74481. var right = texture.readPixels(0);
  74482. var left = texture.readPixels(1);
  74483. var up;
  74484. var down;
  74485. if (texture.isRenderTarget) {
  74486. up = texture.readPixels(3);
  74487. down = texture.readPixels(2);
  74488. }
  74489. else {
  74490. up = texture.readPixels(2);
  74491. down = texture.readPixels(3);
  74492. }
  74493. var front = texture.readPixels(4);
  74494. var back = texture.readPixels(5);
  74495. var gammaSpace = texture.gammaSpace;
  74496. // Always read as RGBA.
  74497. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  74498. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  74499. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  74500. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  74501. }
  74502. var cubeInfo = {
  74503. size: size,
  74504. right: right,
  74505. left: left,
  74506. up: up,
  74507. down: down,
  74508. front: front,
  74509. back: back,
  74510. format: format,
  74511. type: type,
  74512. gammaSpace: gammaSpace,
  74513. };
  74514. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  74515. };
  74516. /**
  74517. * Converts a cubemap to the according Spherical Polynomial data.
  74518. * This extracts the first 3 orders only as they are the only one used in the lighting.
  74519. *
  74520. * @param cubeInfo The Cube map to extract the information from.
  74521. * @return The Spherical Polynomial data.
  74522. */
  74523. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  74524. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  74525. var totalSolidAngle = 0.0;
  74526. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  74527. var du = 2.0 / cubeInfo.size;
  74528. var dv = du;
  74529. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  74530. var minUV = du * 0.5 - 1.0;
  74531. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  74532. var fileFace = this.FileFaces[faceIndex];
  74533. var dataArray = cubeInfo[fileFace.name];
  74534. var v = minUV;
  74535. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  74536. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  74537. // Because SP is still linear, so summation is fine in that basis.
  74538. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  74539. for (var y = 0; y < cubeInfo.size; y++) {
  74540. var u = minUV;
  74541. for (var x = 0; x < cubeInfo.size; x++) {
  74542. // World direction (not normalised)
  74543. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  74544. worldDirection.normalize();
  74545. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  74546. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  74547. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  74548. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  74549. // Handle Integer types.
  74550. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  74551. r /= 255;
  74552. g /= 255;
  74553. b /= 255;
  74554. }
  74555. // Handle Gamma space textures.
  74556. if (cubeInfo.gammaSpace) {
  74557. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  74558. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  74559. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  74560. }
  74561. var color = new BABYLON.Color3(r, g, b);
  74562. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  74563. totalSolidAngle += deltaSolidAngle;
  74564. u += du;
  74565. }
  74566. v += dv;
  74567. }
  74568. }
  74569. // Solid angle for entire sphere is 4*pi
  74570. var sphereSolidAngle = 4.0 * Math.PI;
  74571. // Adjust the solid angle to allow for how many faces we processed.
  74572. var facesProcessed = 6.0;
  74573. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  74574. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  74575. // This is needed because the numerical integration over the cube uses a
  74576. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  74577. // and also to compensate for accumulative error due to float precision in the summation.
  74578. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  74579. sphericalHarmonics.scale(correctionFactor);
  74580. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  74581. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  74582. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  74583. };
  74584. CubeMapToSphericalPolynomialTools.FileFaces = [
  74585. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  74586. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  74587. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  74588. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  74589. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  74590. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  74591. ];
  74592. return CubeMapToSphericalPolynomialTools;
  74593. }());
  74594. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  74595. })(BABYLON || (BABYLON = {}));
  74596. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  74597. "use strict";
  74598. var BABYLON;
  74599. (function (BABYLON) {
  74600. /**
  74601. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  74602. */
  74603. var PanoramaToCubeMapTools = /** @class */ (function () {
  74604. function PanoramaToCubeMapTools() {
  74605. }
  74606. /**
  74607. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  74608. *
  74609. * @param float32Array The source data.
  74610. * @param inputWidth The width of the input panorama.
  74611. * @param inputhHeight The height of the input panorama.
  74612. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  74613. * @return The cubemap data
  74614. */
  74615. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  74616. if (!float32Array) {
  74617. throw "ConvertPanoramaToCubemap: input cannot be null";
  74618. }
  74619. if (float32Array.length != inputWidth * inputHeight * 3) {
  74620. throw "ConvertPanoramaToCubemap: input size is wrong";
  74621. }
  74622. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  74623. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  74624. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  74625. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  74626. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  74627. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  74628. return {
  74629. front: textureFront,
  74630. back: textureBack,
  74631. left: textureLeft,
  74632. right: textureRight,
  74633. up: textureUp,
  74634. down: textureDown,
  74635. size: size,
  74636. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  74637. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  74638. gammaSpace: false,
  74639. };
  74640. };
  74641. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  74642. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  74643. var textureArray = new Float32Array(buffer);
  74644. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  74645. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  74646. var dy = 1 / texSize;
  74647. var fy = 0;
  74648. for (var y = 0; y < texSize; y++) {
  74649. var xv1 = faceData[0];
  74650. var xv2 = faceData[2];
  74651. for (var x = 0; x < texSize; x++) {
  74652. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  74653. v.normalize();
  74654. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  74655. // 3 channels per pixels
  74656. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  74657. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  74658. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  74659. xv1 = xv1.add(rotDX1);
  74660. xv2 = xv2.add(rotDX2);
  74661. }
  74662. fy += dy;
  74663. }
  74664. return textureArray;
  74665. };
  74666. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  74667. var theta = Math.atan2(vDir.z, vDir.x);
  74668. var phi = Math.acos(vDir.y);
  74669. while (theta < -Math.PI)
  74670. theta += 2 * Math.PI;
  74671. while (theta > Math.PI)
  74672. theta -= 2 * Math.PI;
  74673. var dx = theta / Math.PI;
  74674. var dy = phi / Math.PI;
  74675. // recenter.
  74676. dx = dx * 0.5 + 0.5;
  74677. var px = Math.round(dx * inputWidth);
  74678. if (px < 0)
  74679. px = 0;
  74680. else if (px >= inputWidth)
  74681. px = inputWidth - 1;
  74682. var py = Math.round(dy * inputHeight);
  74683. if (py < 0)
  74684. py = 0;
  74685. else if (py >= inputHeight)
  74686. py = inputHeight - 1;
  74687. var inputY = (inputHeight - py - 1);
  74688. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  74689. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  74690. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  74691. return {
  74692. r: r,
  74693. g: g,
  74694. b: b
  74695. };
  74696. };
  74697. PanoramaToCubeMapTools.FACE_FRONT = [
  74698. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  74699. new BABYLON.Vector3(1.0, -1.0, -1.0),
  74700. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  74701. new BABYLON.Vector3(1.0, 1.0, -1.0)
  74702. ];
  74703. PanoramaToCubeMapTools.FACE_BACK = [
  74704. new BABYLON.Vector3(1.0, -1.0, 1.0),
  74705. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  74706. new BABYLON.Vector3(1.0, 1.0, 1.0),
  74707. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  74708. ];
  74709. PanoramaToCubeMapTools.FACE_RIGHT = [
  74710. new BABYLON.Vector3(1.0, -1.0, -1.0),
  74711. new BABYLON.Vector3(1.0, -1.0, 1.0),
  74712. new BABYLON.Vector3(1.0, 1.0, -1.0),
  74713. new BABYLON.Vector3(1.0, 1.0, 1.0)
  74714. ];
  74715. PanoramaToCubeMapTools.FACE_LEFT = [
  74716. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  74717. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  74718. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  74719. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  74720. ];
  74721. PanoramaToCubeMapTools.FACE_DOWN = [
  74722. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  74723. new BABYLON.Vector3(1.0, 1.0, -1.0),
  74724. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  74725. new BABYLON.Vector3(1.0, 1.0, 1.0)
  74726. ];
  74727. PanoramaToCubeMapTools.FACE_UP = [
  74728. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  74729. new BABYLON.Vector3(1.0, -1.0, 1.0),
  74730. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  74731. new BABYLON.Vector3(1.0, -1.0, -1.0)
  74732. ];
  74733. return PanoramaToCubeMapTools;
  74734. }());
  74735. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  74736. })(BABYLON || (BABYLON = {}));
  74737. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  74738. "use strict";
  74739. var BABYLON;
  74740. (function (BABYLON) {
  74741. ;
  74742. /**
  74743. * This groups tools to convert HDR texture to native colors array.
  74744. */
  74745. var HDRTools = /** @class */ (function () {
  74746. function HDRTools() {
  74747. }
  74748. HDRTools.Ldexp = function (mantissa, exponent) {
  74749. if (exponent > 1023) {
  74750. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  74751. }
  74752. if (exponent < -1074) {
  74753. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  74754. }
  74755. return mantissa * Math.pow(2, exponent);
  74756. };
  74757. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  74758. if (exponent > 0) {
  74759. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  74760. float32array[index + 0] = red * exponent;
  74761. float32array[index + 1] = green * exponent;
  74762. float32array[index + 2] = blue * exponent;
  74763. }
  74764. else {
  74765. float32array[index + 0] = 0;
  74766. float32array[index + 1] = 0;
  74767. float32array[index + 2] = 0;
  74768. }
  74769. };
  74770. HDRTools.readStringLine = function (uint8array, startIndex) {
  74771. var line = "";
  74772. var character = "";
  74773. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  74774. character = String.fromCharCode(uint8array[i]);
  74775. if (character == "\n") {
  74776. break;
  74777. }
  74778. line += character;
  74779. }
  74780. return line;
  74781. };
  74782. /**
  74783. * Reads header information from an RGBE texture stored in a native array.
  74784. * More information on this format are available here:
  74785. * https://en.wikipedia.org/wiki/RGBE_image_format
  74786. *
  74787. * @param uint8array The binary file stored in native array.
  74788. * @return The header information.
  74789. */
  74790. HDRTools.RGBE_ReadHeader = function (uint8array) {
  74791. var height = 0;
  74792. var width = 0;
  74793. var line = this.readStringLine(uint8array, 0);
  74794. if (line[0] != '#' || line[1] != '?') {
  74795. throw "Bad HDR Format.";
  74796. }
  74797. var endOfHeader = false;
  74798. var findFormat = false;
  74799. var lineIndex = 0;
  74800. do {
  74801. lineIndex += (line.length + 1);
  74802. line = this.readStringLine(uint8array, lineIndex);
  74803. if (line == "FORMAT=32-bit_rle_rgbe") {
  74804. findFormat = true;
  74805. }
  74806. else if (line.length == 0) {
  74807. endOfHeader = true;
  74808. }
  74809. } while (!endOfHeader);
  74810. if (!findFormat) {
  74811. throw "HDR Bad header format, unsupported FORMAT";
  74812. }
  74813. lineIndex += (line.length + 1);
  74814. line = this.readStringLine(uint8array, lineIndex);
  74815. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  74816. var match = sizeRegexp.exec(line);
  74817. // TODO. Support +Y and -X if needed.
  74818. if (!match || match.length < 3) {
  74819. throw "HDR Bad header format, no size";
  74820. }
  74821. width = parseInt(match[2]);
  74822. height = parseInt(match[1]);
  74823. if (width < 8 || width > 0x7fff) {
  74824. throw "HDR Bad header format, unsupported size";
  74825. }
  74826. lineIndex += (line.length + 1);
  74827. return {
  74828. height: height,
  74829. width: width,
  74830. dataPosition: lineIndex
  74831. };
  74832. };
  74833. /**
  74834. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  74835. * This RGBE texture needs to store the information as a panorama.
  74836. *
  74837. * More information on this format are available here:
  74838. * https://en.wikipedia.org/wiki/RGBE_image_format
  74839. *
  74840. * @param buffer The binary file stored in an array buffer.
  74841. * @param size The expected size of the extracted cubemap.
  74842. * @return The Cube Map information.
  74843. */
  74844. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  74845. var uint8array = new Uint8Array(buffer);
  74846. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  74847. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  74848. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  74849. return cubeMapData;
  74850. };
  74851. /**
  74852. * Returns the pixels data extracted from an RGBE texture.
  74853. * This pixels will be stored left to right up to down in the R G B order in one array.
  74854. *
  74855. * More information on this format are available here:
  74856. * https://en.wikipedia.org/wiki/RGBE_image_format
  74857. *
  74858. * @param uint8array The binary file stored in an array buffer.
  74859. * @param hdrInfo The header information of the file.
  74860. * @return The pixels data in RGB right to left up to down order.
  74861. */
  74862. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  74863. // Keep for multi format supports.
  74864. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  74865. };
  74866. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  74867. var num_scanlines = hdrInfo.height;
  74868. var scanline_width = hdrInfo.width;
  74869. var a, b, c, d, count;
  74870. var dataIndex = hdrInfo.dataPosition;
  74871. var index = 0, endIndex = 0, i = 0;
  74872. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  74873. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  74874. // 3 channels of 4 bytes per pixel in float.
  74875. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  74876. var resultArray = new Float32Array(resultBuffer);
  74877. // read in each successive scanline
  74878. while (num_scanlines > 0) {
  74879. a = uint8array[dataIndex++];
  74880. b = uint8array[dataIndex++];
  74881. c = uint8array[dataIndex++];
  74882. d = uint8array[dataIndex++];
  74883. if (a != 2 || b != 2 || (c & 0x80)) {
  74884. // this file is not run length encoded
  74885. throw "HDR Bad header format, not RLE";
  74886. }
  74887. if (((c << 8) | d) != scanline_width) {
  74888. throw "HDR Bad header format, wrong scan line width";
  74889. }
  74890. index = 0;
  74891. // read each of the four channels for the scanline into the buffer
  74892. for (i = 0; i < 4; i++) {
  74893. endIndex = (i + 1) * scanline_width;
  74894. while (index < endIndex) {
  74895. a = uint8array[dataIndex++];
  74896. b = uint8array[dataIndex++];
  74897. if (a > 128) {
  74898. // a run of the same value
  74899. count = a - 128;
  74900. if ((count == 0) || (count > endIndex - index)) {
  74901. throw "HDR Bad Format, bad scanline data (run)";
  74902. }
  74903. while (count-- > 0) {
  74904. scanLineArray[index++] = b;
  74905. }
  74906. }
  74907. else {
  74908. // a non-run
  74909. count = a;
  74910. if ((count == 0) || (count > endIndex - index)) {
  74911. throw "HDR Bad Format, bad scanline data (non-run)";
  74912. }
  74913. scanLineArray[index++] = b;
  74914. if (--count > 0) {
  74915. for (var j = 0; j < count; j++) {
  74916. scanLineArray[index++] = uint8array[dataIndex++];
  74917. }
  74918. }
  74919. }
  74920. }
  74921. }
  74922. // now convert data from buffer into floats
  74923. for (i = 0; i < scanline_width; i++) {
  74924. a = scanLineArray[i];
  74925. b = scanLineArray[i + scanline_width];
  74926. c = scanLineArray[i + 2 * scanline_width];
  74927. d = scanLineArray[i + 3 * scanline_width];
  74928. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  74929. }
  74930. num_scanlines--;
  74931. }
  74932. return resultArray;
  74933. };
  74934. return HDRTools;
  74935. }());
  74936. BABYLON.HDRTools = HDRTools;
  74937. })(BABYLON || (BABYLON = {}));
  74938. //# sourceMappingURL=babylon.hdr.js.map
  74939. "use strict";
  74940. var BABYLON;
  74941. (function (BABYLON) {
  74942. /**
  74943. * This represents a texture coming from an HDR input.
  74944. *
  74945. * The only supported format is currently panorama picture stored in RGBE format.
  74946. * Example of such files can be found on HDRLib: http://hdrlib.com/
  74947. */
  74948. var HDRCubeTexture = /** @class */ (function (_super) {
  74949. __extends(HDRCubeTexture, _super);
  74950. /**
  74951. * Instantiates an HDRTexture from the following parameters.
  74952. *
  74953. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  74954. * @param scene The scene the texture will be used in
  74955. * @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.
  74956. * @param noMipmap Forces to not generate the mipmap if true
  74957. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  74958. * @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)
  74959. * @param usePMREMGenerator Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  74960. */
  74961. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  74962. if (noMipmap === void 0) { noMipmap = false; }
  74963. if (generateHarmonics === void 0) { generateHarmonics = true; }
  74964. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  74965. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  74966. if (onLoad === void 0) { onLoad = null; }
  74967. if (onError === void 0) { onError = null; }
  74968. var _this = _super.call(this, scene) || this;
  74969. _this._useInGammaSpace = false;
  74970. _this._generateHarmonics = true;
  74971. _this._isBABYLONPreprocessed = false;
  74972. _this._onLoad = null;
  74973. _this._onError = null;
  74974. /**
  74975. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  74976. */
  74977. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  74978. /**
  74979. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  74980. * This is usefull at run time to apply the good shader.
  74981. */
  74982. _this.isPMREM = false;
  74983. _this._isBlocking = true;
  74984. /**
  74985. * Gets or sets the center of the bounding box associated with the cube texture
  74986. * It must define where the camera used to render the texture was set
  74987. */
  74988. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  74989. if (!url) {
  74990. return _this;
  74991. }
  74992. _this.name = url;
  74993. _this.url = url;
  74994. _this.hasAlpha = false;
  74995. _this.isCube = true;
  74996. _this._textureMatrix = BABYLON.Matrix.Identity();
  74997. _this._onLoad = onLoad;
  74998. _this._onError = onError;
  74999. _this.gammaSpace = false;
  75000. var caps = scene.getEngine().getCaps();
  75001. if (size) {
  75002. _this._isBABYLONPreprocessed = false;
  75003. _this._noMipmap = noMipmap;
  75004. _this._size = size;
  75005. _this._useInGammaSpace = useInGammaSpace;
  75006. _this._usePMREMGenerator = usePMREMGenerator &&
  75007. caps.textureLOD &&
  75008. caps.textureFloat &&
  75009. !_this._useInGammaSpace;
  75010. }
  75011. else {
  75012. _this._isBABYLONPreprocessed = true;
  75013. _this._noMipmap = false;
  75014. _this._useInGammaSpace = false;
  75015. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  75016. !_this._useInGammaSpace;
  75017. }
  75018. _this.isPMREM = _this._usePMREMGenerator;
  75019. _this._texture = _this._getFromCache(url, _this._noMipmap);
  75020. if (!_this._texture) {
  75021. if (!scene.useDelayedTextureLoading) {
  75022. _this.loadTexture();
  75023. }
  75024. else {
  75025. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  75026. }
  75027. }
  75028. return _this;
  75029. }
  75030. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  75031. /**
  75032. * Gets wether or not the texture is blocking during loading.
  75033. */
  75034. get: function () {
  75035. return this._isBlocking;
  75036. },
  75037. /**
  75038. * Sets wether or not the texture is blocking during loading.
  75039. */
  75040. set: function (value) {
  75041. this._isBlocking = value;
  75042. },
  75043. enumerable: true,
  75044. configurable: true
  75045. });
  75046. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  75047. get: function () {
  75048. return this._boundingBoxSize;
  75049. },
  75050. /**
  75051. * Gets or sets the size of the bounding box associated with the cube texture
  75052. * When defined, the cubemap will switch to local mode
  75053. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  75054. * @example https://www.babylonjs-playground.com/#RNASML
  75055. */
  75056. set: function (value) {
  75057. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  75058. return;
  75059. }
  75060. this._boundingBoxSize = value;
  75061. var scene = this.getScene();
  75062. if (scene) {
  75063. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  75064. }
  75065. },
  75066. enumerable: true,
  75067. configurable: true
  75068. });
  75069. /**
  75070. * Occurs when the file is a preprocessed .babylon.hdr file.
  75071. */
  75072. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  75073. var _this = this;
  75074. var mipLevels = 0;
  75075. var floatArrayView = null;
  75076. var scene = this.getScene();
  75077. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  75078. var mips = new Array();
  75079. if (!floatArrayView) {
  75080. return mips;
  75081. }
  75082. var startIndex = 30;
  75083. for (var level = 0; level < mipLevels; level++) {
  75084. mips.push([]);
  75085. // Fill each pixel of the mip level.
  75086. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  75087. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  75088. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  75089. mips[level].push(faceData);
  75090. startIndex += faceSize;
  75091. }
  75092. }
  75093. return mips;
  75094. } : null;
  75095. var callback = function (buffer) {
  75096. var scene = _this.getScene();
  75097. if (!scene) {
  75098. return null;
  75099. }
  75100. // Create Native Array Views
  75101. var intArrayView = new Int32Array(buffer);
  75102. floatArrayView = new Float32Array(buffer);
  75103. // Fill header.
  75104. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  75105. _this._size = intArrayView[1]; // CubeMap max mip face size.
  75106. // Update Texture Information.
  75107. if (!_this._texture) {
  75108. return null;
  75109. }
  75110. _this._texture.updateSize(_this._size, _this._size);
  75111. // Fill polynomial information.
  75112. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  75113. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  75114. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  75115. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  75116. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  75117. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  75118. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  75119. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  75120. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  75121. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  75122. _this.sphericalPolynomial = sphericalPolynomial;
  75123. // Fill pixel data.
  75124. mipLevels = intArrayView[29]; // Number of mip levels.
  75125. var startIndex = 30;
  75126. var data = [];
  75127. var faceSize = Math.pow(_this._size, 2) * 3;
  75128. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  75129. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  75130. startIndex += faceSize;
  75131. }
  75132. var results = [];
  75133. var byteArray = null;
  75134. // Push each faces.
  75135. for (var k = 0; k < 6; k++) {
  75136. var dataFace = null;
  75137. // To be deprecated.
  75138. if (version === 1) {
  75139. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  75140. dataFace = data[j];
  75141. }
  75142. // If special cases.
  75143. if (!mipmapGenerator && dataFace) {
  75144. if (!scene.getEngine().getCaps().textureFloat) {
  75145. // 3 channels of 1 bytes per pixel in bytes.
  75146. var byteBuffer = new ArrayBuffer(faceSize);
  75147. byteArray = new Uint8Array(byteBuffer);
  75148. }
  75149. for (var i = 0; i < _this._size * _this._size; i++) {
  75150. // Put in gamma space if requested.
  75151. if (_this._useInGammaSpace) {
  75152. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  75153. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  75154. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  75155. }
  75156. // Convert to int texture for fallback.
  75157. if (byteArray) {
  75158. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  75159. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  75160. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  75161. // May use luminance instead if the result is not accurate.
  75162. var max = Math.max(Math.max(r, g), b);
  75163. if (max > 255) {
  75164. var scale = 255 / max;
  75165. r *= scale;
  75166. g *= scale;
  75167. b *= scale;
  75168. }
  75169. byteArray[(i * 3) + 0] = r;
  75170. byteArray[(i * 3) + 1] = g;
  75171. byteArray[(i * 3) + 2] = b;
  75172. }
  75173. }
  75174. }
  75175. // Fill the array accordingly.
  75176. if (byteArray) {
  75177. results.push(byteArray);
  75178. }
  75179. else {
  75180. results.push(dataFace);
  75181. }
  75182. }
  75183. return results;
  75184. };
  75185. if (scene) {
  75186. 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);
  75187. }
  75188. };
  75189. /**
  75190. * Occurs when the file is raw .hdr file.
  75191. */
  75192. HDRCubeTexture.prototype.loadHDRTexture = function () {
  75193. var _this = this;
  75194. var callback = function (buffer) {
  75195. var scene = _this.getScene();
  75196. if (!scene) {
  75197. return null;
  75198. }
  75199. // Extract the raw linear data.
  75200. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  75201. // Generate harmonics if needed.
  75202. if (_this._generateHarmonics) {
  75203. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  75204. _this.sphericalPolynomial = sphericalPolynomial;
  75205. }
  75206. var results = [];
  75207. var byteArray = null;
  75208. // Push each faces.
  75209. for (var j = 0; j < 6; j++) {
  75210. // Create uintarray fallback.
  75211. if (!scene.getEngine().getCaps().textureFloat) {
  75212. // 3 channels of 1 bytes per pixel in bytes.
  75213. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  75214. byteArray = new Uint8Array(byteBuffer);
  75215. }
  75216. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  75217. // If special cases.
  75218. if (_this._useInGammaSpace || byteArray) {
  75219. for (var i = 0; i < _this._size * _this._size; i++) {
  75220. // Put in gamma space if requested.
  75221. if (_this._useInGammaSpace) {
  75222. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  75223. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  75224. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  75225. }
  75226. // Convert to int texture for fallback.
  75227. if (byteArray) {
  75228. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  75229. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  75230. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  75231. // May use luminance instead if the result is not accurate.
  75232. var max = Math.max(Math.max(r, g), b);
  75233. if (max > 255) {
  75234. var scale = 255 / max;
  75235. r *= scale;
  75236. g *= scale;
  75237. b *= scale;
  75238. }
  75239. byteArray[(i * 3) + 0] = r;
  75240. byteArray[(i * 3) + 1] = g;
  75241. byteArray[(i * 3) + 2] = b;
  75242. }
  75243. }
  75244. }
  75245. if (byteArray) {
  75246. results.push(byteArray);
  75247. }
  75248. else {
  75249. results.push(dataFace);
  75250. }
  75251. }
  75252. return results;
  75253. };
  75254. var mipmapGenerator = null;
  75255. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  75256. // if (!this._noMipmap &&
  75257. // this._usePMREMGenerator) {
  75258. // mipmapGenerator = (data: ArrayBufferView[]) => {
  75259. // // Custom setup of the generator matching with the PBR shader values.
  75260. // var generator = new BABYLON.PMREMGenerator(data,
  75261. // this._size,
  75262. // this._size,
  75263. // 0,
  75264. // 3,
  75265. // this.getScene().getEngine().getCaps().textureFloat,
  75266. // 2048,
  75267. // 0.25,
  75268. // false,
  75269. // true);
  75270. // return generator.filterCubeMap();
  75271. // };
  75272. // }
  75273. var scene = this.getScene();
  75274. if (scene) {
  75275. 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);
  75276. }
  75277. };
  75278. /**
  75279. * Starts the loading process of the texture.
  75280. */
  75281. HDRCubeTexture.prototype.loadTexture = function () {
  75282. if (this._isBABYLONPreprocessed) {
  75283. this.loadBabylonTexture();
  75284. }
  75285. else {
  75286. this.loadHDRTexture();
  75287. }
  75288. };
  75289. HDRCubeTexture.prototype.clone = function () {
  75290. var scene = this.getScene();
  75291. if (!scene) {
  75292. return this;
  75293. }
  75294. var size = (this._isBABYLONPreprocessed ? null : this._size);
  75295. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  75296. // Base texture
  75297. newTexture.level = this.level;
  75298. newTexture.wrapU = this.wrapU;
  75299. newTexture.wrapV = this.wrapV;
  75300. newTexture.coordinatesIndex = this.coordinatesIndex;
  75301. newTexture.coordinatesMode = this.coordinatesMode;
  75302. return newTexture;
  75303. };
  75304. // Methods
  75305. HDRCubeTexture.prototype.delayLoad = function () {
  75306. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  75307. return;
  75308. }
  75309. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  75310. this._texture = this._getFromCache(this.url, this._noMipmap);
  75311. if (!this._texture) {
  75312. this.loadTexture();
  75313. }
  75314. };
  75315. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  75316. return this._textureMatrix;
  75317. };
  75318. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  75319. this._textureMatrix = value;
  75320. };
  75321. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  75322. var texture = null;
  75323. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  75324. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  75325. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  75326. texture.name = parsedTexture.name;
  75327. texture.hasAlpha = parsedTexture.hasAlpha;
  75328. texture.level = parsedTexture.level;
  75329. texture.coordinatesMode = parsedTexture.coordinatesMode;
  75330. texture.isBlocking = parsedTexture.isBlocking;
  75331. }
  75332. if (texture) {
  75333. if (parsedTexture.boundingBoxPosition) {
  75334. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  75335. }
  75336. if (parsedTexture.boundingBoxSize) {
  75337. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  75338. }
  75339. }
  75340. return texture;
  75341. };
  75342. HDRCubeTexture.prototype.serialize = function () {
  75343. if (!this.name) {
  75344. return null;
  75345. }
  75346. var serializationObject = {};
  75347. serializationObject.name = this.name;
  75348. serializationObject.hasAlpha = this.hasAlpha;
  75349. serializationObject.isCube = true;
  75350. serializationObject.level = this.level;
  75351. serializationObject.size = this._size;
  75352. serializationObject.coordinatesMode = this.coordinatesMode;
  75353. serializationObject.useInGammaSpace = this._useInGammaSpace;
  75354. serializationObject.generateHarmonics = this._generateHarmonics;
  75355. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  75356. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  75357. serializationObject.customType = "BABYLON.HDRCubeTexture";
  75358. serializationObject.noMipmap = this._noMipmap;
  75359. serializationObject.isBlocking = this._isBlocking;
  75360. return serializationObject;
  75361. };
  75362. /**
  75363. * Saves as a file the data contained in the texture in a binary format.
  75364. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  75365. * as the spherical used in the lighting.
  75366. * @param url The HDR file url.
  75367. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  75368. * @param onError Method called if any error happens during download.
  75369. * @return The packed binary data.
  75370. */
  75371. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  75372. if (onError === void 0) { onError = null; }
  75373. var callback = function (buffer) {
  75374. var data = new Blob([buffer], { type: 'application/octet-stream' });
  75375. // Returns a URL you can use as a href.
  75376. var objUrl = window.URL.createObjectURL(data);
  75377. // Simulates a link to it and click to dowload.
  75378. var a = document.createElement("a");
  75379. document.body.appendChild(a);
  75380. a.style.display = "none";
  75381. a.href = objUrl;
  75382. a.download = "envmap.babylon.hdr";
  75383. a.click();
  75384. };
  75385. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  75386. };
  75387. /**
  75388. * Serializes the data contained in the texture in a binary format.
  75389. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  75390. * as the spherical used in the lighting.
  75391. * @param url The HDR file url.
  75392. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  75393. * @param onError Method called if any error happens during download.
  75394. * @return The packed binary data.
  75395. */
  75396. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  75397. if (onError === void 0) { onError = null; }
  75398. // Needs the url tho create the texture.
  75399. if (!url) {
  75400. return;
  75401. }
  75402. // Check Power of two size.
  75403. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  75404. return;
  75405. }
  75406. // Coming Back in 3.x.
  75407. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  75408. };
  75409. HDRCubeTexture._facesMapping = [
  75410. "right",
  75411. "left",
  75412. "up",
  75413. "down",
  75414. "front",
  75415. "back"
  75416. ];
  75417. return HDRCubeTexture;
  75418. }(BABYLON.BaseTexture));
  75419. BABYLON.HDRCubeTexture = HDRCubeTexture;
  75420. })(BABYLON || (BABYLON = {}));
  75421. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  75422. "use strict";
  75423. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  75424. // Huge respect for a such great lib.
  75425. // Earcut license:
  75426. // Copyright (c) 2016, Mapbox
  75427. //
  75428. // Permission to use, copy, modify, and/or distribute this software for any purpose
  75429. // with or without fee is hereby granted, provided that the above copyright notice
  75430. // and this permission notice appear in all copies.
  75431. //
  75432. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  75433. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  75434. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  75435. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  75436. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  75437. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  75438. // THIS SOFTWARE.
  75439. var Earcut;
  75440. (function (Earcut) {
  75441. /**
  75442. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  75443. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  75444. * @param holeIndices is an array of hole indices if any (e.g. [5, 8] for a 12- vertice input would mean one hole with vertices 5–7 and another with 8–11).
  75445. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  75446. */
  75447. function earcut(data, holeIndices, dim) {
  75448. dim = dim || 2;
  75449. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  75450. if (!outerNode)
  75451. return triangles;
  75452. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  75453. if (hasHoles)
  75454. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  75455. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  75456. if (data.length > 80 * dim) {
  75457. minX = maxX = data[0];
  75458. minY = maxY = data[1];
  75459. for (var i = dim; i < outerLen; i += dim) {
  75460. x = data[i];
  75461. y = data[i + 1];
  75462. if (x < minX)
  75463. minX = x;
  75464. if (y < minY)
  75465. minY = y;
  75466. if (x > maxX)
  75467. maxX = x;
  75468. if (y > maxY)
  75469. maxY = y;
  75470. }
  75471. // minX, minY and size are later used to transform coords into integers for z-order calculation
  75472. size = Math.max(maxX - minX, maxY - minY);
  75473. }
  75474. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  75475. return triangles;
  75476. }
  75477. Earcut.earcut = earcut;
  75478. var Node = /** @class */ (function () {
  75479. function Node(i, x, y) {
  75480. this.i = i;
  75481. this.x = x;
  75482. this.y = y;
  75483. this.prev = null;
  75484. this.next = null;
  75485. this.z = null;
  75486. this.prevZ = null;
  75487. this.nextZ = null;
  75488. this.steiner = false;
  75489. }
  75490. return Node;
  75491. }());
  75492. // create a circular doubly linked list from polygon points in the specified winding order
  75493. function linkedList(data, start, end, dim, clockwise) {
  75494. var i, last = null;
  75495. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  75496. for (i = start; i < end; i += dim)
  75497. last = insertNode(i, data[i], data[i + 1], last);
  75498. }
  75499. else {
  75500. for (i = end - dim; i >= start; i -= dim)
  75501. last = insertNode(i, data[i], data[i + 1], last);
  75502. }
  75503. if (last && equals(last, last.next)) {
  75504. removeNode(last);
  75505. last = last.next;
  75506. }
  75507. return last;
  75508. }
  75509. // eliminate colinear or duplicate points
  75510. function filterPoints(start, end) {
  75511. if (!start)
  75512. return start;
  75513. if (!end)
  75514. end = start;
  75515. var p = start, again;
  75516. do {
  75517. again = false;
  75518. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  75519. removeNode(p);
  75520. p = end = p.prev;
  75521. if (p === p.next)
  75522. return undefined;
  75523. again = true;
  75524. }
  75525. else {
  75526. p = p.next;
  75527. }
  75528. } while (again || p !== end);
  75529. return end;
  75530. }
  75531. // main ear slicing loop which triangulates a polygon (given as a linked list)
  75532. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  75533. if (!ear)
  75534. return;
  75535. // interlink polygon nodes in z-order
  75536. if (!pass && size)
  75537. indexCurve(ear, minX, minY, size);
  75538. var stop = ear, prev, next;
  75539. // iterate through ears, slicing them one by one
  75540. while (ear.prev !== ear.next) {
  75541. prev = ear.prev;
  75542. next = ear.next;
  75543. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  75544. // cut off the triangle
  75545. triangles.push(prev.i / dim);
  75546. triangles.push(ear.i / dim);
  75547. triangles.push(next.i / dim);
  75548. removeNode(ear);
  75549. // skipping the next vertice leads to less sliver triangles
  75550. ear = next.next;
  75551. stop = next.next;
  75552. continue;
  75553. }
  75554. ear = next;
  75555. // if we looped through the whole remaining polygon and can't find any more ears
  75556. if (ear === stop) {
  75557. // try filtering points and slicing again
  75558. if (!pass) {
  75559. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  75560. // if this didn't work, try curing all small self-intersections locally
  75561. }
  75562. else if (pass === 1) {
  75563. ear = cureLocalIntersections(ear, triangles, dim);
  75564. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  75565. // as a last resort, try splitting the remaining polygon into two
  75566. }
  75567. else if (pass === 2) {
  75568. splitEarcut(ear, triangles, dim, minX, minY, size);
  75569. }
  75570. break;
  75571. }
  75572. }
  75573. }
  75574. // check whether a polygon node forms a valid ear with adjacent nodes
  75575. function isEar(ear) {
  75576. var a = ear.prev, b = ear, c = ear.next;
  75577. if (area(a, b, c) >= 0)
  75578. return false; // reflex, can't be an ear
  75579. // now make sure we don't have other points inside the potential ear
  75580. var p = ear.next.next;
  75581. while (p !== ear.prev) {
  75582. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  75583. area(p.prev, p, p.next) >= 0)
  75584. return false;
  75585. p = p.next;
  75586. }
  75587. return true;
  75588. }
  75589. function isEarHashed(ear, minX, minY, size) {
  75590. var a = ear.prev, b = ear, c = ear.next;
  75591. if (area(a, b, c) >= 0)
  75592. return false; // reflex, can't be an ear
  75593. // triangle bbox; min & max are calculated like this for speed
  75594. var minTX = a.x < b.x ? (a.x < c.x ? a.x : c.x) : (b.x < c.x ? b.x : c.x), minTY = a.y < b.y ? (a.y < c.y ? a.y : c.y) : (b.y < c.y ? b.y : c.y), maxTX = a.x > b.x ? (a.x > c.x ? a.x : c.x) : (b.x > c.x ? b.x : c.x), maxTY = a.y > b.y ? (a.y > c.y ? a.y : c.y) : (b.y > c.y ? b.y : c.y);
  75595. // z-order range for the current triangle bbox;
  75596. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  75597. // first look for points inside the triangle in increasing z-order
  75598. var p = ear.nextZ;
  75599. while (p && p.z <= maxZ) {
  75600. if (p !== ear.prev &&
  75601. p !== ear.next &&
  75602. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  75603. area(p.prev, p, p.next) >= 0)
  75604. return false;
  75605. p = p.nextZ;
  75606. }
  75607. // then look for points in decreasing z-order
  75608. p = ear.prevZ;
  75609. while (p && p.z >= minZ) {
  75610. if (p !== ear.prev &&
  75611. p !== ear.next &&
  75612. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  75613. area(p.prev, p, p.next) >= 0)
  75614. return false;
  75615. p = p.prevZ;
  75616. }
  75617. return true;
  75618. }
  75619. // go through all polygon nodes and cure small local self-intersections
  75620. function cureLocalIntersections(start, triangles, dim) {
  75621. var p = start;
  75622. do {
  75623. var a = p.prev, b = p.next.next;
  75624. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  75625. triangles.push(a.i / dim);
  75626. triangles.push(p.i / dim);
  75627. triangles.push(b.i / dim);
  75628. // remove two nodes involved
  75629. removeNode(p);
  75630. removeNode(p.next);
  75631. p = start = b;
  75632. }
  75633. p = p.next;
  75634. } while (p !== start);
  75635. return p;
  75636. }
  75637. // try splitting polygon into two and triangulate them independently
  75638. function splitEarcut(start, triangles, dim, minX, minY, size) {
  75639. // look for a valid diagonal that divides the polygon into two
  75640. var a = start;
  75641. do {
  75642. var b = a.next.next;
  75643. while (b !== a.prev) {
  75644. if (a.i !== b.i && isValidDiagonal(a, b)) {
  75645. // split the polygon in two by the diagonal
  75646. var c = splitPolygon(a, b);
  75647. // filter colinear points around the cuts
  75648. a = filterPoints(a, a.next);
  75649. c = filterPoints(c, c.next);
  75650. // run earcut on each half
  75651. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  75652. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  75653. return;
  75654. }
  75655. b = b.next;
  75656. }
  75657. a = a.next;
  75658. } while (a !== start);
  75659. }
  75660. // link every hole into the outer loop, producing a single-ring polygon without holes
  75661. function eliminateHoles(data, holeIndices, outerNode, dim) {
  75662. var queue = [], i, len, start, end, list;
  75663. for (i = 0, len = holeIndices.length; i < len; i++) {
  75664. start = holeIndices[i] * dim;
  75665. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  75666. list = linkedList(data, start, end, dim, false);
  75667. if (list === list.next)
  75668. list.steiner = true;
  75669. queue.push(getLeftmost(list));
  75670. }
  75671. queue.sort(compareX);
  75672. // process holes from left to right
  75673. for (i = 0; i < queue.length; i++) {
  75674. eliminateHole(queue[i], outerNode);
  75675. outerNode = filterPoints(outerNode, outerNode.next);
  75676. }
  75677. return outerNode;
  75678. }
  75679. function compareX(a, b) {
  75680. return a.x - b.x;
  75681. }
  75682. // find a bridge between vertices that connects hole with an outer ring and and link it
  75683. function eliminateHole(hole, outerNode) {
  75684. outerNode = findHoleBridge(hole, outerNode);
  75685. if (outerNode) {
  75686. var b = splitPolygon(outerNode, hole);
  75687. filterPoints(b, b.next);
  75688. }
  75689. }
  75690. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  75691. function findHoleBridge(hole, outerNode) {
  75692. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  75693. // find a segment intersected by a ray from the hole's leftmost point to the left;
  75694. // segment's endpoint with lesser x will be potential connection point
  75695. do {
  75696. if (hy <= p.y && hy >= p.next.y) {
  75697. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  75698. if (x <= hx && x > qx) {
  75699. qx = x;
  75700. if (x === hx) {
  75701. if (hy === p.y)
  75702. return p;
  75703. if (hy === p.next.y)
  75704. return p.next;
  75705. }
  75706. m = p.x < p.next.x ? p : p.next;
  75707. }
  75708. }
  75709. p = p.next;
  75710. } while (p !== outerNode);
  75711. if (!m)
  75712. return null;
  75713. if (hx === qx)
  75714. return m.prev; // hole touches outer segment; pick lower endpoint
  75715. // look for points inside the triangle of hole point, segment intersection and endpoint;
  75716. // if there are no points found, we have a valid connection;
  75717. // otherwise choose the point of the minimum angle with the ray as connection point
  75718. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  75719. p = m.next;
  75720. while (p !== stop) {
  75721. if (hx >= p.x &&
  75722. p.x >= mx &&
  75723. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  75724. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  75725. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  75726. m = p;
  75727. tanMin = tan;
  75728. }
  75729. }
  75730. p = p.next;
  75731. }
  75732. return m;
  75733. }
  75734. // interlink polygon nodes in z-order
  75735. function indexCurve(start, minX, minY, size) {
  75736. var p = start;
  75737. do {
  75738. if (p.z === null)
  75739. p.z = zOrder(p.x, p.y, minX, minY, size);
  75740. p.prevZ = p.prev;
  75741. p.nextZ = p.next;
  75742. p = p.next;
  75743. } while (p !== start);
  75744. p.prevZ.nextZ = null;
  75745. p.prevZ = null;
  75746. sortLinked(p);
  75747. }
  75748. // Simon Tatham's linked list merge sort algorithm
  75749. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  75750. function sortLinked(list) {
  75751. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  75752. do {
  75753. p = list;
  75754. list = null;
  75755. tail = null;
  75756. numMerges = 0;
  75757. while (p) {
  75758. numMerges++;
  75759. q = p;
  75760. pSize = 0;
  75761. for (i = 0; i < inSize; i++) {
  75762. pSize++;
  75763. q = q.nextZ;
  75764. if (!q)
  75765. break;
  75766. }
  75767. qSize = inSize;
  75768. while (pSize > 0 || (qSize > 0 && q)) {
  75769. if (pSize === 0) {
  75770. e = q;
  75771. q = q.nextZ;
  75772. qSize--;
  75773. }
  75774. else if (qSize === 0 || !q) {
  75775. e = p;
  75776. p = p.nextZ;
  75777. pSize--;
  75778. }
  75779. else if (p.z <= q.z) {
  75780. e = p;
  75781. p = p.nextZ;
  75782. pSize--;
  75783. }
  75784. else {
  75785. e = q;
  75786. q = q.nextZ;
  75787. qSize--;
  75788. }
  75789. if (tail)
  75790. tail.nextZ = e;
  75791. else
  75792. list = e;
  75793. e.prevZ = tail;
  75794. tail = e;
  75795. }
  75796. p = q;
  75797. }
  75798. tail.nextZ = null;
  75799. inSize *= 2;
  75800. } while (numMerges > 1);
  75801. return list;
  75802. }
  75803. // z-order of a point given coords and size of the data bounding box
  75804. function zOrder(x, y, minX, minY, size) {
  75805. // coords are transformed into non-negative 15-bit integer range
  75806. x = 32767 * (x - minX) / size;
  75807. y = 32767 * (y - minY) / size;
  75808. x = (x | (x << 8)) & 0x00FF00FF;
  75809. x = (x | (x << 4)) & 0x0F0F0F0F;
  75810. x = (x | (x << 2)) & 0x33333333;
  75811. x = (x | (x << 1)) & 0x55555555;
  75812. y = (y | (y << 8)) & 0x00FF00FF;
  75813. y = (y | (y << 4)) & 0x0F0F0F0F;
  75814. y = (y | (y << 2)) & 0x33333333;
  75815. y = (y | (y << 1)) & 0x55555555;
  75816. return x | (y << 1);
  75817. }
  75818. // find the leftmost node of a polygon ring
  75819. function getLeftmost(start) {
  75820. var p = start, leftmost = start;
  75821. do {
  75822. if (p.x < leftmost.x)
  75823. leftmost = p;
  75824. p = p.next;
  75825. } while (p !== start);
  75826. return leftmost;
  75827. }
  75828. // check if a point lies within a convex triangle
  75829. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  75830. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  75831. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  75832. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  75833. }
  75834. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  75835. function isValidDiagonal(a, b) {
  75836. return a.next.i !== b.i &&
  75837. a.prev.i !== b.i &&
  75838. !intersectsPolygon(a, b) &&
  75839. locallyInside(a, b) &&
  75840. locallyInside(b, a) &&
  75841. middleInside(a, b);
  75842. }
  75843. // signed area of a triangle
  75844. function area(p, q, r) {
  75845. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  75846. }
  75847. // check if two points are equal
  75848. function equals(p1, p2) {
  75849. return p1.x === p2.x && p1.y === p2.y;
  75850. }
  75851. // check if two segments intersect
  75852. function intersects(p1, q1, p2, q2) {
  75853. if ((equals(p1, q1) && equals(p2, q2)) ||
  75854. (equals(p1, q2) && equals(p2, q1)))
  75855. return true;
  75856. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  75857. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  75858. }
  75859. // check if a polygon diagonal intersects any polygon segments
  75860. function intersectsPolygon(a, b) {
  75861. var p = a;
  75862. do {
  75863. if (p.i !== a.i &&
  75864. p.next.i !== a.i &&
  75865. p.i !== b.i &&
  75866. p.next.i !== b.i &&
  75867. intersects(p, p.next, a, b))
  75868. return true;
  75869. p = p.next;
  75870. } while (p !== a);
  75871. return false;
  75872. }
  75873. // check if a polygon diagonal is locally inside the polygon
  75874. function locallyInside(a, b) {
  75875. return area(a.prev, a, a.next) < 0
  75876. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  75877. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  75878. }
  75879. // check if the middle point of a polygon diagonal is inside the polygon
  75880. function middleInside(a, b) {
  75881. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  75882. do {
  75883. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  75884. inside = !inside;
  75885. p = p.next;
  75886. } while (p !== a);
  75887. return inside;
  75888. }
  75889. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  75890. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  75891. function splitPolygon(a, b) {
  75892. var a2 = new Node(a.i, a.x, a.y), b2 = new Node(b.i, b.x, b.y), an = a.next, bp = b.prev;
  75893. a.next = b;
  75894. b.prev = a;
  75895. a2.next = an;
  75896. an.prev = a2;
  75897. b2.next = a2;
  75898. a2.prev = b2;
  75899. bp.next = b2;
  75900. b2.prev = bp;
  75901. return b2;
  75902. }
  75903. // create a node and optionally link it with previous one (in a circular doubly linked list)
  75904. function insertNode(i, x, y, last) {
  75905. var p = new Node(i, x, y);
  75906. if (!last) {
  75907. p.prev = p;
  75908. p.next = p;
  75909. }
  75910. else {
  75911. p.next = last.next;
  75912. p.prev = last;
  75913. last.next.prev = p;
  75914. last.next = p;
  75915. }
  75916. return p;
  75917. }
  75918. function removeNode(p) {
  75919. p.next.prev = p.prev;
  75920. p.prev.next = p.next;
  75921. if (p.prevZ)
  75922. p.prevZ.nextZ = p.nextZ;
  75923. if (p.nextZ)
  75924. p.nextZ.prevZ = p.prevZ;
  75925. }
  75926. /**
  75927. * return a percentage difference between the polygon area and its triangulation area;
  75928. * used to verify correctness of triangulation
  75929. */
  75930. function deviation(data, holeIndices, dim, triangles) {
  75931. var hasHoles = holeIndices && holeIndices.length;
  75932. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  75933. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  75934. if (hasHoles) {
  75935. for (var i = 0, len = holeIndices.length; i < len; i++) {
  75936. var start = holeIndices[i] * dim;
  75937. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  75938. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  75939. }
  75940. }
  75941. var trianglesArea = 0;
  75942. for (i = 0; i < triangles.length; i += 3) {
  75943. var a = triangles[i] * dim;
  75944. var b = triangles[i + 1] * dim;
  75945. var c = triangles[i + 2] * dim;
  75946. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  75947. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  75948. }
  75949. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  75950. }
  75951. Earcut.deviation = deviation;
  75952. ;
  75953. function signedArea(data, start, end, dim) {
  75954. var sum = 0;
  75955. for (var i = start, j = end - dim; i < end; i += dim) {
  75956. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  75957. j = i;
  75958. }
  75959. return sum;
  75960. }
  75961. /**
  75962. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  75963. */
  75964. function flatten(data) {
  75965. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  75966. for (var i = 0; i < data.length; i++) {
  75967. for (var j = 0; j < data[i].length; j++) {
  75968. for (var d = 0; d < dim; d++)
  75969. result.vertices.push(data[i][j][d]);
  75970. }
  75971. if (i > 0) {
  75972. holeIndex += data[i - 1].length;
  75973. result.holes.push(holeIndex);
  75974. }
  75975. }
  75976. return result;
  75977. }
  75978. Earcut.flatten = flatten;
  75979. ;
  75980. })(Earcut || (Earcut = {}));
  75981. //# sourceMappingURL=babylon.earcut.js.map
  75982. "use strict";
  75983. var BABYLON;
  75984. (function (BABYLON) {
  75985. var IndexedVector2 = /** @class */ (function (_super) {
  75986. __extends(IndexedVector2, _super);
  75987. function IndexedVector2(original, index) {
  75988. var _this = _super.call(this, original.x, original.y) || this;
  75989. _this.index = index;
  75990. return _this;
  75991. }
  75992. return IndexedVector2;
  75993. }(BABYLON.Vector2));
  75994. var PolygonPoints = /** @class */ (function () {
  75995. function PolygonPoints() {
  75996. this.elements = new Array();
  75997. }
  75998. PolygonPoints.prototype.add = function (originalPoints) {
  75999. var _this = this;
  76000. var result = new Array();
  76001. originalPoints.forEach(function (point) {
  76002. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  76003. var newPoint = new IndexedVector2(point, _this.elements.length);
  76004. result.push(newPoint);
  76005. _this.elements.push(newPoint);
  76006. }
  76007. });
  76008. return result;
  76009. };
  76010. PolygonPoints.prototype.computeBounds = function () {
  76011. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  76012. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  76013. this.elements.forEach(function (point) {
  76014. // x
  76015. if (point.x < lmin.x) {
  76016. lmin.x = point.x;
  76017. }
  76018. else if (point.x > lmax.x) {
  76019. lmax.x = point.x;
  76020. }
  76021. // y
  76022. if (point.y < lmin.y) {
  76023. lmin.y = point.y;
  76024. }
  76025. else if (point.y > lmax.y) {
  76026. lmax.y = point.y;
  76027. }
  76028. });
  76029. return {
  76030. min: lmin,
  76031. max: lmax,
  76032. width: lmax.x - lmin.x,
  76033. height: lmax.y - lmin.y
  76034. };
  76035. };
  76036. return PolygonPoints;
  76037. }());
  76038. var Polygon = /** @class */ (function () {
  76039. function Polygon() {
  76040. }
  76041. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  76042. return [
  76043. new BABYLON.Vector2(xmin, ymin),
  76044. new BABYLON.Vector2(xmax, ymin),
  76045. new BABYLON.Vector2(xmax, ymax),
  76046. new BABYLON.Vector2(xmin, ymax)
  76047. ];
  76048. };
  76049. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  76050. if (cx === void 0) { cx = 0; }
  76051. if (cy === void 0) { cy = 0; }
  76052. if (numberOfSides === void 0) { numberOfSides = 32; }
  76053. var result = new Array();
  76054. var angle = 0;
  76055. var increment = (Math.PI * 2) / numberOfSides;
  76056. for (var i = 0; i < numberOfSides; i++) {
  76057. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  76058. angle -= increment;
  76059. }
  76060. return result;
  76061. };
  76062. Polygon.Parse = function (input) {
  76063. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  76064. var i, result = [];
  76065. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  76066. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  76067. }
  76068. return result;
  76069. };
  76070. Polygon.StartingAt = function (x, y) {
  76071. return BABYLON.Path2.StartingAt(x, y);
  76072. };
  76073. return Polygon;
  76074. }());
  76075. BABYLON.Polygon = Polygon;
  76076. var PolygonMeshBuilder = /** @class */ (function () {
  76077. function PolygonMeshBuilder(name, contours, scene) {
  76078. this._points = new PolygonPoints();
  76079. this._outlinepoints = new PolygonPoints();
  76080. this._holes = new Array();
  76081. this._epoints = new Array();
  76082. this._eholes = new Array();
  76083. this._name = name;
  76084. this._scene = scene;
  76085. var points;
  76086. if (contours instanceof BABYLON.Path2) {
  76087. points = contours.getPoints();
  76088. }
  76089. else {
  76090. points = contours;
  76091. }
  76092. this._addToepoint(points);
  76093. this._points.add(points);
  76094. this._outlinepoints.add(points);
  76095. }
  76096. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  76097. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  76098. var p = points_1[_i];
  76099. this._epoints.push(p.x, p.y);
  76100. }
  76101. };
  76102. PolygonMeshBuilder.prototype.addHole = function (hole) {
  76103. this._points.add(hole);
  76104. var holepoints = new PolygonPoints();
  76105. holepoints.add(hole);
  76106. this._holes.push(holepoints);
  76107. this._eholes.push(this._epoints.length / 2);
  76108. this._addToepoint(hole);
  76109. return this;
  76110. };
  76111. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  76112. var _this = this;
  76113. if (updatable === void 0) { updatable = false; }
  76114. if (depth === void 0) { depth = 0; }
  76115. var result = new BABYLON.Mesh(this._name, this._scene);
  76116. var normals = new Array();
  76117. var positions = new Array();
  76118. var uvs = new Array();
  76119. var bounds = this._points.computeBounds();
  76120. this._points.elements.forEach(function (p) {
  76121. normals.push(0, 1.0, 0);
  76122. positions.push(p.x, 0, p.y);
  76123. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  76124. });
  76125. var indices = new Array();
  76126. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  76127. for (var i = 0; i < res.length; i++) {
  76128. indices.push(res[i]);
  76129. }
  76130. if (depth > 0) {
  76131. var positionscount = (positions.length / 3); //get the current pointcount
  76132. this._points.elements.forEach(function (p) {
  76133. normals.push(0, -1.0, 0);
  76134. positions.push(p.x, -depth, p.y);
  76135. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  76136. });
  76137. var totalCount = indices.length;
  76138. for (var i = 0; i < totalCount; i += 3) {
  76139. var i0 = indices[i + 0];
  76140. var i1 = indices[i + 1];
  76141. var i2 = indices[i + 2];
  76142. indices.push(i2 + positionscount);
  76143. indices.push(i1 + positionscount);
  76144. indices.push(i0 + positionscount);
  76145. }
  76146. //Add the sides
  76147. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  76148. this._holes.forEach(function (hole) {
  76149. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  76150. });
  76151. }
  76152. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  76153. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  76154. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  76155. result.setIndices(indices);
  76156. return result;
  76157. };
  76158. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  76159. var StartIndex = positions.length / 3;
  76160. var ulength = 0;
  76161. for (var i = 0; i < points.elements.length; i++) {
  76162. var p = points.elements[i];
  76163. var p1;
  76164. if ((i + 1) > points.elements.length - 1) {
  76165. p1 = points.elements[0];
  76166. }
  76167. else {
  76168. p1 = points.elements[i + 1];
  76169. }
  76170. positions.push(p.x, 0, p.y);
  76171. positions.push(p.x, -depth, p.y);
  76172. positions.push(p1.x, 0, p1.y);
  76173. positions.push(p1.x, -depth, p1.y);
  76174. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  76175. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  76176. var v3 = v2.subtract(v1);
  76177. var v4 = new BABYLON.Vector3(0, 1, 0);
  76178. var vn = BABYLON.Vector3.Cross(v3, v4);
  76179. vn = vn.normalize();
  76180. uvs.push(ulength / bounds.width, 0);
  76181. uvs.push(ulength / bounds.width, 1);
  76182. ulength += v3.length();
  76183. uvs.push((ulength / bounds.width), 0);
  76184. uvs.push((ulength / bounds.width), 1);
  76185. if (!flip) {
  76186. normals.push(-vn.x, -vn.y, -vn.z);
  76187. normals.push(-vn.x, -vn.y, -vn.z);
  76188. normals.push(-vn.x, -vn.y, -vn.z);
  76189. normals.push(-vn.x, -vn.y, -vn.z);
  76190. indices.push(StartIndex);
  76191. indices.push(StartIndex + 1);
  76192. indices.push(StartIndex + 2);
  76193. indices.push(StartIndex + 1);
  76194. indices.push(StartIndex + 3);
  76195. indices.push(StartIndex + 2);
  76196. }
  76197. else {
  76198. normals.push(vn.x, vn.y, vn.z);
  76199. normals.push(vn.x, vn.y, vn.z);
  76200. normals.push(vn.x, vn.y, vn.z);
  76201. normals.push(vn.x, vn.y, vn.z);
  76202. indices.push(StartIndex);
  76203. indices.push(StartIndex + 2);
  76204. indices.push(StartIndex + 1);
  76205. indices.push(StartIndex + 1);
  76206. indices.push(StartIndex + 2);
  76207. indices.push(StartIndex + 3);
  76208. }
  76209. StartIndex += 4;
  76210. }
  76211. ;
  76212. };
  76213. return PolygonMeshBuilder;
  76214. }());
  76215. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  76216. })(BABYLON || (BABYLON = {}));
  76217. //# sourceMappingURL=babylon.polygonMesh.js.map
  76218. "use strict";
  76219. var BABYLON;
  76220. (function (BABYLON) {
  76221. // Unique ID when we import meshes from Babylon to CSG
  76222. var currentCSGMeshId = 0;
  76223. // # class Vertex
  76224. // Represents a vertex of a polygon. Use your own vertex class instead of this
  76225. // one to provide additional features like texture coordinates and vertex
  76226. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  76227. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  76228. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  76229. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  76230. // is not used anywhere else.
  76231. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  76232. var Vertex = /** @class */ (function () {
  76233. function Vertex(pos, normal, uv) {
  76234. this.pos = pos;
  76235. this.normal = normal;
  76236. this.uv = uv;
  76237. }
  76238. Vertex.prototype.clone = function () {
  76239. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  76240. };
  76241. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  76242. // orientation of a polygon is flipped.
  76243. Vertex.prototype.flip = function () {
  76244. this.normal = this.normal.scale(-1);
  76245. };
  76246. // Create a new vertex between this vertex and `other` by linearly
  76247. // interpolating all properties using a parameter of `t`. Subclasses should
  76248. // override this to interpolate additional properties.
  76249. Vertex.prototype.interpolate = function (other, t) {
  76250. 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));
  76251. };
  76252. return Vertex;
  76253. }());
  76254. // # class Plane
  76255. // Represents a plane in 3D space.
  76256. var Plane = /** @class */ (function () {
  76257. function Plane(normal, w) {
  76258. this.normal = normal;
  76259. this.w = w;
  76260. }
  76261. Plane.FromPoints = function (a, b, c) {
  76262. var v0 = c.subtract(a);
  76263. var v1 = b.subtract(a);
  76264. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  76265. return null;
  76266. }
  76267. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  76268. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  76269. };
  76270. Plane.prototype.clone = function () {
  76271. return new Plane(this.normal.clone(), this.w);
  76272. };
  76273. Plane.prototype.flip = function () {
  76274. this.normal.scaleInPlace(-1);
  76275. this.w = -this.w;
  76276. };
  76277. // Split `polygon` by this plane if needed, then put the polygon or polygon
  76278. // fragments in the appropriate lists. Coplanar polygons go into either
  76279. // `coplanarFront` or `coplanarBack` depending on their orientation with
  76280. // respect to this plane. Polygons in front or in back of this plane go into
  76281. // either `front` or `back`.
  76282. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  76283. var COPLANAR = 0;
  76284. var FRONT = 1;
  76285. var BACK = 2;
  76286. var SPANNING = 3;
  76287. // Classify each point as well as the entire polygon into one of the above
  76288. // four classes.
  76289. var polygonType = 0;
  76290. var types = [];
  76291. var i;
  76292. var t;
  76293. for (i = 0; i < polygon.vertices.length; i++) {
  76294. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  76295. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  76296. polygonType |= type;
  76297. types.push(type);
  76298. }
  76299. // Put the polygon in the correct list, splitting it when necessary.
  76300. switch (polygonType) {
  76301. case COPLANAR:
  76302. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  76303. break;
  76304. case FRONT:
  76305. front.push(polygon);
  76306. break;
  76307. case BACK:
  76308. back.push(polygon);
  76309. break;
  76310. case SPANNING:
  76311. var f = [], b = [];
  76312. for (i = 0; i < polygon.vertices.length; i++) {
  76313. var j = (i + 1) % polygon.vertices.length;
  76314. var ti = types[i], tj = types[j];
  76315. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  76316. if (ti !== BACK)
  76317. f.push(vi);
  76318. if (ti !== FRONT)
  76319. b.push(ti !== BACK ? vi.clone() : vi);
  76320. if ((ti | tj) === SPANNING) {
  76321. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  76322. var v = vi.interpolate(vj, t);
  76323. f.push(v);
  76324. b.push(v.clone());
  76325. }
  76326. }
  76327. var poly;
  76328. if (f.length >= 3) {
  76329. poly = new Polygon(f, polygon.shared);
  76330. if (poly.plane)
  76331. front.push(poly);
  76332. }
  76333. if (b.length >= 3) {
  76334. poly = new Polygon(b, polygon.shared);
  76335. if (poly.plane)
  76336. back.push(poly);
  76337. }
  76338. break;
  76339. }
  76340. };
  76341. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  76342. // point is on the plane.
  76343. Plane.EPSILON = 1e-5;
  76344. return Plane;
  76345. }());
  76346. // # class Polygon
  76347. // Represents a convex polygon. The vertices used to initialize a polygon must
  76348. // be coplanar and form a convex loop.
  76349. //
  76350. // Each convex polygon has a `shared` property, which is shared between all
  76351. // polygons that are clones of each other or were split from the same polygon.
  76352. // This can be used to define per-polygon properties (such as surface color).
  76353. var Polygon = /** @class */ (function () {
  76354. function Polygon(vertices, shared) {
  76355. this.vertices = vertices;
  76356. this.shared = shared;
  76357. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  76358. }
  76359. Polygon.prototype.clone = function () {
  76360. var vertices = this.vertices.map(function (v) { return v.clone(); });
  76361. return new Polygon(vertices, this.shared);
  76362. };
  76363. Polygon.prototype.flip = function () {
  76364. this.vertices.reverse().map(function (v) { v.flip(); });
  76365. this.plane.flip();
  76366. };
  76367. return Polygon;
  76368. }());
  76369. // # class Node
  76370. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  76371. // by picking a polygon to split along. That polygon (and all other coplanar
  76372. // polygons) are added directly to that node and the other polygons are added to
  76373. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  76374. // no distinction between internal and leaf nodes.
  76375. var Node = /** @class */ (function () {
  76376. function Node(polygons) {
  76377. this.plane = null;
  76378. this.front = null;
  76379. this.back = null;
  76380. this.polygons = new Array();
  76381. if (polygons) {
  76382. this.build(polygons);
  76383. }
  76384. }
  76385. Node.prototype.clone = function () {
  76386. var node = new Node();
  76387. node.plane = this.plane && this.plane.clone();
  76388. node.front = this.front && this.front.clone();
  76389. node.back = this.back && this.back.clone();
  76390. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  76391. return node;
  76392. };
  76393. // Convert solid space to empty space and empty space to solid space.
  76394. Node.prototype.invert = function () {
  76395. for (var i = 0; i < this.polygons.length; i++) {
  76396. this.polygons[i].flip();
  76397. }
  76398. if (this.plane) {
  76399. this.plane.flip();
  76400. }
  76401. if (this.front) {
  76402. this.front.invert();
  76403. }
  76404. if (this.back) {
  76405. this.back.invert();
  76406. }
  76407. var temp = this.front;
  76408. this.front = this.back;
  76409. this.back = temp;
  76410. };
  76411. // Recursively remove all polygons in `polygons` that are inside this BSP
  76412. // tree.
  76413. Node.prototype.clipPolygons = function (polygons) {
  76414. if (!this.plane)
  76415. return polygons.slice();
  76416. var front = new Array(), back = new Array();
  76417. for (var i = 0; i < polygons.length; i++) {
  76418. this.plane.splitPolygon(polygons[i], front, back, front, back);
  76419. }
  76420. if (this.front) {
  76421. front = this.front.clipPolygons(front);
  76422. }
  76423. if (this.back) {
  76424. back = this.back.clipPolygons(back);
  76425. }
  76426. else {
  76427. back = [];
  76428. }
  76429. return front.concat(back);
  76430. };
  76431. // Remove all polygons in this BSP tree that are inside the other BSP tree
  76432. // `bsp`.
  76433. Node.prototype.clipTo = function (bsp) {
  76434. this.polygons = bsp.clipPolygons(this.polygons);
  76435. if (this.front)
  76436. this.front.clipTo(bsp);
  76437. if (this.back)
  76438. this.back.clipTo(bsp);
  76439. };
  76440. // Return a list of all polygons in this BSP tree.
  76441. Node.prototype.allPolygons = function () {
  76442. var polygons = this.polygons.slice();
  76443. if (this.front)
  76444. polygons = polygons.concat(this.front.allPolygons());
  76445. if (this.back)
  76446. polygons = polygons.concat(this.back.allPolygons());
  76447. return polygons;
  76448. };
  76449. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  76450. // new polygons are filtered down to the bottom of the tree and become new
  76451. // nodes there. Each set of polygons is partitioned using the first polygon
  76452. // (no heuristic is used to pick a good split).
  76453. Node.prototype.build = function (polygons) {
  76454. if (!polygons.length)
  76455. return;
  76456. if (!this.plane)
  76457. this.plane = polygons[0].plane.clone();
  76458. var front = new Array(), back = new Array();
  76459. for (var i = 0; i < polygons.length; i++) {
  76460. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  76461. }
  76462. if (front.length) {
  76463. if (!this.front)
  76464. this.front = new Node();
  76465. this.front.build(front);
  76466. }
  76467. if (back.length) {
  76468. if (!this.back)
  76469. this.back = new Node();
  76470. this.back.build(back);
  76471. }
  76472. };
  76473. return Node;
  76474. }());
  76475. var CSG = /** @class */ (function () {
  76476. function CSG() {
  76477. this.polygons = new Array();
  76478. }
  76479. // Convert BABYLON.Mesh to BABYLON.CSG
  76480. CSG.FromMesh = function (mesh) {
  76481. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  76482. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  76483. if (mesh instanceof BABYLON.Mesh) {
  76484. mesh.computeWorldMatrix(true);
  76485. matrix = mesh.getWorldMatrix();
  76486. meshPosition = mesh.position.clone();
  76487. meshRotation = mesh.rotation.clone();
  76488. if (mesh.rotationQuaternion) {
  76489. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  76490. }
  76491. meshScaling = mesh.scaling.clone();
  76492. }
  76493. else {
  76494. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  76495. }
  76496. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  76497. var subMeshes = mesh.subMeshes;
  76498. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  76499. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  76500. vertices = [];
  76501. for (var j = 0; j < 3; j++) {
  76502. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  76503. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  76504. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  76505. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  76506. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  76507. vertex = new Vertex(position, normal, uv);
  76508. vertices.push(vertex);
  76509. }
  76510. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  76511. // To handle the case of degenerated triangle
  76512. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  76513. if (polygon.plane)
  76514. polygons.push(polygon);
  76515. }
  76516. }
  76517. var csg = CSG.FromPolygons(polygons);
  76518. csg.matrix = matrix;
  76519. csg.position = meshPosition;
  76520. csg.rotation = meshRotation;
  76521. csg.scaling = meshScaling;
  76522. csg.rotationQuaternion = meshRotationQuaternion;
  76523. currentCSGMeshId++;
  76524. return csg;
  76525. };
  76526. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  76527. CSG.FromPolygons = function (polygons) {
  76528. var csg = new CSG();
  76529. csg.polygons = polygons;
  76530. return csg;
  76531. };
  76532. CSG.prototype.clone = function () {
  76533. var csg = new CSG();
  76534. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  76535. csg.copyTransformAttributes(this);
  76536. return csg;
  76537. };
  76538. CSG.prototype.union = function (csg) {
  76539. var a = new Node(this.clone().polygons);
  76540. var b = new Node(csg.clone().polygons);
  76541. a.clipTo(b);
  76542. b.clipTo(a);
  76543. b.invert();
  76544. b.clipTo(a);
  76545. b.invert();
  76546. a.build(b.allPolygons());
  76547. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  76548. };
  76549. CSG.prototype.unionInPlace = function (csg) {
  76550. var a = new Node(this.polygons);
  76551. var b = new Node(csg.polygons);
  76552. a.clipTo(b);
  76553. b.clipTo(a);
  76554. b.invert();
  76555. b.clipTo(a);
  76556. b.invert();
  76557. a.build(b.allPolygons());
  76558. this.polygons = a.allPolygons();
  76559. };
  76560. CSG.prototype.subtract = function (csg) {
  76561. var a = new Node(this.clone().polygons);
  76562. var b = new Node(csg.clone().polygons);
  76563. a.invert();
  76564. a.clipTo(b);
  76565. b.clipTo(a);
  76566. b.invert();
  76567. b.clipTo(a);
  76568. b.invert();
  76569. a.build(b.allPolygons());
  76570. a.invert();
  76571. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  76572. };
  76573. CSG.prototype.subtractInPlace = function (csg) {
  76574. var a = new Node(this.polygons);
  76575. var b = new Node(csg.polygons);
  76576. a.invert();
  76577. a.clipTo(b);
  76578. b.clipTo(a);
  76579. b.invert();
  76580. b.clipTo(a);
  76581. b.invert();
  76582. a.build(b.allPolygons());
  76583. a.invert();
  76584. this.polygons = a.allPolygons();
  76585. };
  76586. CSG.prototype.intersect = function (csg) {
  76587. var a = new Node(this.clone().polygons);
  76588. var b = new Node(csg.clone().polygons);
  76589. a.invert();
  76590. b.clipTo(a);
  76591. b.invert();
  76592. a.clipTo(b);
  76593. b.clipTo(a);
  76594. a.build(b.allPolygons());
  76595. a.invert();
  76596. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  76597. };
  76598. CSG.prototype.intersectInPlace = function (csg) {
  76599. var a = new Node(this.polygons);
  76600. var b = new Node(csg.polygons);
  76601. a.invert();
  76602. b.clipTo(a);
  76603. b.invert();
  76604. a.clipTo(b);
  76605. b.clipTo(a);
  76606. a.build(b.allPolygons());
  76607. a.invert();
  76608. this.polygons = a.allPolygons();
  76609. };
  76610. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  76611. // not modified.
  76612. CSG.prototype.inverse = function () {
  76613. var csg = this.clone();
  76614. csg.inverseInPlace();
  76615. return csg;
  76616. };
  76617. CSG.prototype.inverseInPlace = function () {
  76618. this.polygons.map(function (p) { p.flip(); });
  76619. };
  76620. // This is used to keep meshes transformations so they can be restored
  76621. // when we build back a Babylon Mesh
  76622. // NB : All CSG operations are performed in world coordinates
  76623. CSG.prototype.copyTransformAttributes = function (csg) {
  76624. this.matrix = csg.matrix;
  76625. this.position = csg.position;
  76626. this.rotation = csg.rotation;
  76627. this.scaling = csg.scaling;
  76628. this.rotationQuaternion = csg.rotationQuaternion;
  76629. return this;
  76630. };
  76631. // Build Raw mesh from CSG
  76632. // Coordinates here are in world space
  76633. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  76634. var matrix = this.matrix.clone();
  76635. matrix.invert();
  76636. 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;
  76637. if (keepSubMeshes) {
  76638. // Sort Polygons, since subMeshes are indices range
  76639. polygons.sort(function (a, b) {
  76640. if (a.shared.meshId === b.shared.meshId) {
  76641. return a.shared.subMeshId - b.shared.subMeshId;
  76642. }
  76643. else {
  76644. return a.shared.meshId - b.shared.meshId;
  76645. }
  76646. });
  76647. }
  76648. for (var i = 0, il = polygons.length; i < il; i++) {
  76649. polygon = polygons[i];
  76650. // Building SubMeshes
  76651. if (!subMesh_dict[polygon.shared.meshId]) {
  76652. subMesh_dict[polygon.shared.meshId] = {};
  76653. }
  76654. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  76655. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  76656. indexStart: +Infinity,
  76657. indexEnd: -Infinity,
  76658. materialIndex: polygon.shared.materialIndex
  76659. };
  76660. }
  76661. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  76662. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  76663. polygonIndices[0] = 0;
  76664. polygonIndices[1] = j - 1;
  76665. polygonIndices[2] = j;
  76666. for (var k = 0; k < 3; k++) {
  76667. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  76668. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  76669. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  76670. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  76671. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  76672. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  76673. // Check if 2 points can be merged
  76674. if (!(typeof vertex_idx !== 'undefined' &&
  76675. normals[vertex_idx * 3] === localNormal.x &&
  76676. normals[vertex_idx * 3 + 1] === localNormal.y &&
  76677. normals[vertex_idx * 3 + 2] === localNormal.z &&
  76678. uvs[vertex_idx * 2] === uv.x &&
  76679. uvs[vertex_idx * 2 + 1] === uv.y)) {
  76680. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  76681. uvs.push(uv.x, uv.y);
  76682. normals.push(normal.x, normal.y, normal.z);
  76683. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  76684. }
  76685. indices.push(vertex_idx);
  76686. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  76687. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  76688. currentIndex++;
  76689. }
  76690. }
  76691. }
  76692. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  76693. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  76694. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  76695. mesh.setIndices(indices, null);
  76696. if (keepSubMeshes) {
  76697. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  76698. var materialIndexOffset = 0, materialMaxIndex;
  76699. mesh.subMeshes = new Array();
  76700. for (var m in subMesh_dict) {
  76701. materialMaxIndex = -1;
  76702. for (var sm in subMesh_dict[m]) {
  76703. subMesh_obj = subMesh_dict[m][sm];
  76704. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  76705. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  76706. }
  76707. materialIndexOffset += ++materialMaxIndex;
  76708. }
  76709. }
  76710. return mesh;
  76711. };
  76712. // Build Mesh from CSG taking material and transforms into account
  76713. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  76714. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  76715. mesh.material = material;
  76716. mesh.position.copyFrom(this.position);
  76717. mesh.rotation.copyFrom(this.rotation);
  76718. if (this.rotationQuaternion) {
  76719. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  76720. }
  76721. mesh.scaling.copyFrom(this.scaling);
  76722. mesh.computeWorldMatrix(true);
  76723. return mesh;
  76724. };
  76725. return CSG;
  76726. }());
  76727. BABYLON.CSG = CSG;
  76728. })(BABYLON || (BABYLON = {}));
  76729. //# sourceMappingURL=babylon.csg.js.map
  76730. "use strict";
  76731. var BABYLON;
  76732. (function (BABYLON) {
  76733. var LensFlare = /** @class */ (function () {
  76734. function LensFlare(size, position, color, imgUrl, system) {
  76735. this.size = size;
  76736. this.position = position;
  76737. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  76738. this.color = color || new BABYLON.Color3(1, 1, 1);
  76739. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  76740. this._system = system;
  76741. system.lensFlares.push(this);
  76742. }
  76743. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  76744. return new LensFlare(size, position, color, imgUrl, system);
  76745. };
  76746. LensFlare.prototype.dispose = function () {
  76747. if (this.texture) {
  76748. this.texture.dispose();
  76749. }
  76750. // Remove from scene
  76751. var index = this._system.lensFlares.indexOf(this);
  76752. this._system.lensFlares.splice(index, 1);
  76753. };
  76754. ;
  76755. return LensFlare;
  76756. }());
  76757. BABYLON.LensFlare = LensFlare;
  76758. })(BABYLON || (BABYLON = {}));
  76759. //# sourceMappingURL=babylon.lensFlare.js.map
  76760. "use strict";
  76761. var BABYLON;
  76762. (function (BABYLON) {
  76763. var LensFlareSystem = /** @class */ (function () {
  76764. function LensFlareSystem(name, emitter, scene) {
  76765. this.name = name;
  76766. this.lensFlares = new Array();
  76767. this.borderLimit = 300;
  76768. this.viewportBorder = 0;
  76769. this.layerMask = 0x0FFFFFFF;
  76770. this._vertexBuffers = {};
  76771. this._isEnabled = true;
  76772. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  76773. this._emitter = emitter;
  76774. this.id = name;
  76775. scene.lensFlareSystems.push(this);
  76776. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  76777. var engine = scene.getEngine();
  76778. // VBO
  76779. var vertices = [];
  76780. vertices.push(1, 1);
  76781. vertices.push(-1, 1);
  76782. vertices.push(-1, -1);
  76783. vertices.push(1, -1);
  76784. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  76785. // Indices
  76786. var indices = [];
  76787. indices.push(0);
  76788. indices.push(1);
  76789. indices.push(2);
  76790. indices.push(0);
  76791. indices.push(2);
  76792. indices.push(3);
  76793. this._indexBuffer = engine.createIndexBuffer(indices);
  76794. // Effects
  76795. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  76796. }
  76797. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  76798. get: function () {
  76799. return this._isEnabled;
  76800. },
  76801. set: function (value) {
  76802. this._isEnabled = value;
  76803. },
  76804. enumerable: true,
  76805. configurable: true
  76806. });
  76807. LensFlareSystem.prototype.getScene = function () {
  76808. return this._scene;
  76809. };
  76810. LensFlareSystem.prototype.getEmitter = function () {
  76811. return this._emitter;
  76812. };
  76813. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  76814. this._emitter = newEmitter;
  76815. };
  76816. LensFlareSystem.prototype.getEmitterPosition = function () {
  76817. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  76818. };
  76819. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  76820. var position = this.getEmitterPosition();
  76821. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  76822. this._positionX = position.x;
  76823. this._positionY = position.y;
  76824. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  76825. if (this.viewportBorder > 0) {
  76826. globalViewport.x -= this.viewportBorder;
  76827. globalViewport.y -= this.viewportBorder;
  76828. globalViewport.width += this.viewportBorder * 2;
  76829. globalViewport.height += this.viewportBorder * 2;
  76830. position.x += this.viewportBorder;
  76831. position.y += this.viewportBorder;
  76832. this._positionX += this.viewportBorder;
  76833. this._positionY += this.viewportBorder;
  76834. }
  76835. if (position.z > 0) {
  76836. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  76837. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  76838. return true;
  76839. }
  76840. return true;
  76841. }
  76842. return false;
  76843. };
  76844. LensFlareSystem.prototype._isVisible = function () {
  76845. if (!this._isEnabled || !this._scene.activeCamera) {
  76846. return false;
  76847. }
  76848. var emitterPosition = this.getEmitterPosition();
  76849. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  76850. var distance = direction.length();
  76851. direction.normalize();
  76852. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  76853. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  76854. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  76855. };
  76856. LensFlareSystem.prototype.render = function () {
  76857. if (!this._effect.isReady() || !this._scene.activeCamera)
  76858. return false;
  76859. var engine = this._scene.getEngine();
  76860. var viewport = this._scene.activeCamera.viewport;
  76861. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  76862. // Position
  76863. if (!this.computeEffectivePosition(globalViewport)) {
  76864. return false;
  76865. }
  76866. // Visibility
  76867. if (!this._isVisible()) {
  76868. return false;
  76869. }
  76870. // Intensity
  76871. var awayX;
  76872. var awayY;
  76873. if (this._positionX < this.borderLimit + globalViewport.x) {
  76874. awayX = this.borderLimit + globalViewport.x - this._positionX;
  76875. }
  76876. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  76877. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  76878. }
  76879. else {
  76880. awayX = 0;
  76881. }
  76882. if (this._positionY < this.borderLimit + globalViewport.y) {
  76883. awayY = this.borderLimit + globalViewport.y - this._positionY;
  76884. }
  76885. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  76886. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  76887. }
  76888. else {
  76889. awayY = 0;
  76890. }
  76891. var away = (awayX > awayY) ? awayX : awayY;
  76892. away -= this.viewportBorder;
  76893. if (away > this.borderLimit) {
  76894. away = this.borderLimit;
  76895. }
  76896. var intensity = 1.0 - (away / this.borderLimit);
  76897. if (intensity < 0) {
  76898. return false;
  76899. }
  76900. if (intensity > 1.0) {
  76901. intensity = 1.0;
  76902. }
  76903. if (this.viewportBorder > 0) {
  76904. globalViewport.x += this.viewportBorder;
  76905. globalViewport.y += this.viewportBorder;
  76906. globalViewport.width -= this.viewportBorder * 2;
  76907. globalViewport.height -= this.viewportBorder * 2;
  76908. this._positionX -= this.viewportBorder;
  76909. this._positionY -= this.viewportBorder;
  76910. }
  76911. // Position
  76912. var centerX = globalViewport.x + globalViewport.width / 2;
  76913. var centerY = globalViewport.y + globalViewport.height / 2;
  76914. var distX = centerX - this._positionX;
  76915. var distY = centerY - this._positionY;
  76916. // Effects
  76917. engine.enableEffect(this._effect);
  76918. engine.setState(false);
  76919. engine.setDepthBuffer(false);
  76920. // VBOs
  76921. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  76922. // Flares
  76923. for (var index = 0; index < this.lensFlares.length; index++) {
  76924. var flare = this.lensFlares[index];
  76925. engine.setAlphaMode(flare.alphaMode);
  76926. var x = centerX - (distX * flare.position);
  76927. var y = centerY - (distY * flare.position);
  76928. var cw = flare.size;
  76929. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  76930. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  76931. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  76932. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  76933. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  76934. // Texture
  76935. this._effect.setTexture("textureSampler", flare.texture);
  76936. // Color
  76937. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  76938. // Draw order
  76939. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  76940. }
  76941. engine.setDepthBuffer(true);
  76942. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  76943. return true;
  76944. };
  76945. LensFlareSystem.prototype.dispose = function () {
  76946. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  76947. if (vertexBuffer) {
  76948. vertexBuffer.dispose();
  76949. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  76950. }
  76951. if (this._indexBuffer) {
  76952. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  76953. this._indexBuffer = null;
  76954. }
  76955. while (this.lensFlares.length) {
  76956. this.lensFlares[0].dispose();
  76957. }
  76958. // Remove from scene
  76959. var index = this._scene.lensFlareSystems.indexOf(this);
  76960. this._scene.lensFlareSystems.splice(index, 1);
  76961. };
  76962. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  76963. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  76964. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  76965. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  76966. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  76967. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  76968. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  76969. var parsedFlare = parsedLensFlareSystem.flares[index];
  76970. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  76971. }
  76972. return lensFlareSystem;
  76973. };
  76974. LensFlareSystem.prototype.serialize = function () {
  76975. var serializationObject = {};
  76976. serializationObject.id = this.id;
  76977. serializationObject.name = this.name;
  76978. serializationObject.emitterId = this.getEmitter().id;
  76979. serializationObject.borderLimit = this.borderLimit;
  76980. serializationObject.flares = [];
  76981. for (var index = 0; index < this.lensFlares.length; index++) {
  76982. var flare = this.lensFlares[index];
  76983. serializationObject.flares.push({
  76984. size: flare.size,
  76985. position: flare.position,
  76986. color: flare.color.asArray(),
  76987. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  76988. });
  76989. }
  76990. return serializationObject;
  76991. };
  76992. return LensFlareSystem;
  76993. }());
  76994. BABYLON.LensFlareSystem = LensFlareSystem;
  76995. })(BABYLON || (BABYLON = {}));
  76996. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  76997. "use strict";
  76998. var BABYLON;
  76999. (function (BABYLON) {
  77000. /**
  77001. * This is a holder class for the physics joint created by the physics plugin.
  77002. * It holds a set of functions to control the underlying joint.
  77003. */
  77004. var PhysicsJoint = /** @class */ (function () {
  77005. function PhysicsJoint(type, jointData) {
  77006. this.type = type;
  77007. this.jointData = jointData;
  77008. jointData.nativeParams = jointData.nativeParams || {};
  77009. }
  77010. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  77011. get: function () {
  77012. return this._physicsJoint;
  77013. },
  77014. set: function (newJoint) {
  77015. if (this._physicsJoint) {
  77016. //remove from the wolrd
  77017. }
  77018. this._physicsJoint = newJoint;
  77019. },
  77020. enumerable: true,
  77021. configurable: true
  77022. });
  77023. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  77024. set: function (physicsPlugin) {
  77025. this._physicsPlugin = physicsPlugin;
  77026. },
  77027. enumerable: true,
  77028. configurable: true
  77029. });
  77030. /**
  77031. * Execute a function that is physics-plugin specific.
  77032. * @param {Function} func the function that will be executed.
  77033. * It accepts two parameters: the physics world and the physics joint.
  77034. */
  77035. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  77036. func(this._physicsPlugin.world, this._physicsJoint);
  77037. };
  77038. //TODO check if the native joints are the same
  77039. //Joint Types
  77040. PhysicsJoint.DistanceJoint = 0;
  77041. PhysicsJoint.HingeJoint = 1;
  77042. PhysicsJoint.BallAndSocketJoint = 2;
  77043. PhysicsJoint.WheelJoint = 3;
  77044. PhysicsJoint.SliderJoint = 4;
  77045. //OIMO
  77046. PhysicsJoint.PrismaticJoint = 5;
  77047. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  77048. PhysicsJoint.UniversalJoint = 6;
  77049. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  77050. //Cannon
  77051. //Similar to a Ball-Joint. Different in params
  77052. PhysicsJoint.PointToPointJoint = 8;
  77053. //Cannon only at the moment
  77054. PhysicsJoint.SpringJoint = 9;
  77055. PhysicsJoint.LockJoint = 10;
  77056. return PhysicsJoint;
  77057. }());
  77058. BABYLON.PhysicsJoint = PhysicsJoint;
  77059. /**
  77060. * A class representing a physics distance joint.
  77061. */
  77062. var DistanceJoint = /** @class */ (function (_super) {
  77063. __extends(DistanceJoint, _super);
  77064. function DistanceJoint(jointData) {
  77065. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  77066. }
  77067. /**
  77068. * Update the predefined distance.
  77069. */
  77070. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  77071. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  77072. };
  77073. return DistanceJoint;
  77074. }(PhysicsJoint));
  77075. BABYLON.DistanceJoint = DistanceJoint;
  77076. var MotorEnabledJoint = /** @class */ (function (_super) {
  77077. __extends(MotorEnabledJoint, _super);
  77078. function MotorEnabledJoint(type, jointData) {
  77079. return _super.call(this, type, jointData) || this;
  77080. }
  77081. /**
  77082. * Set the motor values.
  77083. * Attention, this function is plugin specific. Engines won't react 100% the same.
  77084. * @param {number} force the force to apply
  77085. * @param {number} maxForce max force for this motor.
  77086. */
  77087. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  77088. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  77089. };
  77090. /**
  77091. * Set the motor's limits.
  77092. * Attention, this function is plugin specific. Engines won't react 100% the same.
  77093. */
  77094. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  77095. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  77096. };
  77097. return MotorEnabledJoint;
  77098. }(PhysicsJoint));
  77099. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  77100. /**
  77101. * This class represents a single hinge physics joint
  77102. */
  77103. var HingeJoint = /** @class */ (function (_super) {
  77104. __extends(HingeJoint, _super);
  77105. function HingeJoint(jointData) {
  77106. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  77107. }
  77108. /**
  77109. * Set the motor values.
  77110. * Attention, this function is plugin specific. Engines won't react 100% the same.
  77111. * @param {number} force the force to apply
  77112. * @param {number} maxForce max force for this motor.
  77113. */
  77114. HingeJoint.prototype.setMotor = function (force, maxForce) {
  77115. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  77116. };
  77117. /**
  77118. * Set the motor's limits.
  77119. * Attention, this function is plugin specific. Engines won't react 100% the same.
  77120. */
  77121. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  77122. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  77123. };
  77124. return HingeJoint;
  77125. }(MotorEnabledJoint));
  77126. BABYLON.HingeJoint = HingeJoint;
  77127. /**
  77128. * This class represents a dual hinge physics joint (same as wheel joint)
  77129. */
  77130. var Hinge2Joint = /** @class */ (function (_super) {
  77131. __extends(Hinge2Joint, _super);
  77132. function Hinge2Joint(jointData) {
  77133. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  77134. }
  77135. /**
  77136. * Set the motor values.
  77137. * Attention, this function is plugin specific. Engines won't react 100% the same.
  77138. * @param {number} force the force to apply
  77139. * @param {number} maxForce max force for this motor.
  77140. * @param {motorIndex} the motor's index, 0 or 1.
  77141. */
  77142. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  77143. if (motorIndex === void 0) { motorIndex = 0; }
  77144. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  77145. };
  77146. /**
  77147. * Set the motor limits.
  77148. * Attention, this function is plugin specific. Engines won't react 100% the same.
  77149. * @param {number} upperLimit the upper limit
  77150. * @param {number} lowerLimit lower limit
  77151. * @param {motorIndex} the motor's index, 0 or 1.
  77152. */
  77153. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  77154. if (motorIndex === void 0) { motorIndex = 0; }
  77155. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  77156. };
  77157. return Hinge2Joint;
  77158. }(MotorEnabledJoint));
  77159. BABYLON.Hinge2Joint = Hinge2Joint;
  77160. })(BABYLON || (BABYLON = {}));
  77161. //# sourceMappingURL=babylon.physicsJoint.js.map
  77162. "use strict";
  77163. var BABYLON;
  77164. (function (BABYLON) {
  77165. var PhysicsImpostor = /** @class */ (function () {
  77166. function PhysicsImpostor(object, type, _options, _scene) {
  77167. if (_options === void 0) { _options = { mass: 0 }; }
  77168. var _this = this;
  77169. this.object = object;
  77170. this.type = type;
  77171. this._options = _options;
  77172. this._scene = _scene;
  77173. this._bodyUpdateRequired = false;
  77174. this._onBeforePhysicsStepCallbacks = new Array();
  77175. this._onAfterPhysicsStepCallbacks = new Array();
  77176. this._onPhysicsCollideCallbacks = [];
  77177. this._deltaPosition = BABYLON.Vector3.Zero();
  77178. this._isDisposed = false;
  77179. //temp variables for parent rotation calculations
  77180. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  77181. this._tmpQuat = new BABYLON.Quaternion();
  77182. this._tmpQuat2 = new BABYLON.Quaternion();
  77183. /**
  77184. * this function is executed by the physics engine.
  77185. */
  77186. this.beforeStep = function () {
  77187. if (!_this._physicsEngine) {
  77188. return;
  77189. }
  77190. _this.object.translate(_this._deltaPosition, -1);
  77191. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  77192. _this.object.computeWorldMatrix(false);
  77193. if (_this.object.parent && _this.object.rotationQuaternion) {
  77194. _this.getParentsRotation();
  77195. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  77196. }
  77197. else {
  77198. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  77199. }
  77200. if (!_this._options.disableBidirectionalTransformation) {
  77201. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  77202. }
  77203. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  77204. func(_this);
  77205. });
  77206. };
  77207. /**
  77208. * this function is executed by the physics engine.
  77209. */
  77210. this.afterStep = function () {
  77211. if (!_this._physicsEngine) {
  77212. return;
  77213. }
  77214. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  77215. func(_this);
  77216. });
  77217. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  77218. // object has now its world rotation. needs to be converted to local.
  77219. if (_this.object.parent && _this.object.rotationQuaternion) {
  77220. _this.getParentsRotation();
  77221. _this._tmpQuat.conjugateInPlace();
  77222. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  77223. }
  77224. // take the position set and make it the absolute position of this object.
  77225. _this.object.setAbsolutePosition(_this.object.position);
  77226. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  77227. _this.object.translate(_this._deltaPosition, 1);
  77228. };
  77229. /**
  77230. * Legacy collision detection event support
  77231. */
  77232. this.onCollideEvent = null;
  77233. //event and body object due to cannon's event-based architecture.
  77234. this.onCollide = function (e) {
  77235. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  77236. return;
  77237. }
  77238. if (!_this._physicsEngine) {
  77239. return;
  77240. }
  77241. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  77242. if (otherImpostor) {
  77243. // Legacy collision detection event support
  77244. if (_this.onCollideEvent) {
  77245. _this.onCollideEvent(_this, otherImpostor);
  77246. }
  77247. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  77248. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  77249. }).forEach(function (obj) {
  77250. obj.callback(_this, otherImpostor);
  77251. });
  77252. }
  77253. };
  77254. //sanity check!
  77255. if (!this.object) {
  77256. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  77257. return;
  77258. }
  77259. //legacy support for old syntax.
  77260. if (!this._scene && object.getScene) {
  77261. this._scene = object.getScene();
  77262. }
  77263. if (!this._scene) {
  77264. return;
  77265. }
  77266. this._physicsEngine = this._scene.getPhysicsEngine();
  77267. if (!this._physicsEngine) {
  77268. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  77269. }
  77270. else {
  77271. //set the object's quaternion, if not set
  77272. if (!this.object.rotationQuaternion) {
  77273. if (this.object.rotation) {
  77274. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  77275. }
  77276. else {
  77277. this.object.rotationQuaternion = new BABYLON.Quaternion();
  77278. }
  77279. }
  77280. //default options params
  77281. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  77282. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  77283. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  77284. this._joints = [];
  77285. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  77286. if (!this.object.parent || this._options.ignoreParent) {
  77287. this._init();
  77288. }
  77289. else if (this.object.parent.physicsImpostor) {
  77290. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  77291. }
  77292. }
  77293. }
  77294. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  77295. get: function () {
  77296. return this._isDisposed;
  77297. },
  77298. enumerable: true,
  77299. configurable: true
  77300. });
  77301. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  77302. get: function () {
  77303. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  77304. },
  77305. set: function (value) {
  77306. this.setMass(value);
  77307. },
  77308. enumerable: true,
  77309. configurable: true
  77310. });
  77311. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  77312. get: function () {
  77313. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  77314. },
  77315. set: function (value) {
  77316. if (!this._physicsEngine) {
  77317. return;
  77318. }
  77319. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  77320. },
  77321. enumerable: true,
  77322. configurable: true
  77323. });
  77324. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  77325. get: function () {
  77326. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  77327. },
  77328. set: function (value) {
  77329. if (!this._physicsEngine) {
  77330. return;
  77331. }
  77332. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  77333. },
  77334. enumerable: true,
  77335. configurable: true
  77336. });
  77337. /**
  77338. * This function will completly initialize this impostor.
  77339. * It will create a new body - but only if this mesh has no parent.
  77340. * If it has, this impostor will not be used other than to define the impostor
  77341. * of the child mesh.
  77342. */
  77343. PhysicsImpostor.prototype._init = function () {
  77344. if (!this._physicsEngine) {
  77345. return;
  77346. }
  77347. this._physicsEngine.removeImpostor(this);
  77348. this.physicsBody = null;
  77349. this._parent = this._parent || this._getPhysicsParent();
  77350. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  77351. this._physicsEngine.addImpostor(this);
  77352. }
  77353. };
  77354. PhysicsImpostor.prototype._getPhysicsParent = function () {
  77355. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  77356. var parentMesh = this.object.parent;
  77357. return parentMesh.physicsImpostor;
  77358. }
  77359. return null;
  77360. };
  77361. /**
  77362. * Should a new body be generated.
  77363. */
  77364. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  77365. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  77366. };
  77367. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  77368. this.forceUpdate();
  77369. };
  77370. /**
  77371. * Force a regeneration of this or the parent's impostor's body.
  77372. * Use under cautious - This will remove all joints already implemented.
  77373. */
  77374. PhysicsImpostor.prototype.forceUpdate = function () {
  77375. this._init();
  77376. if (this.parent && !this._options.ignoreParent) {
  77377. this.parent.forceUpdate();
  77378. }
  77379. };
  77380. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  77381. /*public get mesh(): AbstractMesh {
  77382. return this._mesh;
  77383. }*/
  77384. /**
  77385. * Gets the body that holds this impostor. Either its own, or its parent.
  77386. */
  77387. get: function () {
  77388. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  77389. },
  77390. /**
  77391. * Set the physics body. Used mainly by the physics engine/plugin
  77392. */
  77393. set: function (physicsBody) {
  77394. if (this._physicsBody && this._physicsEngine) {
  77395. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  77396. }
  77397. this._physicsBody = physicsBody;
  77398. this.resetUpdateFlags();
  77399. },
  77400. enumerable: true,
  77401. configurable: true
  77402. });
  77403. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  77404. get: function () {
  77405. return !this._options.ignoreParent && this._parent ? this._parent : null;
  77406. },
  77407. set: function (value) {
  77408. this._parent = value;
  77409. },
  77410. enumerable: true,
  77411. configurable: true
  77412. });
  77413. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  77414. this._bodyUpdateRequired = false;
  77415. };
  77416. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  77417. if (this.object.getBoundingInfo) {
  77418. var q = this.object.rotationQuaternion;
  77419. //reset rotation
  77420. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  77421. //calculate the world matrix with no rotation
  77422. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  77423. var boundingInfo = this.object.getBoundingInfo();
  77424. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  77425. //bring back the rotation
  77426. this.object.rotationQuaternion = q;
  77427. //calculate the world matrix with the new rotation
  77428. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  77429. return size;
  77430. }
  77431. else {
  77432. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  77433. }
  77434. };
  77435. PhysicsImpostor.prototype.getObjectCenter = function () {
  77436. if (this.object.getBoundingInfo) {
  77437. var boundingInfo = this.object.getBoundingInfo();
  77438. return boundingInfo.boundingBox.centerWorld;
  77439. }
  77440. else {
  77441. return this.object.position;
  77442. }
  77443. };
  77444. /**
  77445. * Get a specific parametes from the options parameter.
  77446. */
  77447. PhysicsImpostor.prototype.getParam = function (paramName) {
  77448. return this._options[paramName];
  77449. };
  77450. /**
  77451. * Sets a specific parameter in the options given to the physics plugin
  77452. */
  77453. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  77454. this._options[paramName] = value;
  77455. this._bodyUpdateRequired = true;
  77456. };
  77457. /**
  77458. * Specifically change the body's mass option. Won't recreate the physics body object
  77459. */
  77460. PhysicsImpostor.prototype.setMass = function (mass) {
  77461. if (this.getParam("mass") !== mass) {
  77462. this.setParam("mass", mass);
  77463. }
  77464. if (this._physicsEngine) {
  77465. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  77466. }
  77467. };
  77468. PhysicsImpostor.prototype.getLinearVelocity = function () {
  77469. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  77470. };
  77471. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  77472. if (this._physicsEngine) {
  77473. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  77474. }
  77475. };
  77476. PhysicsImpostor.prototype.getAngularVelocity = function () {
  77477. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  77478. };
  77479. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  77480. if (this._physicsEngine) {
  77481. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  77482. }
  77483. };
  77484. /**
  77485. * Execute a function with the physics plugin native code.
  77486. * Provide a function the will have two variables - the world object and the physics body object.
  77487. */
  77488. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  77489. if (this._physicsEngine) {
  77490. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  77491. }
  77492. };
  77493. /**
  77494. * Register a function that will be executed before the physics world is stepping forward.
  77495. */
  77496. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  77497. this._onBeforePhysicsStepCallbacks.push(func);
  77498. };
  77499. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  77500. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  77501. if (index > -1) {
  77502. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  77503. }
  77504. else {
  77505. BABYLON.Tools.Warn("Function to remove was not found");
  77506. }
  77507. };
  77508. /**
  77509. * Register a function that will be executed after the physics step
  77510. */
  77511. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  77512. this._onAfterPhysicsStepCallbacks.push(func);
  77513. };
  77514. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  77515. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  77516. if (index > -1) {
  77517. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  77518. }
  77519. else {
  77520. BABYLON.Tools.Warn("Function to remove was not found");
  77521. }
  77522. };
  77523. /**
  77524. * register a function that will be executed when this impostor collides against a different body.
  77525. */
  77526. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  77527. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  77528. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  77529. };
  77530. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  77531. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  77532. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  77533. if (index > -1) {
  77534. this._onPhysicsCollideCallbacks.splice(index, 1);
  77535. }
  77536. else {
  77537. BABYLON.Tools.Warn("Function to remove was not found");
  77538. }
  77539. };
  77540. PhysicsImpostor.prototype.getParentsRotation = function () {
  77541. var parent = this.object.parent;
  77542. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  77543. while (parent) {
  77544. if (parent.rotationQuaternion) {
  77545. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  77546. }
  77547. else {
  77548. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  77549. }
  77550. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  77551. parent = parent.parent;
  77552. }
  77553. return this._tmpQuat;
  77554. };
  77555. /**
  77556. * Apply a force
  77557. */
  77558. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  77559. if (this._physicsEngine) {
  77560. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  77561. }
  77562. return this;
  77563. };
  77564. /**
  77565. * Apply an impulse
  77566. */
  77567. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  77568. if (this._physicsEngine) {
  77569. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  77570. }
  77571. return this;
  77572. };
  77573. /**
  77574. * A help function to create a joint.
  77575. */
  77576. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  77577. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  77578. this.addJoint(otherImpostor, joint);
  77579. return this;
  77580. };
  77581. /**
  77582. * Add a joint to this impostor with a different impostor.
  77583. */
  77584. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  77585. this._joints.push({
  77586. otherImpostor: otherImpostor,
  77587. joint: joint
  77588. });
  77589. if (this._physicsEngine) {
  77590. this._physicsEngine.addJoint(this, otherImpostor, joint);
  77591. }
  77592. return this;
  77593. };
  77594. /**
  77595. * Will keep this body still, in a sleep mode.
  77596. */
  77597. PhysicsImpostor.prototype.sleep = function () {
  77598. if (this._physicsEngine) {
  77599. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  77600. }
  77601. return this;
  77602. };
  77603. /**
  77604. * Wake the body up.
  77605. */
  77606. PhysicsImpostor.prototype.wakeUp = function () {
  77607. if (this._physicsEngine) {
  77608. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  77609. }
  77610. return this;
  77611. };
  77612. PhysicsImpostor.prototype.clone = function (newObject) {
  77613. if (!newObject)
  77614. return null;
  77615. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  77616. };
  77617. PhysicsImpostor.prototype.dispose = function () {
  77618. var _this = this;
  77619. //no dispose if no physics engine is available.
  77620. if (!this._physicsEngine) {
  77621. return;
  77622. }
  77623. this._joints.forEach(function (j) {
  77624. if (_this._physicsEngine) {
  77625. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  77626. }
  77627. });
  77628. //dispose the physics body
  77629. this._physicsEngine.removeImpostor(this);
  77630. if (this.parent) {
  77631. this.parent.forceUpdate();
  77632. }
  77633. else {
  77634. /*this._object.getChildMeshes().forEach(function(mesh) {
  77635. if (mesh.physicsImpostor) {
  77636. if (disposeChildren) {
  77637. mesh.physicsImpostor.dispose();
  77638. mesh.physicsImpostor = null;
  77639. }
  77640. }
  77641. })*/
  77642. }
  77643. this._isDisposed = true;
  77644. };
  77645. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  77646. this._deltaPosition.copyFrom(position);
  77647. };
  77648. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  77649. if (!this._deltaRotation) {
  77650. this._deltaRotation = new BABYLON.Quaternion();
  77651. }
  77652. this._deltaRotation.copyFrom(rotation);
  77653. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  77654. };
  77655. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  77656. if (this._physicsEngine) {
  77657. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  77658. }
  77659. return this;
  77660. };
  77661. PhysicsImpostor.prototype.getRadius = function () {
  77662. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  77663. };
  77664. /**
  77665. * Sync a bone with this impostor
  77666. * @param bone The bone to sync to the impostor.
  77667. * @param boneMesh The mesh that the bone is influencing.
  77668. * @param jointPivot The pivot of the joint / bone in local space.
  77669. * @param distToJoint Optional distance from the impostor to the joint.
  77670. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  77671. */
  77672. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  77673. var tempVec = PhysicsImpostor._tmpVecs[0];
  77674. var mesh = this.object;
  77675. if (mesh.rotationQuaternion) {
  77676. if (adjustRotation) {
  77677. var tempQuat = PhysicsImpostor._tmpQuat;
  77678. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  77679. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  77680. }
  77681. else {
  77682. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  77683. }
  77684. }
  77685. tempVec.x = 0;
  77686. tempVec.y = 0;
  77687. tempVec.z = 0;
  77688. if (jointPivot) {
  77689. tempVec.x = jointPivot.x;
  77690. tempVec.y = jointPivot.y;
  77691. tempVec.z = jointPivot.z;
  77692. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  77693. if (distToJoint === undefined || distToJoint === null) {
  77694. distToJoint = jointPivot.length();
  77695. }
  77696. tempVec.x *= distToJoint;
  77697. tempVec.y *= distToJoint;
  77698. tempVec.z *= distToJoint;
  77699. }
  77700. if (bone.getParent()) {
  77701. tempVec.addInPlace(mesh.getAbsolutePosition());
  77702. bone.setAbsolutePosition(tempVec, boneMesh);
  77703. }
  77704. else {
  77705. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  77706. boneMesh.position.x -= tempVec.x;
  77707. boneMesh.position.y -= tempVec.y;
  77708. boneMesh.position.z -= tempVec.z;
  77709. }
  77710. };
  77711. /**
  77712. * Sync impostor to a bone
  77713. * @param bone The bone that the impostor will be synced to.
  77714. * @param boneMesh The mesh that the bone is influencing.
  77715. * @param jointPivot The pivot of the joint / bone in local space.
  77716. * @param distToJoint Optional distance from the impostor to the joint.
  77717. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  77718. * @param boneAxis Optional vector3 axis the bone is aligned with
  77719. */
  77720. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  77721. var mesh = this.object;
  77722. if (mesh.rotationQuaternion) {
  77723. if (adjustRotation) {
  77724. var tempQuat = PhysicsImpostor._tmpQuat;
  77725. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  77726. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  77727. }
  77728. else {
  77729. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  77730. }
  77731. }
  77732. var pos = PhysicsImpostor._tmpVecs[0];
  77733. var boneDir = PhysicsImpostor._tmpVecs[1];
  77734. if (!boneAxis) {
  77735. boneAxis = PhysicsImpostor._tmpVecs[2];
  77736. boneAxis.x = 0;
  77737. boneAxis.y = 1;
  77738. boneAxis.z = 0;
  77739. }
  77740. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  77741. bone.getAbsolutePositionToRef(boneMesh, pos);
  77742. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  77743. distToJoint = jointPivot.length();
  77744. }
  77745. if (distToJoint !== undefined && distToJoint !== null) {
  77746. pos.x += boneDir.x * distToJoint;
  77747. pos.y += boneDir.y * distToJoint;
  77748. pos.z += boneDir.z * distToJoint;
  77749. }
  77750. mesh.setAbsolutePosition(pos);
  77751. };
  77752. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  77753. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  77754. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  77755. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  77756. //Impostor types
  77757. PhysicsImpostor.NoImpostor = 0;
  77758. PhysicsImpostor.SphereImpostor = 1;
  77759. PhysicsImpostor.BoxImpostor = 2;
  77760. PhysicsImpostor.PlaneImpostor = 3;
  77761. PhysicsImpostor.MeshImpostor = 4;
  77762. PhysicsImpostor.CylinderImpostor = 7;
  77763. PhysicsImpostor.ParticleImpostor = 8;
  77764. PhysicsImpostor.HeightmapImpostor = 9;
  77765. return PhysicsImpostor;
  77766. }());
  77767. BABYLON.PhysicsImpostor = PhysicsImpostor;
  77768. })(BABYLON || (BABYLON = {}));
  77769. //# sourceMappingURL=babylon.physicsImpostor.js.map
  77770. "use strict";
  77771. var BABYLON;
  77772. (function (BABYLON) {
  77773. var PhysicsEngine = /** @class */ (function () {
  77774. function PhysicsEngine(gravity, _physicsPlugin) {
  77775. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  77776. this._physicsPlugin = _physicsPlugin;
  77777. //new methods and parameters
  77778. this._impostors = [];
  77779. this._joints = [];
  77780. if (!this._physicsPlugin.isSupported()) {
  77781. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  77782. + "Please make sure it is included.");
  77783. }
  77784. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  77785. this.setGravity(gravity);
  77786. this.setTimeStep();
  77787. }
  77788. PhysicsEngine.prototype.setGravity = function (gravity) {
  77789. this.gravity = gravity;
  77790. this._physicsPlugin.setGravity(this.gravity);
  77791. };
  77792. /**
  77793. * Set the time step of the physics engine.
  77794. * default is 1/60.
  77795. * To slow it down, enter 1/600 for example.
  77796. * To speed it up, 1/30
  77797. * @param {number} newTimeStep the new timestep to apply to this world.
  77798. */
  77799. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  77800. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  77801. this._physicsPlugin.setTimeStep(newTimeStep);
  77802. };
  77803. /**
  77804. * Get the time step of the physics engine.
  77805. */
  77806. PhysicsEngine.prototype.getTimeStep = function () {
  77807. return this._physicsPlugin.getTimeStep();
  77808. };
  77809. PhysicsEngine.prototype.dispose = function () {
  77810. this._impostors.forEach(function (impostor) {
  77811. impostor.dispose();
  77812. });
  77813. this._physicsPlugin.dispose();
  77814. };
  77815. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  77816. return this._physicsPlugin.name;
  77817. };
  77818. /**
  77819. * Adding a new impostor for the impostor tracking.
  77820. * This will be done by the impostor itself.
  77821. * @param {PhysicsImpostor} impostor the impostor to add
  77822. */
  77823. PhysicsEngine.prototype.addImpostor = function (impostor) {
  77824. impostor.uniqueId = this._impostors.push(impostor);
  77825. //if no parent, generate the body
  77826. if (!impostor.parent) {
  77827. this._physicsPlugin.generatePhysicsBody(impostor);
  77828. }
  77829. };
  77830. /**
  77831. * Remove an impostor from the engine.
  77832. * This impostor and its mesh will not longer be updated by the physics engine.
  77833. * @param {PhysicsImpostor} impostor the impostor to remove
  77834. */
  77835. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  77836. var index = this._impostors.indexOf(impostor);
  77837. if (index > -1) {
  77838. var removed = this._impostors.splice(index, 1);
  77839. //Is it needed?
  77840. if (removed.length) {
  77841. //this will also remove it from the world.
  77842. removed[0].physicsBody = null;
  77843. }
  77844. }
  77845. };
  77846. /**
  77847. * Add a joint to the physics engine
  77848. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  77849. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  77850. * @param {PhysicsJoint} the joint that will connect both impostors.
  77851. */
  77852. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  77853. var impostorJoint = {
  77854. mainImpostor: mainImpostor,
  77855. connectedImpostor: connectedImpostor,
  77856. joint: joint
  77857. };
  77858. joint.physicsPlugin = this._physicsPlugin;
  77859. this._joints.push(impostorJoint);
  77860. this._physicsPlugin.generateJoint(impostorJoint);
  77861. };
  77862. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  77863. var matchingJoints = this._joints.filter(function (impostorJoint) {
  77864. return (impostorJoint.connectedImpostor === connectedImpostor
  77865. && impostorJoint.joint === joint
  77866. && impostorJoint.mainImpostor === mainImpostor);
  77867. });
  77868. if (matchingJoints.length) {
  77869. this._physicsPlugin.removeJoint(matchingJoints[0]);
  77870. //TODO remove it from the list as well
  77871. }
  77872. };
  77873. /**
  77874. * Called by the scene. no need to call it.
  77875. */
  77876. PhysicsEngine.prototype._step = function (delta) {
  77877. var _this = this;
  77878. //check if any mesh has no body / requires an update
  77879. this._impostors.forEach(function (impostor) {
  77880. if (impostor.isBodyInitRequired()) {
  77881. _this._physicsPlugin.generatePhysicsBody(impostor);
  77882. }
  77883. });
  77884. if (delta > 0.1) {
  77885. delta = 0.1;
  77886. }
  77887. else if (delta <= 0) {
  77888. delta = 1.0 / 60.0;
  77889. }
  77890. this._physicsPlugin.executeStep(delta, this._impostors);
  77891. };
  77892. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  77893. return this._physicsPlugin;
  77894. };
  77895. PhysicsEngine.prototype.getImpostors = function () {
  77896. return this._impostors;
  77897. };
  77898. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  77899. for (var i = 0; i < this._impostors.length; ++i) {
  77900. if (this._impostors[i].object === object) {
  77901. return this._impostors[i];
  77902. }
  77903. }
  77904. return null;
  77905. };
  77906. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  77907. for (var i = 0; i < this._impostors.length; ++i) {
  77908. if (this._impostors[i].physicsBody === body) {
  77909. return this._impostors[i];
  77910. }
  77911. }
  77912. return null;
  77913. };
  77914. // Statics
  77915. PhysicsEngine.Epsilon = 0.001;
  77916. return PhysicsEngine;
  77917. }());
  77918. BABYLON.PhysicsEngine = PhysicsEngine;
  77919. })(BABYLON || (BABYLON = {}));
  77920. //# sourceMappingURL=babylon.physicsEngine.js.map
  77921. "use strict";
  77922. var BABYLON;
  77923. (function (BABYLON) {
  77924. var PhysicsHelper = /** @class */ (function () {
  77925. function PhysicsHelper(scene) {
  77926. this._scene = scene;
  77927. this._physicsEngine = this._scene.getPhysicsEngine();
  77928. if (!this._physicsEngine) {
  77929. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  77930. }
  77931. }
  77932. /**
  77933. * @param {Vector3} origin the origin of the explosion
  77934. * @param {number} radius the explosion radius
  77935. * @param {number} strength the explosion strength
  77936. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  77937. */
  77938. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  77939. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  77940. if (!this._physicsEngine) {
  77941. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  77942. return null;
  77943. }
  77944. var impostors = this._physicsEngine.getImpostors();
  77945. if (impostors.length === 0) {
  77946. return null;
  77947. }
  77948. var event = new PhysicsRadialExplosionEvent(this._scene);
  77949. impostors.forEach(function (impostor) {
  77950. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  77951. if (!impostorForceAndContactPoint) {
  77952. return;
  77953. }
  77954. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  77955. });
  77956. event.dispose(false);
  77957. return event;
  77958. };
  77959. /**
  77960. * @param {Vector3} origin the origin of the explosion
  77961. * @param {number} radius the explosion radius
  77962. * @param {number} strength the explosion strength
  77963. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  77964. */
  77965. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  77966. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  77967. if (!this._physicsEngine) {
  77968. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  77969. return null;
  77970. }
  77971. var impostors = this._physicsEngine.getImpostors();
  77972. if (impostors.length === 0) {
  77973. return null;
  77974. }
  77975. var event = new PhysicsRadialExplosionEvent(this._scene);
  77976. impostors.forEach(function (impostor) {
  77977. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  77978. if (!impostorForceAndContactPoint) {
  77979. return;
  77980. }
  77981. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  77982. });
  77983. event.dispose(false);
  77984. return event;
  77985. };
  77986. /**
  77987. * @param {Vector3} origin the origin of the explosion
  77988. * @param {number} radius the explosion radius
  77989. * @param {number} strength the explosion strength
  77990. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  77991. */
  77992. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  77993. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  77994. if (!this._physicsEngine) {
  77995. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  77996. return null;
  77997. }
  77998. var impostors = this._physicsEngine.getImpostors();
  77999. if (impostors.length === 0) {
  78000. return null;
  78001. }
  78002. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  78003. event.dispose(false);
  78004. return event;
  78005. };
  78006. /**
  78007. * @param {Vector3} origin the origin of the updraft
  78008. * @param {number} radius the radius of the updraft
  78009. * @param {number} strength the strength of the updraft
  78010. * @param {number} height the height of the updraft
  78011. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  78012. */
  78013. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  78014. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  78015. if (!this._physicsEngine) {
  78016. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  78017. return null;
  78018. }
  78019. if (this._physicsEngine.getImpostors().length === 0) {
  78020. return null;
  78021. }
  78022. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  78023. event.dispose(false);
  78024. return event;
  78025. };
  78026. /**
  78027. * @param {Vector3} origin the of the vortex
  78028. * @param {number} radius the radius of the vortex
  78029. * @param {number} strength the strength of the vortex
  78030. * @param {number} height the height of the vortex
  78031. */
  78032. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  78033. if (!this._physicsEngine) {
  78034. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  78035. return null;
  78036. }
  78037. if (this._physicsEngine.getImpostors().length === 0) {
  78038. return null;
  78039. }
  78040. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  78041. event.dispose(false);
  78042. return event;
  78043. };
  78044. return PhysicsHelper;
  78045. }());
  78046. BABYLON.PhysicsHelper = PhysicsHelper;
  78047. /***** Radial explosion *****/
  78048. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  78049. function PhysicsRadialExplosionEvent(scene) {
  78050. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  78051. this._rays = [];
  78052. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  78053. this._scene = scene;
  78054. }
  78055. /**
  78056. * Returns the data related to the radial explosion event (sphere & rays).
  78057. * @returns {PhysicsRadialExplosionEventData}
  78058. */
  78059. PhysicsRadialExplosionEvent.prototype.getData = function () {
  78060. this._dataFetched = true;
  78061. return {
  78062. sphere: this._sphere,
  78063. rays: this._rays,
  78064. };
  78065. };
  78066. /**
  78067. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  78068. * @param impostor
  78069. * @param {Vector3} origin the origin of the explosion
  78070. * @param {number} radius the explosion radius
  78071. * @param {number} strength the explosion strength
  78072. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  78073. * @returns {Nullable<PhysicsForceAndContactPoint>}
  78074. */
  78075. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  78076. if (impostor.mass === 0) {
  78077. return null;
  78078. }
  78079. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  78080. return null;
  78081. }
  78082. if (impostor.object.getClassName() !== 'Mesh') {
  78083. return null;
  78084. }
  78085. var impostorObject = impostor.object;
  78086. var impostorObjectCenter = impostor.getObjectCenter();
  78087. var direction = impostorObjectCenter.subtract(origin);
  78088. var ray = new BABYLON.Ray(origin, direction, radius);
  78089. this._rays.push(ray);
  78090. var hit = ray.intersectsMesh(impostorObject);
  78091. var contactPoint = hit.pickedPoint;
  78092. if (!contactPoint) {
  78093. return null;
  78094. }
  78095. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  78096. if (distanceFromOrigin > radius) {
  78097. return null;
  78098. }
  78099. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  78100. ? strength
  78101. : strength * (1 - (distanceFromOrigin / radius));
  78102. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  78103. return { force: force, contactPoint: contactPoint };
  78104. };
  78105. /**
  78106. * Disposes the sphere.
  78107. * @param {bolean} force
  78108. */
  78109. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  78110. var _this = this;
  78111. if (force === void 0) { force = true; }
  78112. if (force) {
  78113. this._sphere.dispose();
  78114. }
  78115. else {
  78116. setTimeout(function () {
  78117. if (!_this._dataFetched) {
  78118. _this._sphere.dispose();
  78119. }
  78120. }, 0);
  78121. }
  78122. };
  78123. /*** Helpers ***/
  78124. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  78125. if (!this._sphere) {
  78126. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  78127. this._sphere.isVisible = false;
  78128. }
  78129. };
  78130. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  78131. var impostorObject = impostor.object;
  78132. this._prepareSphere();
  78133. this._sphere.position = origin;
  78134. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  78135. this._sphere._updateBoundingInfo();
  78136. this._sphere.computeWorldMatrix(true);
  78137. return this._sphere.intersectsMesh(impostorObject, true);
  78138. };
  78139. return PhysicsRadialExplosionEvent;
  78140. }());
  78141. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  78142. /***** Gravitational Field *****/
  78143. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  78144. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  78145. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  78146. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  78147. this._physicsHelper = physicsHelper;
  78148. this._scene = scene;
  78149. this._origin = origin;
  78150. this._radius = radius;
  78151. this._strength = strength;
  78152. this._falloff = falloff;
  78153. this._tickCallback = this._tick.bind(this);
  78154. }
  78155. /**
  78156. * Returns the data related to the gravitational field event (sphere).
  78157. * @returns {PhysicsGravitationalFieldEventData}
  78158. */
  78159. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  78160. this._dataFetched = true;
  78161. return {
  78162. sphere: this._sphere,
  78163. };
  78164. };
  78165. /**
  78166. * Enables the gravitational field.
  78167. */
  78168. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  78169. this._tickCallback.call(this);
  78170. this._scene.registerBeforeRender(this._tickCallback);
  78171. };
  78172. /**
  78173. * Disables the gravitational field.
  78174. */
  78175. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  78176. this._scene.unregisterBeforeRender(this._tickCallback);
  78177. };
  78178. /**
  78179. * Disposes the sphere.
  78180. * @param {bolean} force
  78181. */
  78182. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  78183. var _this = this;
  78184. if (force === void 0) { force = true; }
  78185. if (force) {
  78186. this._sphere.dispose();
  78187. }
  78188. else {
  78189. setTimeout(function () {
  78190. if (!_this._dataFetched) {
  78191. _this._sphere.dispose();
  78192. }
  78193. }, 0);
  78194. }
  78195. };
  78196. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  78197. // Since the params won't change, we fetch the event only once
  78198. if (this._sphere) {
  78199. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  78200. }
  78201. else {
  78202. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  78203. if (radialExplosionEvent) {
  78204. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  78205. }
  78206. }
  78207. };
  78208. return PhysicsGravitationalFieldEvent;
  78209. }());
  78210. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  78211. /***** Updraft *****/
  78212. var PhysicsUpdraftEvent = /** @class */ (function () {
  78213. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  78214. this._scene = _scene;
  78215. this._origin = _origin;
  78216. this._radius = _radius;
  78217. this._strength = _strength;
  78218. this._height = _height;
  78219. this._updraftMode = _updraftMode;
  78220. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  78221. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  78222. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  78223. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  78224. this._physicsEngine = this._scene.getPhysicsEngine();
  78225. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  78226. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  78227. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  78228. this._originDirection = this._origin.subtract(this._originTop).normalize();
  78229. }
  78230. this._tickCallback = this._tick.bind(this);
  78231. }
  78232. /**
  78233. * Returns the data related to the updraft event (cylinder).
  78234. * @returns {PhysicsUpdraftEventData}
  78235. */
  78236. PhysicsUpdraftEvent.prototype.getData = function () {
  78237. this._dataFetched = true;
  78238. return {
  78239. cylinder: this._cylinder,
  78240. };
  78241. };
  78242. /**
  78243. * Enables the updraft.
  78244. */
  78245. PhysicsUpdraftEvent.prototype.enable = function () {
  78246. this._tickCallback.call(this);
  78247. this._scene.registerBeforeRender(this._tickCallback);
  78248. };
  78249. /**
  78250. * Disables the cortex.
  78251. */
  78252. PhysicsUpdraftEvent.prototype.disable = function () {
  78253. this._scene.unregisterBeforeRender(this._tickCallback);
  78254. };
  78255. /**
  78256. * Disposes the sphere.
  78257. * @param {bolean} force
  78258. */
  78259. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  78260. var _this = this;
  78261. if (force === void 0) { force = true; }
  78262. if (force) {
  78263. this._cylinder.dispose();
  78264. }
  78265. else {
  78266. setTimeout(function () {
  78267. if (!_this._dataFetched) {
  78268. _this._cylinder.dispose();
  78269. }
  78270. }, 0);
  78271. }
  78272. };
  78273. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  78274. if (impostor.mass === 0) {
  78275. return null;
  78276. }
  78277. if (!this._intersectsWithCylinder(impostor)) {
  78278. return null;
  78279. }
  78280. var impostorObjectCenter = impostor.getObjectCenter();
  78281. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  78282. var direction = this._originDirection;
  78283. }
  78284. else {
  78285. var direction = impostorObjectCenter.subtract(this._originTop);
  78286. }
  78287. var multiplier = this._strength * -1;
  78288. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  78289. return { force: force, contactPoint: impostorObjectCenter };
  78290. };
  78291. PhysicsUpdraftEvent.prototype._tick = function () {
  78292. var _this = this;
  78293. this._physicsEngine.getImpostors().forEach(function (impostor) {
  78294. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  78295. if (!impostorForceAndContactPoint) {
  78296. return;
  78297. }
  78298. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  78299. });
  78300. };
  78301. /*** Helpers ***/
  78302. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  78303. if (!this._cylinder) {
  78304. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  78305. height: this._height,
  78306. diameter: this._radius * 2,
  78307. }, this._scene);
  78308. this._cylinder.isVisible = false;
  78309. }
  78310. };
  78311. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  78312. var impostorObject = impostor.object;
  78313. this._prepareCylinder();
  78314. this._cylinder.position = this._cylinderPosition;
  78315. return this._cylinder.intersectsMesh(impostorObject, true);
  78316. };
  78317. return PhysicsUpdraftEvent;
  78318. }());
  78319. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  78320. /***** Vortex *****/
  78321. var PhysicsVortexEvent = /** @class */ (function () {
  78322. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  78323. this._scene = _scene;
  78324. this._origin = _origin;
  78325. this._radius = _radius;
  78326. this._strength = _strength;
  78327. this._height = _height;
  78328. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  78329. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  78330. this._updraftMultiplier = 0.02;
  78331. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  78332. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  78333. this._physicsEngine = this._scene.getPhysicsEngine();
  78334. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  78335. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  78336. this._tickCallback = this._tick.bind(this);
  78337. }
  78338. /**
  78339. * Returns the data related to the vortex event (cylinder).
  78340. * @returns {PhysicsVortexEventData}
  78341. */
  78342. PhysicsVortexEvent.prototype.getData = function () {
  78343. this._dataFetched = true;
  78344. return {
  78345. cylinder: this._cylinder,
  78346. };
  78347. };
  78348. /**
  78349. * Enables the vortex.
  78350. */
  78351. PhysicsVortexEvent.prototype.enable = function () {
  78352. this._tickCallback.call(this);
  78353. this._scene.registerBeforeRender(this._tickCallback);
  78354. };
  78355. /**
  78356. * Disables the cortex.
  78357. */
  78358. PhysicsVortexEvent.prototype.disable = function () {
  78359. this._scene.unregisterBeforeRender(this._tickCallback);
  78360. };
  78361. /**
  78362. * Disposes the sphere.
  78363. * @param {bolean} force
  78364. */
  78365. PhysicsVortexEvent.prototype.dispose = function (force) {
  78366. var _this = this;
  78367. if (force === void 0) { force = true; }
  78368. if (force) {
  78369. this._cylinder.dispose();
  78370. }
  78371. else {
  78372. setTimeout(function () {
  78373. if (!_this._dataFetched) {
  78374. _this._cylinder.dispose();
  78375. }
  78376. }, 0);
  78377. }
  78378. };
  78379. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  78380. if (impostor.mass === 0) {
  78381. return null;
  78382. }
  78383. if (!this._intersectsWithCylinder(impostor)) {
  78384. return null;
  78385. }
  78386. if (impostor.object.getClassName() !== 'Mesh') {
  78387. return null;
  78388. }
  78389. var impostorObject = impostor.object;
  78390. var impostorObjectCenter = impostor.getObjectCenter();
  78391. 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)
  78392. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  78393. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  78394. var hit = ray.intersectsMesh(impostorObject);
  78395. var contactPoint = hit.pickedPoint;
  78396. if (!contactPoint) {
  78397. return null;
  78398. }
  78399. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  78400. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  78401. var directionToOrigin = contactPoint.normalize();
  78402. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  78403. directionToOrigin = directionToOrigin.negate();
  78404. }
  78405. // TODO: find a more physically based solution
  78406. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  78407. var forceX = directionToOrigin.x * this._strength / 8;
  78408. var forceY = directionToOrigin.y * this._updraftMultiplier;
  78409. var forceZ = directionToOrigin.z * this._strength / 8;
  78410. }
  78411. else {
  78412. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  78413. var forceY = this._originTop.y * this._updraftMultiplier;
  78414. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  78415. }
  78416. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  78417. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  78418. return { force: force, contactPoint: impostorObjectCenter };
  78419. };
  78420. PhysicsVortexEvent.prototype._tick = function () {
  78421. var _this = this;
  78422. this._physicsEngine.getImpostors().forEach(function (impostor) {
  78423. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  78424. if (!impostorForceAndContactPoint) {
  78425. return;
  78426. }
  78427. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  78428. });
  78429. };
  78430. /*** Helpers ***/
  78431. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  78432. if (!this._cylinder) {
  78433. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  78434. height: this._height,
  78435. diameter: this._radius * 2,
  78436. }, this._scene);
  78437. this._cylinder.isVisible = false;
  78438. }
  78439. };
  78440. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  78441. var impostorObject = impostor.object;
  78442. this._prepareCylinder();
  78443. this._cylinder.position = this._cylinderPosition;
  78444. return this._cylinder.intersectsMesh(impostorObject, true);
  78445. };
  78446. return PhysicsVortexEvent;
  78447. }());
  78448. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  78449. /***** Enums *****/
  78450. /**
  78451. * The strenght of the force in correspondence to the distance of the affected object
  78452. */
  78453. var PhysicsRadialImpulseFalloff;
  78454. (function (PhysicsRadialImpulseFalloff) {
  78455. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  78456. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  78457. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  78458. /**
  78459. * The strenght of the force in correspondence to the distance of the affected object
  78460. */
  78461. var PhysicsUpdraftMode;
  78462. (function (PhysicsUpdraftMode) {
  78463. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  78464. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; // once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder
  78465. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  78466. })(BABYLON || (BABYLON = {}));
  78467. //# sourceMappingURL=babylon.physicsHelper.js.map
  78468. "use strict";
  78469. var BABYLON;
  78470. (function (BABYLON) {
  78471. var CannonJSPlugin = /** @class */ (function () {
  78472. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  78473. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  78474. if (iterations === void 0) { iterations = 10; }
  78475. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  78476. this.name = "CannonJSPlugin";
  78477. this._physicsMaterials = new Array();
  78478. this._fixedTimeStep = 1 / 60;
  78479. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  78480. this.BJSCANNON = CANNON;
  78481. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  78482. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  78483. this._tmpPosition = BABYLON.Vector3.Zero();
  78484. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  78485. this._tmpUnityRotation = new BABYLON.Quaternion();
  78486. if (!this.isSupported()) {
  78487. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  78488. return;
  78489. }
  78490. this._extendNamespace();
  78491. this.world = new this.BJSCANNON.World();
  78492. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  78493. this.world.solver.iterations = iterations;
  78494. }
  78495. CannonJSPlugin.prototype.setGravity = function (gravity) {
  78496. this.world.gravity.copy(gravity);
  78497. };
  78498. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  78499. this._fixedTimeStep = timeStep;
  78500. };
  78501. CannonJSPlugin.prototype.getTimeStep = function () {
  78502. return this._fixedTimeStep;
  78503. };
  78504. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  78505. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  78506. };
  78507. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  78508. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  78509. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  78510. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  78511. };
  78512. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  78513. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  78514. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  78515. impostor.physicsBody.applyForce(impulse, worldPoint);
  78516. };
  78517. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  78518. //parent-child relationship. Does this impostor has a parent impostor?
  78519. if (impostor.parent) {
  78520. if (impostor.physicsBody) {
  78521. this.removePhysicsBody(impostor);
  78522. //TODO is that needed?
  78523. impostor.forceUpdate();
  78524. }
  78525. return;
  78526. }
  78527. //should a new body be created for this impostor?
  78528. if (impostor.isBodyInitRequired()) {
  78529. var shape = this._createShape(impostor);
  78530. //unregister events, if body is being changed
  78531. var oldBody = impostor.physicsBody;
  78532. if (oldBody) {
  78533. this.removePhysicsBody(impostor);
  78534. }
  78535. //create the body and material
  78536. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  78537. var bodyCreationObject = {
  78538. mass: impostor.getParam("mass"),
  78539. material: material
  78540. };
  78541. // A simple extend, in case native options were used.
  78542. var nativeOptions = impostor.getParam("nativeOptions");
  78543. for (var key in nativeOptions) {
  78544. if (nativeOptions.hasOwnProperty(key)) {
  78545. bodyCreationObject[key] = nativeOptions[key];
  78546. }
  78547. }
  78548. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  78549. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  78550. this.world.addEventListener("preStep", impostor.beforeStep);
  78551. this.world.addEventListener("postStep", impostor.afterStep);
  78552. impostor.physicsBody.addShape(shape);
  78553. this.world.add(impostor.physicsBody);
  78554. //try to keep the body moving in the right direction by taking old properties.
  78555. //Should be tested!
  78556. if (oldBody) {
  78557. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  78558. impostor.physicsBody[param].copy(oldBody[param]);
  78559. });
  78560. }
  78561. this._processChildMeshes(impostor);
  78562. }
  78563. //now update the body's transformation
  78564. this._updatePhysicsBodyTransformation(impostor);
  78565. };
  78566. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  78567. var _this = this;
  78568. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  78569. var currentRotation = mainImpostor.object.rotationQuaternion;
  78570. if (meshChildren.length) {
  78571. var processMesh = function (localPosition, mesh) {
  78572. if (!currentRotation || !mesh.rotationQuaternion) {
  78573. return;
  78574. }
  78575. var childImpostor = mesh.getPhysicsImpostor();
  78576. if (childImpostor) {
  78577. var parent = childImpostor.parent;
  78578. if (parent !== mainImpostor) {
  78579. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  78580. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  78581. if (childImpostor.physicsBody) {
  78582. _this.removePhysicsBody(childImpostor);
  78583. childImpostor.physicsBody = null;
  78584. }
  78585. childImpostor.parent = mainImpostor;
  78586. childImpostor.resetUpdateFlags();
  78587. 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));
  78588. //Add the mass of the children.
  78589. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  78590. }
  78591. }
  78592. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  78593. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  78594. };
  78595. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  78596. }
  78597. };
  78598. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  78599. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  78600. this.world.removeEventListener("preStep", impostor.beforeStep);
  78601. this.world.removeEventListener("postStep", impostor.afterStep);
  78602. this.world.remove(impostor.physicsBody);
  78603. };
  78604. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  78605. var mainBody = impostorJoint.mainImpostor.physicsBody;
  78606. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  78607. if (!mainBody || !connectedBody) {
  78608. return;
  78609. }
  78610. var constraint;
  78611. var jointData = impostorJoint.joint.jointData;
  78612. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  78613. var constraintData = {
  78614. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  78615. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  78616. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  78617. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  78618. maxForce: jointData.nativeParams.maxForce,
  78619. collideConnected: !!jointData.collision
  78620. };
  78621. switch (impostorJoint.joint.type) {
  78622. case BABYLON.PhysicsJoint.HingeJoint:
  78623. case BABYLON.PhysicsJoint.Hinge2Joint:
  78624. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  78625. break;
  78626. case BABYLON.PhysicsJoint.DistanceJoint:
  78627. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  78628. break;
  78629. case BABYLON.PhysicsJoint.SpringJoint:
  78630. var springData = jointData;
  78631. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  78632. restLength: springData.length,
  78633. stiffness: springData.stiffness,
  78634. damping: springData.damping,
  78635. localAnchorA: constraintData.pivotA,
  78636. localAnchorB: constraintData.pivotB
  78637. });
  78638. break;
  78639. case BABYLON.PhysicsJoint.LockJoint:
  78640. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  78641. break;
  78642. case BABYLON.PhysicsJoint.PointToPointJoint:
  78643. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  78644. default:
  78645. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  78646. break;
  78647. }
  78648. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  78649. constraint.collideConnected = !!jointData.collision;
  78650. impostorJoint.joint.physicsJoint = constraint;
  78651. //don't add spring as constraint, as it is not one.
  78652. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  78653. this.world.addConstraint(constraint);
  78654. }
  78655. else {
  78656. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  78657. constraint.applyForce();
  78658. });
  78659. }
  78660. };
  78661. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  78662. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  78663. };
  78664. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  78665. var index;
  78666. var mat;
  78667. for (index = 0; index < this._physicsMaterials.length; index++) {
  78668. mat = this._physicsMaterials[index];
  78669. if (mat.friction === friction && mat.restitution === restitution) {
  78670. return mat;
  78671. }
  78672. }
  78673. var currentMat = new this.BJSCANNON.Material(name);
  78674. currentMat.friction = friction;
  78675. currentMat.restitution = restitution;
  78676. this._physicsMaterials.push(currentMat);
  78677. return currentMat;
  78678. };
  78679. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  78680. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  78681. };
  78682. CannonJSPlugin.prototype._createShape = function (impostor) {
  78683. var object = impostor.object;
  78684. var returnValue;
  78685. var extendSize = impostor.getObjectExtendSize();
  78686. switch (impostor.type) {
  78687. case BABYLON.PhysicsImpostor.SphereImpostor:
  78688. var radiusX = extendSize.x;
  78689. var radiusY = extendSize.y;
  78690. var radiusZ = extendSize.z;
  78691. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  78692. break;
  78693. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  78694. case BABYLON.PhysicsImpostor.CylinderImpostor:
  78695. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  78696. break;
  78697. case BABYLON.PhysicsImpostor.BoxImpostor:
  78698. var box = extendSize.scale(0.5);
  78699. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  78700. break;
  78701. case BABYLON.PhysicsImpostor.PlaneImpostor:
  78702. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  78703. returnValue = new this.BJSCANNON.Plane();
  78704. break;
  78705. case BABYLON.PhysicsImpostor.MeshImpostor:
  78706. // should transform the vertex data to world coordinates!!
  78707. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  78708. var rawFaces = object.getIndices ? object.getIndices() : [];
  78709. if (!rawVerts)
  78710. return;
  78711. // get only scale! so the object could transform correctly.
  78712. var oldPosition = object.position.clone();
  78713. var oldRotation = object.rotation && object.rotation.clone();
  78714. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  78715. object.position.copyFromFloats(0, 0, 0);
  78716. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  78717. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  78718. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  78719. var transform = object.computeWorldMatrix(true);
  78720. // convert rawVerts to object space
  78721. var temp = new Array();
  78722. var index;
  78723. for (index = 0; index < rawVerts.length; index += 3) {
  78724. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  78725. }
  78726. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  78727. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  78728. //now set back the transformation!
  78729. object.position.copyFrom(oldPosition);
  78730. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  78731. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  78732. break;
  78733. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  78734. var oldPosition2 = object.position.clone();
  78735. var oldRotation2 = object.rotation && object.rotation.clone();
  78736. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  78737. object.position.copyFromFloats(0, 0, 0);
  78738. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  78739. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  78740. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  78741. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  78742. returnValue = this._createHeightmap(object);
  78743. object.position.copyFrom(oldPosition2);
  78744. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  78745. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  78746. object.computeWorldMatrix(true);
  78747. break;
  78748. case BABYLON.PhysicsImpostor.ParticleImpostor:
  78749. returnValue = new this.BJSCANNON.Particle();
  78750. break;
  78751. }
  78752. return returnValue;
  78753. };
  78754. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  78755. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  78756. var transform = object.computeWorldMatrix(true);
  78757. // convert rawVerts to object space
  78758. var temp = new Array();
  78759. var index;
  78760. for (index = 0; index < pos.length; index += 3) {
  78761. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  78762. }
  78763. pos = temp;
  78764. var matrix = new Array();
  78765. //For now pointDepth will not be used and will be automatically calculated.
  78766. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  78767. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  78768. var boundingInfo = object.getBoundingInfo();
  78769. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  78770. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  78771. var elementSize = dim * 2 / arraySize;
  78772. for (var i = 0; i < pos.length; i = i + 3) {
  78773. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  78774. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  78775. var y = -pos[i + 2] + minY;
  78776. if (!matrix[x]) {
  78777. matrix[x] = [];
  78778. }
  78779. if (!matrix[x][z]) {
  78780. matrix[x][z] = y;
  78781. }
  78782. matrix[x][z] = Math.max(y, matrix[x][z]);
  78783. }
  78784. for (var x = 0; x <= arraySize; ++x) {
  78785. if (!matrix[x]) {
  78786. var loc = 1;
  78787. while (!matrix[(x + loc) % arraySize]) {
  78788. loc++;
  78789. }
  78790. matrix[x] = matrix[(x + loc) % arraySize].slice();
  78791. //console.log("missing x", x);
  78792. }
  78793. for (var z = 0; z <= arraySize; ++z) {
  78794. if (!matrix[x][z]) {
  78795. var loc = 1;
  78796. var newValue;
  78797. while (newValue === undefined) {
  78798. newValue = matrix[x][(z + loc++) % arraySize];
  78799. }
  78800. matrix[x][z] = newValue;
  78801. }
  78802. }
  78803. }
  78804. var shape = new this.BJSCANNON.Heightfield(matrix, {
  78805. elementSize: elementSize
  78806. });
  78807. //For future reference, needed for body transformation
  78808. shape.minY = minY;
  78809. return shape;
  78810. };
  78811. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  78812. var object = impostor.object;
  78813. //make sure it is updated...
  78814. object.computeWorldMatrix && object.computeWorldMatrix(true);
  78815. // The delta between the mesh position and the mesh bounding box center
  78816. var bInfo = object.getBoundingInfo();
  78817. if (!bInfo)
  78818. return;
  78819. var center = impostor.getObjectCenter();
  78820. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  78821. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  78822. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  78823. this._tmpPosition.copyFrom(center);
  78824. var quaternion = object.rotationQuaternion;
  78825. if (!quaternion) {
  78826. return;
  78827. }
  78828. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  78829. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  78830. //-90 DEG in X, precalculated
  78831. quaternion = quaternion.multiply(this._minus90X);
  78832. //Invert! (Precalculated, 90 deg in X)
  78833. //No need to clone. this will never change.
  78834. impostor.setDeltaRotation(this._plus90X);
  78835. }
  78836. //If it is a heightfield, if should be centered.
  78837. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  78838. var mesh = object;
  78839. var boundingInfo = mesh.getBoundingInfo();
  78840. //calculate the correct body position:
  78841. var rotationQuaternion = mesh.rotationQuaternion;
  78842. mesh.rotationQuaternion = this._tmpUnityRotation;
  78843. mesh.computeWorldMatrix(true);
  78844. //get original center with no rotation
  78845. var c = center.clone();
  78846. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  78847. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  78848. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  78849. mesh.setPreTransformMatrix(p);
  78850. mesh.computeWorldMatrix(true);
  78851. //calculate the translation
  78852. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  78853. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  78854. //add it inverted to the delta
  78855. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  78856. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  78857. //rotation is back
  78858. mesh.rotationQuaternion = rotationQuaternion;
  78859. mesh.setPreTransformMatrix(oldPivot);
  78860. mesh.computeWorldMatrix(true);
  78861. }
  78862. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  78863. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  78864. //this._tmpPosition.copyFrom(object.position);
  78865. }
  78866. impostor.setDeltaPosition(this._tmpDeltaPosition);
  78867. //Now update the impostor object
  78868. impostor.physicsBody.position.copy(this._tmpPosition);
  78869. impostor.physicsBody.quaternion.copy(quaternion);
  78870. };
  78871. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  78872. impostor.object.position.copyFrom(impostor.physicsBody.position);
  78873. if (impostor.object.rotationQuaternion) {
  78874. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  78875. }
  78876. };
  78877. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  78878. impostor.physicsBody.position.copy(newPosition);
  78879. impostor.physicsBody.quaternion.copy(newRotation);
  78880. };
  78881. CannonJSPlugin.prototype.isSupported = function () {
  78882. return this.BJSCANNON !== undefined;
  78883. };
  78884. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  78885. impostor.physicsBody.velocity.copy(velocity);
  78886. };
  78887. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  78888. impostor.physicsBody.angularVelocity.copy(velocity);
  78889. };
  78890. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  78891. var v = impostor.physicsBody.velocity;
  78892. if (!v) {
  78893. return null;
  78894. }
  78895. return new BABYLON.Vector3(v.x, v.y, v.z);
  78896. };
  78897. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  78898. var v = impostor.physicsBody.angularVelocity;
  78899. if (!v) {
  78900. return null;
  78901. }
  78902. return new BABYLON.Vector3(v.x, v.y, v.z);
  78903. };
  78904. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  78905. impostor.physicsBody.mass = mass;
  78906. impostor.physicsBody.updateMassProperties();
  78907. };
  78908. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  78909. return impostor.physicsBody.mass;
  78910. };
  78911. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  78912. return impostor.physicsBody.material.friction;
  78913. };
  78914. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  78915. impostor.physicsBody.material.friction = friction;
  78916. };
  78917. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  78918. return impostor.physicsBody.material.restitution;
  78919. };
  78920. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  78921. impostor.physicsBody.material.restitution = restitution;
  78922. };
  78923. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  78924. impostor.physicsBody.sleep();
  78925. };
  78926. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  78927. impostor.physicsBody.wakeUp();
  78928. };
  78929. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  78930. joint.physicsJoint.distance = maxDistance;
  78931. };
  78932. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  78933. // if (!motorIndex) {
  78934. // joint.physicsJoint.enableMotor();
  78935. // }
  78936. // }
  78937. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  78938. // if (!motorIndex) {
  78939. // joint.physicsJoint.disableMotor();
  78940. // }
  78941. // }
  78942. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  78943. if (!motorIndex) {
  78944. joint.physicsJoint.enableMotor();
  78945. joint.physicsJoint.setMotorSpeed(speed);
  78946. if (maxForce) {
  78947. this.setLimit(joint, maxForce);
  78948. }
  78949. }
  78950. };
  78951. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  78952. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  78953. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  78954. };
  78955. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  78956. var body = impostor.physicsBody;
  78957. mesh.position.x = body.position.x;
  78958. mesh.position.y = body.position.y;
  78959. mesh.position.z = body.position.z;
  78960. if (mesh.rotationQuaternion) {
  78961. mesh.rotationQuaternion.x = body.quaternion.x;
  78962. mesh.rotationQuaternion.y = body.quaternion.y;
  78963. mesh.rotationQuaternion.z = body.quaternion.z;
  78964. mesh.rotationQuaternion.w = body.quaternion.w;
  78965. }
  78966. };
  78967. CannonJSPlugin.prototype.getRadius = function (impostor) {
  78968. var shape = impostor.physicsBody.shapes[0];
  78969. return shape.boundingSphereRadius;
  78970. };
  78971. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  78972. var shape = impostor.physicsBody.shapes[0];
  78973. result.x = shape.halfExtents.x * 2;
  78974. result.y = shape.halfExtents.y * 2;
  78975. result.z = shape.halfExtents.z * 2;
  78976. };
  78977. CannonJSPlugin.prototype.dispose = function () {
  78978. };
  78979. CannonJSPlugin.prototype._extendNamespace = function () {
  78980. //this will force cannon to execute at least one step when using interpolation
  78981. var step_tmp1 = new this.BJSCANNON.Vec3();
  78982. var Engine = this.BJSCANNON;
  78983. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  78984. maxSubSteps = maxSubSteps || 10;
  78985. timeSinceLastCalled = timeSinceLastCalled || 0;
  78986. if (timeSinceLastCalled === 0) {
  78987. this.internalStep(dt);
  78988. this.time += dt;
  78989. }
  78990. else {
  78991. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  78992. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  78993. var t0 = performance.now();
  78994. for (var i = 0; i !== internalSteps; i++) {
  78995. this.internalStep(dt);
  78996. if (performance.now() - t0 > dt * 1000) {
  78997. break;
  78998. }
  78999. }
  79000. this.time += timeSinceLastCalled;
  79001. var h = this.time % dt;
  79002. var h_div_dt = h / dt;
  79003. var interpvelo = step_tmp1;
  79004. var bodies = this.bodies;
  79005. for (var j = 0; j !== bodies.length; j++) {
  79006. var b = bodies[j];
  79007. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  79008. b.position.vsub(b.previousPosition, interpvelo);
  79009. interpvelo.scale(h_div_dt, interpvelo);
  79010. b.position.vadd(interpvelo, b.interpolatedPosition);
  79011. }
  79012. else {
  79013. b.interpolatedPosition.copy(b.position);
  79014. b.interpolatedQuaternion.copy(b.quaternion);
  79015. }
  79016. }
  79017. }
  79018. };
  79019. };
  79020. return CannonJSPlugin;
  79021. }());
  79022. BABYLON.CannonJSPlugin = CannonJSPlugin;
  79023. })(BABYLON || (BABYLON = {}));
  79024. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  79025. "use strict";
  79026. var BABYLON;
  79027. (function (BABYLON) {
  79028. var OimoJSPlugin = /** @class */ (function () {
  79029. function OimoJSPlugin(iterations) {
  79030. this.name = "OimoJSPlugin";
  79031. this._tmpImpostorsArray = [];
  79032. this._tmpPositionVector = BABYLON.Vector3.Zero();
  79033. this.BJSOIMO = OIMO;
  79034. this.world = new this.BJSOIMO.World({
  79035. iterations: iterations
  79036. });
  79037. this.world.clear();
  79038. }
  79039. OimoJSPlugin.prototype.setGravity = function (gravity) {
  79040. this.world.gravity.copy(gravity);
  79041. };
  79042. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  79043. this.world.timeStep = timeStep;
  79044. };
  79045. OimoJSPlugin.prototype.getTimeStep = function () {
  79046. return this.world.timeStep;
  79047. };
  79048. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  79049. var _this = this;
  79050. impostors.forEach(function (impostor) {
  79051. impostor.beforeStep();
  79052. });
  79053. this.world.step();
  79054. impostors.forEach(function (impostor) {
  79055. impostor.afterStep();
  79056. //update the ordered impostors array
  79057. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  79058. });
  79059. //check for collisions
  79060. var contact = this.world.contacts;
  79061. while (contact !== null) {
  79062. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  79063. contact = contact.next;
  79064. continue;
  79065. }
  79066. //is this body colliding with any other? get the impostor
  79067. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  79068. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  79069. if (!mainImpostor || !collidingImpostor) {
  79070. contact = contact.next;
  79071. continue;
  79072. }
  79073. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  79074. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  79075. contact = contact.next;
  79076. }
  79077. };
  79078. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  79079. var mass = impostor.physicsBody.mass;
  79080. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  79081. };
  79082. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  79083. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  79084. this.applyImpulse(impostor, force, contactPoint);
  79085. };
  79086. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  79087. var _this = this;
  79088. //parent-child relationship. Does this impostor has a parent impostor?
  79089. if (impostor.parent) {
  79090. if (impostor.physicsBody) {
  79091. this.removePhysicsBody(impostor);
  79092. //TODO is that needed?
  79093. impostor.forceUpdate();
  79094. }
  79095. return;
  79096. }
  79097. if (impostor.isBodyInitRequired()) {
  79098. var bodyConfig = {
  79099. name: impostor.uniqueId,
  79100. //Oimo must have mass, also for static objects.
  79101. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  79102. size: [],
  79103. type: [],
  79104. pos: [],
  79105. posShape: [],
  79106. rot: [],
  79107. rotShape: [],
  79108. move: impostor.getParam("mass") !== 0,
  79109. density: impostor.getParam("mass"),
  79110. friction: impostor.getParam("friction"),
  79111. restitution: impostor.getParam("restitution"),
  79112. //Supporting older versions of Oimo
  79113. world: this.world
  79114. };
  79115. var impostors = [impostor];
  79116. var addToArray = function (parent) {
  79117. if (!parent.getChildMeshes)
  79118. return;
  79119. parent.getChildMeshes().forEach(function (m) {
  79120. if (m.physicsImpostor) {
  79121. impostors.push(m.physicsImpostor);
  79122. //m.physicsImpostor._init();
  79123. }
  79124. });
  79125. };
  79126. addToArray(impostor.object);
  79127. var checkWithEpsilon_1 = function (value) {
  79128. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  79129. };
  79130. impostors.forEach(function (i) {
  79131. if (!i.object.rotationQuaternion) {
  79132. return;
  79133. }
  79134. //get the correct bounding box
  79135. var oldQuaternion = i.object.rotationQuaternion;
  79136. var rot = oldQuaternion.toEulerAngles();
  79137. var extendSize = i.getObjectExtendSize();
  79138. var radToDeg = 57.295779513082320876;
  79139. if (i === impostor) {
  79140. var center = impostor.getObjectCenter();
  79141. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  79142. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  79143. //Can also use Array.prototype.push.apply
  79144. bodyConfig.pos.push(center.x);
  79145. bodyConfig.pos.push(center.y);
  79146. bodyConfig.pos.push(center.z);
  79147. bodyConfig.posShape.push(0, 0, 0);
  79148. //tmp solution
  79149. bodyConfig.rot.push(rot.x * radToDeg);
  79150. bodyConfig.rot.push(rot.y * radToDeg);
  79151. bodyConfig.rot.push(rot.z * radToDeg);
  79152. bodyConfig.rotShape.push(0, 0, 0);
  79153. }
  79154. else {
  79155. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  79156. bodyConfig.posShape.push(localPosition.x);
  79157. bodyConfig.posShape.push(localPosition.y);
  79158. bodyConfig.posShape.push(localPosition.z);
  79159. bodyConfig.pos.push(0, 0, 0);
  79160. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  79161. bodyConfig.rot.push(0);
  79162. bodyConfig.rot.push(0);
  79163. bodyConfig.rot.push(0);
  79164. bodyConfig.rotShape.push(rot.x * radToDeg);
  79165. bodyConfig.rotShape.push(rot.y * radToDeg);
  79166. bodyConfig.rotShape.push(rot.z * radToDeg);
  79167. }
  79168. // register mesh
  79169. switch (i.type) {
  79170. case BABYLON.PhysicsImpostor.ParticleImpostor:
  79171. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  79172. case BABYLON.PhysicsImpostor.SphereImpostor:
  79173. var radiusX = extendSize.x;
  79174. var radiusY = extendSize.y;
  79175. var radiusZ = extendSize.z;
  79176. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  79177. bodyConfig.type.push('sphere');
  79178. //due to the way oimo works with compounds, add 3 times
  79179. bodyConfig.size.push(size);
  79180. bodyConfig.size.push(size);
  79181. bodyConfig.size.push(size);
  79182. break;
  79183. case BABYLON.PhysicsImpostor.CylinderImpostor:
  79184. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  79185. var sizeY = checkWithEpsilon_1(extendSize.y);
  79186. bodyConfig.type.push('cylinder');
  79187. bodyConfig.size.push(sizeX);
  79188. bodyConfig.size.push(sizeY);
  79189. //due to the way oimo works with compounds, add one more value.
  79190. bodyConfig.size.push(sizeY);
  79191. break;
  79192. case BABYLON.PhysicsImpostor.PlaneImpostor:
  79193. case BABYLON.PhysicsImpostor.BoxImpostor:
  79194. default:
  79195. var sizeX = checkWithEpsilon_1(extendSize.x);
  79196. var sizeY = checkWithEpsilon_1(extendSize.y);
  79197. var sizeZ = checkWithEpsilon_1(extendSize.z);
  79198. bodyConfig.type.push('box');
  79199. //if (i === impostor) {
  79200. bodyConfig.size.push(sizeX);
  79201. bodyConfig.size.push(sizeY);
  79202. bodyConfig.size.push(sizeZ);
  79203. //} else {
  79204. // bodyConfig.size.push(0,0,0);
  79205. //}
  79206. break;
  79207. }
  79208. //actually not needed, but hey...
  79209. i.object.rotationQuaternion = oldQuaternion;
  79210. });
  79211. impostor.physicsBody = this.world.add(bodyConfig);
  79212. }
  79213. else {
  79214. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  79215. }
  79216. impostor.setDeltaPosition(this._tmpPositionVector);
  79217. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  79218. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  79219. };
  79220. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  79221. //impostor.physicsBody.dispose();
  79222. //Same as : (older oimo versions)
  79223. this.world.removeRigidBody(impostor.physicsBody);
  79224. };
  79225. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  79226. var mainBody = impostorJoint.mainImpostor.physicsBody;
  79227. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  79228. if (!mainBody || !connectedBody) {
  79229. return;
  79230. }
  79231. var jointData = impostorJoint.joint.jointData;
  79232. var options = jointData.nativeParams || {};
  79233. var type;
  79234. var nativeJointData = {
  79235. body1: mainBody,
  79236. body2: connectedBody,
  79237. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  79238. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  79239. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  79240. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  79241. min: options.min,
  79242. max: options.max,
  79243. collision: options.collision || jointData.collision,
  79244. spring: options.spring,
  79245. //supporting older version of Oimo
  79246. world: this.world
  79247. };
  79248. switch (impostorJoint.joint.type) {
  79249. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  79250. type = "jointBall";
  79251. break;
  79252. case BABYLON.PhysicsJoint.SpringJoint:
  79253. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  79254. var springData = jointData;
  79255. nativeJointData.min = springData.length || nativeJointData.min;
  79256. //Max should also be set, just make sure it is at least min
  79257. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  79258. case BABYLON.PhysicsJoint.DistanceJoint:
  79259. type = "jointDistance";
  79260. nativeJointData.max = jointData.maxDistance;
  79261. break;
  79262. case BABYLON.PhysicsJoint.PrismaticJoint:
  79263. type = "jointPrisme";
  79264. break;
  79265. case BABYLON.PhysicsJoint.SliderJoint:
  79266. type = "jointSlide";
  79267. break;
  79268. case BABYLON.PhysicsJoint.WheelJoint:
  79269. type = "jointWheel";
  79270. break;
  79271. case BABYLON.PhysicsJoint.HingeJoint:
  79272. default:
  79273. type = "jointHinge";
  79274. break;
  79275. }
  79276. nativeJointData.type = type;
  79277. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  79278. };
  79279. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  79280. //Bug in Oimo prevents us from disposing a joint in the playground
  79281. //joint.joint.physicsJoint.dispose();
  79282. //So we will bruteforce it!
  79283. try {
  79284. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  79285. }
  79286. catch (e) {
  79287. BABYLON.Tools.Warn(e);
  79288. }
  79289. };
  79290. OimoJSPlugin.prototype.isSupported = function () {
  79291. return this.BJSOIMO !== undefined;
  79292. };
  79293. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  79294. if (!impostor.physicsBody.sleeping) {
  79295. //TODO check that
  79296. /*if (impostor.physicsBody.shapes.next) {
  79297. var parentShape = this._getLastShape(impostor.physicsBody);
  79298. impostor.object.position.copyFrom(parentShape.position);
  79299. console.log(parentShape.position);
  79300. } else {*/
  79301. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  79302. //}
  79303. if (impostor.object.rotationQuaternion) {
  79304. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  79305. }
  79306. }
  79307. };
  79308. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  79309. var body = impostor.physicsBody;
  79310. body.position.copy(newPosition);
  79311. body.orientation.copy(newRotation);
  79312. body.syncShapes();
  79313. body.awake();
  79314. };
  79315. /*private _getLastShape(body: any): any {
  79316. var lastShape = body.shapes;
  79317. while (lastShape.next) {
  79318. lastShape = lastShape.next;
  79319. }
  79320. return lastShape;
  79321. }*/
  79322. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  79323. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  79324. };
  79325. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  79326. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  79327. };
  79328. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  79329. var v = impostor.physicsBody.linearVelocity;
  79330. if (!v) {
  79331. return null;
  79332. }
  79333. return new BABYLON.Vector3(v.x, v.y, v.z);
  79334. };
  79335. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  79336. var v = impostor.physicsBody.angularVelocity;
  79337. if (!v) {
  79338. return null;
  79339. }
  79340. return new BABYLON.Vector3(v.x, v.y, v.z);
  79341. };
  79342. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  79343. var staticBody = mass === 0;
  79344. //this will actually set the body's density and not its mass.
  79345. //But this is how oimo treats the mass variable.
  79346. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  79347. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  79348. };
  79349. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  79350. return impostor.physicsBody.shapes.density;
  79351. };
  79352. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  79353. return impostor.physicsBody.shapes.friction;
  79354. };
  79355. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  79356. impostor.physicsBody.shapes.friction = friction;
  79357. };
  79358. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  79359. return impostor.physicsBody.shapes.restitution;
  79360. };
  79361. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  79362. impostor.physicsBody.shapes.restitution = restitution;
  79363. };
  79364. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  79365. impostor.physicsBody.sleep();
  79366. };
  79367. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  79368. impostor.physicsBody.awake();
  79369. };
  79370. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  79371. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  79372. if (minDistance !== void 0) {
  79373. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  79374. }
  79375. };
  79376. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  79377. //TODO separate rotational and transational motors.
  79378. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  79379. if (motor) {
  79380. motor.setMotor(speed, maxForce);
  79381. }
  79382. };
  79383. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  79384. //TODO separate rotational and transational motors.
  79385. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  79386. if (motor) {
  79387. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  79388. }
  79389. };
  79390. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  79391. var body = impostor.physicsBody;
  79392. mesh.position.x = body.position.x;
  79393. mesh.position.y = body.position.y;
  79394. mesh.position.z = body.position.z;
  79395. if (mesh.rotationQuaternion) {
  79396. mesh.rotationQuaternion.x = body.orientation.x;
  79397. mesh.rotationQuaternion.y = body.orientation.y;
  79398. mesh.rotationQuaternion.z = body.orientation.z;
  79399. mesh.rotationQuaternion.w = body.orientation.s;
  79400. }
  79401. };
  79402. OimoJSPlugin.prototype.getRadius = function (impostor) {
  79403. return impostor.physicsBody.shapes.radius;
  79404. };
  79405. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  79406. var shape = impostor.physicsBody.shapes;
  79407. result.x = shape.halfWidth * 2;
  79408. result.y = shape.halfHeight * 2;
  79409. result.z = shape.halfDepth * 2;
  79410. };
  79411. OimoJSPlugin.prototype.dispose = function () {
  79412. this.world.clear();
  79413. };
  79414. return OimoJSPlugin;
  79415. }());
  79416. BABYLON.OimoJSPlugin = OimoJSPlugin;
  79417. })(BABYLON || (BABYLON = {}));
  79418. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  79419. "use strict";
  79420. var BABYLON;
  79421. (function (BABYLON) {
  79422. /*
  79423. * Based on jsTGALoader - Javascript loader for TGA file
  79424. * By Vincent Thibault
  79425. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  79426. */
  79427. var TGATools = /** @class */ (function () {
  79428. function TGATools() {
  79429. }
  79430. TGATools.GetTGAHeader = function (data) {
  79431. var offset = 0;
  79432. var header = {
  79433. id_length: data[offset++],
  79434. colormap_type: data[offset++],
  79435. image_type: data[offset++],
  79436. colormap_index: data[offset++] | data[offset++] << 8,
  79437. colormap_length: data[offset++] | data[offset++] << 8,
  79438. colormap_size: data[offset++],
  79439. origin: [
  79440. data[offset++] | data[offset++] << 8,
  79441. data[offset++] | data[offset++] << 8
  79442. ],
  79443. width: data[offset++] | data[offset++] << 8,
  79444. height: data[offset++] | data[offset++] << 8,
  79445. pixel_size: data[offset++],
  79446. flags: data[offset++]
  79447. };
  79448. return header;
  79449. };
  79450. TGATools.UploadContent = function (gl, data) {
  79451. // Not enough data to contain header ?
  79452. if (data.length < 19) {
  79453. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  79454. return;
  79455. }
  79456. // Read Header
  79457. var offset = 18;
  79458. var header = TGATools.GetTGAHeader(data);
  79459. // Assume it's a valid Targa file.
  79460. if (header.id_length + offset > data.length) {
  79461. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  79462. return;
  79463. }
  79464. // Skip not needed data
  79465. offset += header.id_length;
  79466. var use_rle = false;
  79467. var use_pal = false;
  79468. var use_grey = false;
  79469. // Get some informations.
  79470. switch (header.image_type) {
  79471. case TGATools._TYPE_RLE_INDEXED:
  79472. use_rle = true;
  79473. case TGATools._TYPE_INDEXED:
  79474. use_pal = true;
  79475. break;
  79476. case TGATools._TYPE_RLE_RGB:
  79477. use_rle = true;
  79478. case TGATools._TYPE_RGB:
  79479. // use_rgb = true;
  79480. break;
  79481. case TGATools._TYPE_RLE_GREY:
  79482. use_rle = true;
  79483. case TGATools._TYPE_GREY:
  79484. use_grey = true;
  79485. break;
  79486. }
  79487. var pixel_data;
  79488. // var numAlphaBits = header.flags & 0xf;
  79489. var pixel_size = header.pixel_size >> 3;
  79490. var pixel_total = header.width * header.height * pixel_size;
  79491. // Read palettes
  79492. var palettes;
  79493. if (use_pal) {
  79494. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  79495. }
  79496. // Read LRE
  79497. if (use_rle) {
  79498. pixel_data = new Uint8Array(pixel_total);
  79499. var c, count, i;
  79500. var localOffset = 0;
  79501. var pixels = new Uint8Array(pixel_size);
  79502. while (offset < pixel_total && localOffset < pixel_total) {
  79503. c = data[offset++];
  79504. count = (c & 0x7f) + 1;
  79505. // RLE pixels
  79506. if (c & 0x80) {
  79507. // Bind pixel tmp array
  79508. for (i = 0; i < pixel_size; ++i) {
  79509. pixels[i] = data[offset++];
  79510. }
  79511. // Copy pixel array
  79512. for (i = 0; i < count; ++i) {
  79513. pixel_data.set(pixels, localOffset + i * pixel_size);
  79514. }
  79515. localOffset += pixel_size * count;
  79516. }
  79517. else {
  79518. count *= pixel_size;
  79519. for (i = 0; i < count; ++i) {
  79520. pixel_data[localOffset + i] = data[offset++];
  79521. }
  79522. localOffset += count;
  79523. }
  79524. }
  79525. }
  79526. else {
  79527. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  79528. }
  79529. // Load to texture
  79530. var x_start, y_start, x_step, y_step, y_end, x_end;
  79531. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  79532. default:
  79533. case TGATools._ORIGIN_UL:
  79534. x_start = 0;
  79535. x_step = 1;
  79536. x_end = header.width;
  79537. y_start = 0;
  79538. y_step = 1;
  79539. y_end = header.height;
  79540. break;
  79541. case TGATools._ORIGIN_BL:
  79542. x_start = 0;
  79543. x_step = 1;
  79544. x_end = header.width;
  79545. y_start = header.height - 1;
  79546. y_step = -1;
  79547. y_end = -1;
  79548. break;
  79549. case TGATools._ORIGIN_UR:
  79550. x_start = header.width - 1;
  79551. x_step = -1;
  79552. x_end = -1;
  79553. y_start = 0;
  79554. y_step = 1;
  79555. y_end = header.height;
  79556. break;
  79557. case TGATools._ORIGIN_BR:
  79558. x_start = header.width - 1;
  79559. x_step = -1;
  79560. x_end = -1;
  79561. y_start = header.height - 1;
  79562. y_step = -1;
  79563. y_end = -1;
  79564. break;
  79565. }
  79566. // Load the specify method
  79567. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  79568. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  79569. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  79570. };
  79571. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  79572. var image = pixel_data, colormap = palettes;
  79573. var width = header.width, height = header.height;
  79574. var color, i = 0, x, y;
  79575. var imageData = new Uint8Array(width * height * 4);
  79576. for (y = y_start; y !== y_end; y += y_step) {
  79577. for (x = x_start; x !== x_end; x += x_step, i++) {
  79578. color = image[i];
  79579. imageData[(x + width * y) * 4 + 3] = 255;
  79580. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  79581. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  79582. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  79583. }
  79584. }
  79585. return imageData;
  79586. };
  79587. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  79588. var image = pixel_data;
  79589. var width = header.width, height = header.height;
  79590. var color, i = 0, x, y;
  79591. var imageData = new Uint8Array(width * height * 4);
  79592. for (y = y_start; y !== y_end; y += y_step) {
  79593. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  79594. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  79595. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  79596. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  79597. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  79598. imageData[(x + width * y) * 4 + 0] = r;
  79599. imageData[(x + width * y) * 4 + 1] = g;
  79600. imageData[(x + width * y) * 4 + 2] = b;
  79601. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  79602. }
  79603. }
  79604. return imageData;
  79605. };
  79606. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  79607. var image = pixel_data;
  79608. var width = header.width, height = header.height;
  79609. var i = 0, x, y;
  79610. var imageData = new Uint8Array(width * height * 4);
  79611. for (y = y_start; y !== y_end; y += y_step) {
  79612. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  79613. imageData[(x + width * y) * 4 + 3] = 255;
  79614. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  79615. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  79616. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  79617. }
  79618. }
  79619. return imageData;
  79620. };
  79621. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  79622. var image = pixel_data;
  79623. var width = header.width, height = header.height;
  79624. var i = 0, x, y;
  79625. var imageData = new Uint8Array(width * height * 4);
  79626. for (y = y_start; y !== y_end; y += y_step) {
  79627. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  79628. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  79629. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  79630. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  79631. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  79632. }
  79633. }
  79634. return imageData;
  79635. };
  79636. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  79637. var image = pixel_data;
  79638. var width = header.width, height = header.height;
  79639. var color, i = 0, x, y;
  79640. var imageData = new Uint8Array(width * height * 4);
  79641. for (y = y_start; y !== y_end; y += y_step) {
  79642. for (x = x_start; x !== x_end; x += x_step, i++) {
  79643. color = image[i];
  79644. imageData[(x + width * y) * 4 + 0] = color;
  79645. imageData[(x + width * y) * 4 + 1] = color;
  79646. imageData[(x + width * y) * 4 + 2] = color;
  79647. imageData[(x + width * y) * 4 + 3] = 255;
  79648. }
  79649. }
  79650. return imageData;
  79651. };
  79652. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  79653. var image = pixel_data;
  79654. var width = header.width, height = header.height;
  79655. var i = 0, x, y;
  79656. var imageData = new Uint8Array(width * height * 4);
  79657. for (y = y_start; y !== y_end; y += y_step) {
  79658. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  79659. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  79660. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  79661. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  79662. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  79663. }
  79664. }
  79665. return imageData;
  79666. };
  79667. //private static _TYPE_NO_DATA = 0;
  79668. TGATools._TYPE_INDEXED = 1;
  79669. TGATools._TYPE_RGB = 2;
  79670. TGATools._TYPE_GREY = 3;
  79671. TGATools._TYPE_RLE_INDEXED = 9;
  79672. TGATools._TYPE_RLE_RGB = 10;
  79673. TGATools._TYPE_RLE_GREY = 11;
  79674. TGATools._ORIGIN_MASK = 0x30;
  79675. TGATools._ORIGIN_SHIFT = 0x04;
  79676. TGATools._ORIGIN_BL = 0x00;
  79677. TGATools._ORIGIN_BR = 0x01;
  79678. TGATools._ORIGIN_UL = 0x02;
  79679. TGATools._ORIGIN_UR = 0x03;
  79680. return TGATools;
  79681. }());
  79682. BABYLON.TGATools = TGATools;
  79683. })(BABYLON || (BABYLON = {}));
  79684. //# sourceMappingURL=babylon.tga.js.map
  79685. "use strict";
  79686. var BABYLON;
  79687. (function (BABYLON) {
  79688. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  79689. // All values and structures referenced from:
  79690. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  79691. var DDS_MAGIC = 0x20534444;
  79692. var
  79693. //DDSD_CAPS = 0x1,
  79694. //DDSD_HEIGHT = 0x2,
  79695. //DDSD_WIDTH = 0x4,
  79696. //DDSD_PITCH = 0x8,
  79697. //DDSD_PIXELFORMAT = 0x1000,
  79698. DDSD_MIPMAPCOUNT = 0x20000;
  79699. //DDSD_LINEARSIZE = 0x80000,
  79700. //DDSD_DEPTH = 0x800000;
  79701. // var DDSCAPS_COMPLEX = 0x8,
  79702. // DDSCAPS_MIPMAP = 0x400000,
  79703. // DDSCAPS_TEXTURE = 0x1000;
  79704. var DDSCAPS2_CUBEMAP = 0x200;
  79705. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  79706. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  79707. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  79708. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  79709. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  79710. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  79711. // DDSCAPS2_VOLUME = 0x200000;
  79712. var
  79713. //DDPF_ALPHAPIXELS = 0x1,
  79714. //DDPF_ALPHA = 0x2,
  79715. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  79716. //DDPF_YUV = 0x200,
  79717. DDPF_LUMINANCE = 0x20000;
  79718. function FourCCToInt32(value) {
  79719. return value.charCodeAt(0) +
  79720. (value.charCodeAt(1) << 8) +
  79721. (value.charCodeAt(2) << 16) +
  79722. (value.charCodeAt(3) << 24);
  79723. }
  79724. function Int32ToFourCC(value) {
  79725. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  79726. }
  79727. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  79728. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  79729. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  79730. var FOURCC_DX10 = FourCCToInt32("DX10");
  79731. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  79732. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  79733. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  79734. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  79735. var headerLengthInt = 31; // The header length in 32 bit ints
  79736. // Offsets into the header array
  79737. var off_magic = 0;
  79738. var off_size = 1;
  79739. var off_flags = 2;
  79740. var off_height = 3;
  79741. var off_width = 4;
  79742. var off_mipmapCount = 7;
  79743. var off_pfFlags = 20;
  79744. var off_pfFourCC = 21;
  79745. var off_RGBbpp = 22;
  79746. var off_RMask = 23;
  79747. var off_GMask = 24;
  79748. var off_BMask = 25;
  79749. var off_AMask = 26;
  79750. // var off_caps1 = 27;
  79751. var off_caps2 = 28;
  79752. // var off_caps3 = 29;
  79753. // var off_caps4 = 30;
  79754. var off_dxgiFormat = 32;
  79755. ;
  79756. var DDSTools = /** @class */ (function () {
  79757. function DDSTools() {
  79758. }
  79759. DDSTools.GetDDSInfo = function (arrayBuffer) {
  79760. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  79761. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  79762. var mipmapCount = 1;
  79763. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  79764. mipmapCount = Math.max(1, header[off_mipmapCount]);
  79765. }
  79766. var fourCC = header[off_pfFourCC];
  79767. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  79768. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  79769. switch (fourCC) {
  79770. case FOURCC_D3DFMT_R16G16B16A16F:
  79771. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  79772. break;
  79773. case FOURCC_D3DFMT_R32G32B32A32F:
  79774. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  79775. break;
  79776. case FOURCC_DX10:
  79777. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  79778. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  79779. break;
  79780. }
  79781. }
  79782. return {
  79783. width: header[off_width],
  79784. height: header[off_height],
  79785. mipmapCount: mipmapCount,
  79786. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  79787. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  79788. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  79789. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  79790. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  79791. dxgiFormat: dxgiFormat,
  79792. textureType: textureType
  79793. };
  79794. };
  79795. DDSTools._ToHalfFloat = function (value) {
  79796. if (!DDSTools._FloatView) {
  79797. DDSTools._FloatView = new Float32Array(1);
  79798. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  79799. }
  79800. DDSTools._FloatView[0] = value;
  79801. var x = DDSTools._Int32View[0];
  79802. var bits = (x >> 16) & 0x8000; /* Get the sign */
  79803. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  79804. var e = (x >> 23) & 0xff; /* Using int is faster here */
  79805. /* If zero, or denormal, or exponent underflows too much for a denormal
  79806. * half, return signed zero. */
  79807. if (e < 103) {
  79808. return bits;
  79809. }
  79810. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  79811. if (e > 142) {
  79812. bits |= 0x7c00;
  79813. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  79814. * not Inf, so make sure we set one mantissa bit too. */
  79815. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  79816. return bits;
  79817. }
  79818. /* If exponent underflows but not too much, return a denormal */
  79819. if (e < 113) {
  79820. m |= 0x0800;
  79821. /* Extra rounding may overflow and set mantissa to 0 and exponent
  79822. * to 1, which is OK. */
  79823. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  79824. return bits;
  79825. }
  79826. bits |= ((e - 112) << 10) | (m >> 1);
  79827. bits += m & 1;
  79828. return bits;
  79829. };
  79830. DDSTools._FromHalfFloat = function (value) {
  79831. var s = (value & 0x8000) >> 15;
  79832. var e = (value & 0x7C00) >> 10;
  79833. var f = value & 0x03FF;
  79834. if (e === 0) {
  79835. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  79836. }
  79837. else if (e == 0x1F) {
  79838. return f ? NaN : ((s ? -1 : 1) * Infinity);
  79839. }
  79840. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  79841. };
  79842. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  79843. var destArray = new Float32Array(dataLength);
  79844. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  79845. var index = 0;
  79846. for (var y = 0; y < height; y++) {
  79847. for (var x = 0; x < width; x++) {
  79848. var srcPos = (x + y * width) * 4;
  79849. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  79850. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  79851. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  79852. if (DDSTools.StoreLODInAlphaChannel) {
  79853. destArray[index + 3] = lod;
  79854. }
  79855. else {
  79856. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  79857. }
  79858. index += 4;
  79859. }
  79860. }
  79861. return destArray;
  79862. };
  79863. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  79864. if (DDSTools.StoreLODInAlphaChannel) {
  79865. var destArray = new Uint16Array(dataLength);
  79866. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  79867. var index = 0;
  79868. for (var y = 0; y < height; y++) {
  79869. for (var x = 0; x < width; x++) {
  79870. var srcPos = (x + y * width) * 4;
  79871. destArray[index] = srcData[srcPos];
  79872. destArray[index + 1] = srcData[srcPos + 1];
  79873. destArray[index + 2] = srcData[srcPos + 2];
  79874. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  79875. index += 4;
  79876. }
  79877. }
  79878. return destArray;
  79879. }
  79880. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  79881. };
  79882. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  79883. if (DDSTools.StoreLODInAlphaChannel) {
  79884. var destArray = new Float32Array(dataLength);
  79885. var srcData = new Float32Array(arrayBuffer, dataOffset);
  79886. var index = 0;
  79887. for (var y = 0; y < height; y++) {
  79888. for (var x = 0; x < width; x++) {
  79889. var srcPos = (x + y * width) * 4;
  79890. destArray[index] = srcData[srcPos];
  79891. destArray[index + 1] = srcData[srcPos + 1];
  79892. destArray[index + 2] = srcData[srcPos + 2];
  79893. destArray[index + 3] = lod;
  79894. index += 4;
  79895. }
  79896. }
  79897. return destArray;
  79898. }
  79899. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  79900. };
  79901. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  79902. var destArray = new Uint8Array(dataLength);
  79903. var srcData = new Float32Array(arrayBuffer, dataOffset);
  79904. var index = 0;
  79905. for (var y = 0; y < height; y++) {
  79906. for (var x = 0; x < width; x++) {
  79907. var srcPos = (x + y * width) * 4;
  79908. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  79909. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  79910. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  79911. if (DDSTools.StoreLODInAlphaChannel) {
  79912. destArray[index + 3] = lod;
  79913. }
  79914. else {
  79915. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  79916. }
  79917. index += 4;
  79918. }
  79919. }
  79920. return destArray;
  79921. };
  79922. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  79923. var destArray = new Uint8Array(dataLength);
  79924. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  79925. var index = 0;
  79926. for (var y = 0; y < height; y++) {
  79927. for (var x = 0; x < width; x++) {
  79928. var srcPos = (x + y * width) * 4;
  79929. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  79930. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  79931. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  79932. if (DDSTools.StoreLODInAlphaChannel) {
  79933. destArray[index + 3] = lod;
  79934. }
  79935. else {
  79936. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  79937. }
  79938. index += 4;
  79939. }
  79940. }
  79941. return destArray;
  79942. };
  79943. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  79944. var byteArray = new Uint8Array(dataLength);
  79945. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  79946. var index = 0;
  79947. for (var y = 0; y < height; y++) {
  79948. for (var x = 0; x < width; x++) {
  79949. var srcPos = (x + y * width) * 4;
  79950. byteArray[index] = srcData[srcPos + rOffset];
  79951. byteArray[index + 1] = srcData[srcPos + gOffset];
  79952. byteArray[index + 2] = srcData[srcPos + bOffset];
  79953. byteArray[index + 3] = srcData[srcPos + aOffset];
  79954. index += 4;
  79955. }
  79956. }
  79957. return byteArray;
  79958. };
  79959. DDSTools._ExtractLongWordOrder = function (value) {
  79960. if (value === 0 || value === 255 || value === -16777216) {
  79961. return 0;
  79962. }
  79963. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  79964. };
  79965. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  79966. var byteArray = new Uint8Array(dataLength);
  79967. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  79968. var index = 0;
  79969. for (var y = 0; y < height; y++) {
  79970. for (var x = 0; x < width; x++) {
  79971. var srcPos = (x + y * width) * 3;
  79972. byteArray[index] = srcData[srcPos + rOffset];
  79973. byteArray[index + 1] = srcData[srcPos + gOffset];
  79974. byteArray[index + 2] = srcData[srcPos + bOffset];
  79975. index += 3;
  79976. }
  79977. }
  79978. return byteArray;
  79979. };
  79980. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  79981. var byteArray = new Uint8Array(dataLength);
  79982. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  79983. var index = 0;
  79984. for (var y = 0; y < height; y++) {
  79985. for (var x = 0; x < width; x++) {
  79986. var srcPos = (x + y * width);
  79987. byteArray[index] = srcData[srcPos];
  79988. index++;
  79989. }
  79990. }
  79991. return byteArray;
  79992. };
  79993. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  79994. if (lodIndex === void 0) { lodIndex = -1; }
  79995. var ext = engine.getCaps().s3tc;
  79996. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  79997. var fourCC, width, height, dataLength = 0, dataOffset;
  79998. var byteArray, mipmapCount, mip;
  79999. var internalFormat = 0;
  80000. var format = 0;
  80001. var blockBytes = 1;
  80002. if (header[off_magic] !== DDS_MAGIC) {
  80003. BABYLON.Tools.Error("Invalid magic number in DDS header");
  80004. return;
  80005. }
  80006. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  80007. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  80008. return;
  80009. }
  80010. if (info.isCompressed && !ext) {
  80011. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  80012. return;
  80013. }
  80014. var bpp = header[off_RGBbpp];
  80015. dataOffset = header[off_size] + 4;
  80016. var computeFormats = false;
  80017. if (info.isFourCC) {
  80018. fourCC = header[off_pfFourCC];
  80019. switch (fourCC) {
  80020. case FOURCC_DXT1:
  80021. blockBytes = 8;
  80022. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  80023. break;
  80024. case FOURCC_DXT3:
  80025. blockBytes = 16;
  80026. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  80027. break;
  80028. case FOURCC_DXT5:
  80029. blockBytes = 16;
  80030. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  80031. break;
  80032. case FOURCC_D3DFMT_R16G16B16A16F:
  80033. computeFormats = true;
  80034. break;
  80035. case FOURCC_D3DFMT_R32G32B32A32F:
  80036. computeFormats = true;
  80037. break;
  80038. case FOURCC_DX10:
  80039. // There is an additionnal header so dataOffset need to be changed
  80040. dataOffset += 5 * 4; // 5 uints
  80041. var supported = false;
  80042. switch (info.dxgiFormat) {
  80043. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  80044. computeFormats = true;
  80045. supported = true;
  80046. break;
  80047. case DXGI_FORMAT_B8G8R8X8_UNORM:
  80048. info.isRGB = true;
  80049. info.isFourCC = false;
  80050. bpp = 32;
  80051. supported = true;
  80052. break;
  80053. }
  80054. if (supported) {
  80055. break;
  80056. }
  80057. default:
  80058. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  80059. return;
  80060. }
  80061. }
  80062. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  80063. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  80064. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  80065. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  80066. if (computeFormats) {
  80067. format = engine._getWebGLTextureType(info.textureType);
  80068. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  80069. }
  80070. mipmapCount = 1;
  80071. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  80072. mipmapCount = Math.max(1, header[off_mipmapCount]);
  80073. }
  80074. for (var face = 0; face < faces; face++) {
  80075. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  80076. width = header[off_width];
  80077. height = header[off_height];
  80078. for (mip = 0; mip < mipmapCount; ++mip) {
  80079. if (lodIndex === -1 || lodIndex === mip) {
  80080. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  80081. var i = (lodIndex === -1) ? mip : 0;
  80082. if (!info.isCompressed && info.isFourCC) {
  80083. dataLength = width * height * 4;
  80084. var floatArray = null;
  80085. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  80086. if (bpp === 128) {
  80087. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  80088. }
  80089. else if (bpp === 64) {
  80090. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  80091. }
  80092. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  80093. format = engine._getWebGLTextureType(info.textureType);
  80094. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  80095. }
  80096. else {
  80097. if (bpp === 128) {
  80098. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  80099. }
  80100. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  80101. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  80102. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  80103. format = engine._getWebGLTextureType(info.textureType);
  80104. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  80105. }
  80106. else {
  80107. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  80108. }
  80109. }
  80110. if (floatArray) {
  80111. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  80112. }
  80113. }
  80114. else if (info.isRGB) {
  80115. if (bpp === 24) {
  80116. dataLength = width * height * 3;
  80117. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  80118. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  80119. }
  80120. else {
  80121. dataLength = width * height * 4;
  80122. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  80123. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  80124. }
  80125. }
  80126. else if (info.isLuminance) {
  80127. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  80128. var unpaddedRowSize = width;
  80129. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  80130. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  80131. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  80132. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  80133. }
  80134. else {
  80135. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  80136. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  80137. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  80138. }
  80139. }
  80140. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  80141. width *= 0.5;
  80142. height *= 0.5;
  80143. width = Math.max(1.0, width);
  80144. height = Math.max(1.0, height);
  80145. }
  80146. if (currentFace !== undefined) {
  80147. // Loading a single face
  80148. break;
  80149. }
  80150. }
  80151. };
  80152. DDSTools.StoreLODInAlphaChannel = false;
  80153. return DDSTools;
  80154. }());
  80155. BABYLON.DDSTools = DDSTools;
  80156. })(BABYLON || (BABYLON = {}));
  80157. //# sourceMappingURL=babylon.dds.js.map
  80158. "use strict";
  80159. var BABYLON;
  80160. (function (BABYLON) {
  80161. /**
  80162. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  80163. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  80164. */
  80165. var KhronosTextureContainer = /** @class */ (function () {
  80166. /**
  80167. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  80168. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  80169. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  80170. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  80171. */
  80172. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  80173. this.arrayBuffer = arrayBuffer;
  80174. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  80175. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  80176. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  80177. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  80178. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  80179. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  80180. BABYLON.Tools.Error("texture missing KTX identifier");
  80181. return;
  80182. }
  80183. // load the reset of the header in native 32 bit int
  80184. var header = new Int32Array(this.arrayBuffer, 12, 13);
  80185. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  80186. var oppositeEndianess = header[0] === 0x01020304;
  80187. // read all the header elements in order they exist in the file, without modification (sans endainness)
  80188. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  80189. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  80190. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  80191. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  80192. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  80193. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  80194. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  80195. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  80196. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  80197. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  80198. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  80199. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  80200. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  80201. if (this.glType !== 0) {
  80202. BABYLON.Tools.Error("only compressed formats currently supported");
  80203. return;
  80204. }
  80205. else {
  80206. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  80207. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  80208. }
  80209. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  80210. BABYLON.Tools.Error("only 2D textures currently supported");
  80211. return;
  80212. }
  80213. if (this.numberOfArrayElements !== 0) {
  80214. BABYLON.Tools.Error("texture arrays not currently supported");
  80215. return;
  80216. }
  80217. if (this.numberOfFaces !== facesExpected) {
  80218. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  80219. return;
  80220. }
  80221. // we now have a completely validated file, so could use existence of loadType as success
  80222. // would need to make this more elaborate & adjust checks above to support more than one load type
  80223. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  80224. }
  80225. // not as fast hardware based, but will probably never need to use
  80226. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  80227. return ((val & 0xFF) << 24)
  80228. | ((val & 0xFF00) << 8)
  80229. | ((val >> 8) & 0xFF00)
  80230. | ((val >> 24) & 0xFF);
  80231. };
  80232. /**
  80233. * It is assumed that the texture has already been created & is currently bound
  80234. */
  80235. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  80236. switch (this.loadType) {
  80237. case KhronosTextureContainer.COMPRESSED_2D:
  80238. this._upload2DCompressedLevels(gl, loadMipmaps);
  80239. break;
  80240. case KhronosTextureContainer.TEX_2D:
  80241. case KhronosTextureContainer.COMPRESSED_3D:
  80242. case KhronosTextureContainer.TEX_3D:
  80243. }
  80244. };
  80245. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  80246. // initialize width & height for level 1
  80247. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  80248. var width = this.pixelWidth;
  80249. var height = this.pixelHeight;
  80250. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  80251. for (var level = 0; level < mipmapCount; level++) {
  80252. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  80253. for (var face = 0; face < this.numberOfFaces; face++) {
  80254. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  80255. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  80256. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  80257. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  80258. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  80259. }
  80260. width = Math.max(1.0, width * 0.5);
  80261. height = Math.max(1.0, height * 0.5);
  80262. }
  80263. };
  80264. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  80265. // load types
  80266. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  80267. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  80268. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  80269. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  80270. return KhronosTextureContainer;
  80271. }());
  80272. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  80273. })(BABYLON || (BABYLON = {}));
  80274. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  80275. "use strict";
  80276. var BABYLON;
  80277. (function (BABYLON) {
  80278. var Debug = /** @class */ (function () {
  80279. function Debug() {
  80280. }
  80281. Debug.AxesViewer = /** @class */ (function () {
  80282. function AxesViewer(scene, scaleLines) {
  80283. if (scaleLines === void 0) { scaleLines = 1; }
  80284. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80285. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80286. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80287. this.scaleLines = 1;
  80288. this.scaleLines = scaleLines;
  80289. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  80290. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  80291. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  80292. this._xmesh.renderingGroupId = 2;
  80293. this._ymesh.renderingGroupId = 2;
  80294. this._zmesh.renderingGroupId = 2;
  80295. this._xmesh.material.checkReadyOnlyOnce = true;
  80296. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  80297. this._ymesh.material.checkReadyOnlyOnce = true;
  80298. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  80299. this._zmesh.material.checkReadyOnlyOnce = true;
  80300. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  80301. this.scene = scene;
  80302. }
  80303. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  80304. var scaleLines = this.scaleLines;
  80305. if (this._xmesh) {
  80306. this._xmesh.position.copyFrom(position);
  80307. }
  80308. if (this._ymesh) {
  80309. this._ymesh.position.copyFrom(position);
  80310. }
  80311. if (this._zmesh) {
  80312. this._zmesh.position.copyFrom(position);
  80313. }
  80314. var point2 = this._xline[1];
  80315. point2.x = xaxis.x * scaleLines;
  80316. point2.y = xaxis.y * scaleLines;
  80317. point2.z = xaxis.z * scaleLines;
  80318. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  80319. point2 = this._yline[1];
  80320. point2.x = yaxis.x * scaleLines;
  80321. point2.y = yaxis.y * scaleLines;
  80322. point2.z = yaxis.z * scaleLines;
  80323. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  80324. point2 = this._zline[1];
  80325. point2.x = zaxis.x * scaleLines;
  80326. point2.y = zaxis.y * scaleLines;
  80327. point2.z = zaxis.z * scaleLines;
  80328. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  80329. };
  80330. AxesViewer.prototype.dispose = function () {
  80331. if (this._xmesh) {
  80332. this._xmesh.dispose();
  80333. }
  80334. if (this._ymesh) {
  80335. this._ymesh.dispose();
  80336. }
  80337. if (this._zmesh) {
  80338. this._zmesh.dispose();
  80339. }
  80340. this._xmesh = null;
  80341. this._ymesh = null;
  80342. this._zmesh = null;
  80343. this.scene = null;
  80344. };
  80345. return AxesViewer;
  80346. }());
  80347. Debug.BoneAxesViewer = /** @class */ (function (_super) {
  80348. __extends(BoneAxesViewer, _super);
  80349. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  80350. if (scaleLines === void 0) { scaleLines = 1; }
  80351. var _this = _super.call(this, scene, scaleLines) || this;
  80352. _this.pos = BABYLON.Vector3.Zero();
  80353. _this.xaxis = BABYLON.Vector3.Zero();
  80354. _this.yaxis = BABYLON.Vector3.Zero();
  80355. _this.zaxis = BABYLON.Vector3.Zero();
  80356. _this.mesh = mesh;
  80357. _this.bone = bone;
  80358. return _this;
  80359. }
  80360. BoneAxesViewer.prototype.update = function () {
  80361. if (!this.mesh || !this.bone) {
  80362. return;
  80363. }
  80364. var bone = this.bone;
  80365. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  80366. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  80367. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  80368. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  80369. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  80370. };
  80371. BoneAxesViewer.prototype.dispose = function () {
  80372. if (this.mesh) {
  80373. this.mesh = null;
  80374. this.bone = null;
  80375. _super.prototype.dispose.call(this);
  80376. }
  80377. };
  80378. return BoneAxesViewer;
  80379. }(Debug.AxesViewer));
  80380. Debug.PhysicsViewer = /** @class */ (function () {
  80381. function PhysicsViewer(scene) {
  80382. this._impostors = [];
  80383. this._meshes = [];
  80384. this._numMeshes = 0;
  80385. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  80386. var physicEngine = this._scene.getPhysicsEngine();
  80387. if (physicEngine) {
  80388. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  80389. }
  80390. }
  80391. PhysicsViewer.prototype._updateDebugMeshes = function () {
  80392. var plugin = this._physicsEnginePlugin;
  80393. for (var i = 0; i < this._numMeshes; i++) {
  80394. var impostor = this._impostors[i];
  80395. if (!impostor) {
  80396. continue;
  80397. }
  80398. if (impostor.isDisposed) {
  80399. this.hideImpostor(this._impostors[i--]);
  80400. }
  80401. else {
  80402. var mesh = this._meshes[i];
  80403. if (mesh && plugin) {
  80404. plugin.syncMeshWithImpostor(mesh, impostor);
  80405. }
  80406. }
  80407. }
  80408. };
  80409. PhysicsViewer.prototype.showImpostor = function (impostor) {
  80410. if (!this._scene) {
  80411. return;
  80412. }
  80413. for (var i = 0; i < this._numMeshes; i++) {
  80414. if (this._impostors[i] == impostor) {
  80415. return;
  80416. }
  80417. }
  80418. var debugMesh = this._getDebugMesh(impostor, this._scene);
  80419. if (debugMesh) {
  80420. this._impostors[this._numMeshes] = impostor;
  80421. this._meshes[this._numMeshes] = debugMesh;
  80422. if (this._numMeshes === 0) {
  80423. this._renderFunction = this._updateDebugMeshes.bind(this);
  80424. this._scene.registerBeforeRender(this._renderFunction);
  80425. }
  80426. this._numMeshes++;
  80427. }
  80428. };
  80429. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  80430. if (!impostor || !this._scene) {
  80431. return;
  80432. }
  80433. var removed = false;
  80434. for (var i = 0; i < this._numMeshes; i++) {
  80435. if (this._impostors[i] == impostor) {
  80436. var mesh = this._meshes[i];
  80437. if (!mesh) {
  80438. continue;
  80439. }
  80440. this._scene.removeMesh(mesh);
  80441. mesh.dispose();
  80442. this._numMeshes--;
  80443. if (this._numMeshes > 0) {
  80444. this._meshes[i] = this._meshes[this._numMeshes];
  80445. this._impostors[i] = this._impostors[this._numMeshes];
  80446. this._meshes[this._numMeshes] = null;
  80447. this._impostors[this._numMeshes] = null;
  80448. }
  80449. else {
  80450. this._meshes[0] = null;
  80451. this._impostors[0] = null;
  80452. }
  80453. removed = true;
  80454. break;
  80455. }
  80456. }
  80457. if (removed && this._numMeshes === 0) {
  80458. this._scene.unregisterBeforeRender(this._renderFunction);
  80459. }
  80460. };
  80461. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  80462. if (!this._debugMaterial) {
  80463. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  80464. this._debugMaterial.wireframe = true;
  80465. }
  80466. return this._debugMaterial;
  80467. };
  80468. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  80469. if (!this._debugBoxMesh) {
  80470. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  80471. this._debugBoxMesh.renderingGroupId = 1;
  80472. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  80473. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  80474. scene.removeMesh(this._debugBoxMesh);
  80475. }
  80476. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  80477. };
  80478. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  80479. if (!this._debugSphereMesh) {
  80480. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  80481. this._debugSphereMesh.renderingGroupId = 1;
  80482. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  80483. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  80484. scene.removeMesh(this._debugSphereMesh);
  80485. }
  80486. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  80487. };
  80488. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  80489. var mesh = null;
  80490. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  80491. mesh = this._getDebugBoxMesh(scene);
  80492. impostor.getBoxSizeToRef(mesh.scaling);
  80493. }
  80494. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  80495. mesh = this._getDebugSphereMesh(scene);
  80496. var radius = impostor.getRadius();
  80497. mesh.scaling.x = radius * 2;
  80498. mesh.scaling.y = radius * 2;
  80499. mesh.scaling.z = radius * 2;
  80500. }
  80501. return mesh;
  80502. };
  80503. PhysicsViewer.prototype.dispose = function () {
  80504. for (var i = 0; i < this._numMeshes; i++) {
  80505. this.hideImpostor(this._impostors[i]);
  80506. }
  80507. if (this._debugBoxMesh) {
  80508. this._debugBoxMesh.dispose();
  80509. }
  80510. if (this._debugSphereMesh) {
  80511. this._debugSphereMesh.dispose();
  80512. }
  80513. if (this._debugMaterial) {
  80514. this._debugMaterial.dispose();
  80515. }
  80516. this._impostors.length = 0;
  80517. this._scene = null;
  80518. this._physicsEnginePlugin = null;
  80519. };
  80520. return PhysicsViewer;
  80521. }());
  80522. Debug.SkeletonViewer = /** @class */ (function () {
  80523. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  80524. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  80525. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  80526. this.skeleton = skeleton;
  80527. this.mesh = mesh;
  80528. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  80529. this.renderingGroupId = renderingGroupId;
  80530. this.color = BABYLON.Color3.White();
  80531. this._debugLines = new Array();
  80532. this._isEnabled = false;
  80533. this._scene = scene;
  80534. this.update();
  80535. this._renderFunction = this.update.bind(this);
  80536. }
  80537. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  80538. get: function () {
  80539. return this._isEnabled;
  80540. },
  80541. set: function (value) {
  80542. if (this._isEnabled === value) {
  80543. return;
  80544. }
  80545. this._isEnabled = value;
  80546. if (value) {
  80547. this._scene.registerBeforeRender(this._renderFunction);
  80548. }
  80549. else {
  80550. this._scene.unregisterBeforeRender(this._renderFunction);
  80551. }
  80552. },
  80553. enumerable: true,
  80554. configurable: true
  80555. });
  80556. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  80557. if (x === void 0) { x = 0; }
  80558. if (y === void 0) { y = 0; }
  80559. if (z === void 0) { z = 0; }
  80560. var tmat = BABYLON.Tmp.Matrix[0];
  80561. var parentBone = bone.getParent();
  80562. tmat.copyFrom(bone.getLocalMatrix());
  80563. if (x !== 0 || y !== 0 || z !== 0) {
  80564. var tmat2 = BABYLON.Tmp.Matrix[1];
  80565. BABYLON.Matrix.IdentityToRef(tmat2);
  80566. tmat2.m[12] = x;
  80567. tmat2.m[13] = y;
  80568. tmat2.m[14] = z;
  80569. tmat2.multiplyToRef(tmat, tmat);
  80570. }
  80571. if (parentBone) {
  80572. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  80573. }
  80574. tmat.multiplyToRef(meshMat, tmat);
  80575. position.x = tmat.m[12];
  80576. position.y = tmat.m[13];
  80577. position.z = tmat.m[14];
  80578. };
  80579. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  80580. var len = bones.length;
  80581. var meshPos = this.mesh.position;
  80582. for (var i = 0; i < len; i++) {
  80583. var bone = bones[i];
  80584. var points = this._debugLines[i];
  80585. if (!points) {
  80586. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80587. this._debugLines[i] = points;
  80588. }
  80589. this._getBonePosition(points[0], bone, meshMat);
  80590. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  80591. points[0].subtractInPlace(meshPos);
  80592. points[1].subtractInPlace(meshPos);
  80593. }
  80594. };
  80595. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  80596. var len = bones.length;
  80597. var boneNum = 0;
  80598. var meshPos = this.mesh.position;
  80599. for (var i = len - 1; i >= 0; i--) {
  80600. var childBone = bones[i];
  80601. var parentBone = childBone.getParent();
  80602. if (!parentBone) {
  80603. continue;
  80604. }
  80605. var points = this._debugLines[boneNum];
  80606. if (!points) {
  80607. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80608. this._debugLines[boneNum] = points;
  80609. }
  80610. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  80611. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  80612. points[0].subtractInPlace(meshPos);
  80613. points[1].subtractInPlace(meshPos);
  80614. boneNum++;
  80615. }
  80616. };
  80617. SkeletonViewer.prototype.update = function () {
  80618. if (this.autoUpdateBonesMatrices) {
  80619. this.skeleton.computeAbsoluteTransforms();
  80620. }
  80621. if (this.skeleton.bones[0].length === undefined) {
  80622. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  80623. }
  80624. else {
  80625. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  80626. }
  80627. if (!this._debugMesh) {
  80628. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  80629. this._debugMesh.renderingGroupId = this.renderingGroupId;
  80630. }
  80631. else {
  80632. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  80633. }
  80634. this._debugMesh.position.copyFrom(this.mesh.position);
  80635. this._debugMesh.color = this.color;
  80636. };
  80637. SkeletonViewer.prototype.dispose = function () {
  80638. if (this._debugMesh) {
  80639. this.isEnabled = false;
  80640. this._debugMesh.dispose();
  80641. this._debugMesh = null;
  80642. }
  80643. };
  80644. return SkeletonViewer;
  80645. }());
  80646. return Debug;
  80647. }());
  80648. BABYLON.Debug = Debug;
  80649. })(BABYLON || (BABYLON = {}));
  80650. //# sourceMappingURL=babylon.debugModules.js.map
  80651. "use strict";
  80652. var BABYLON;
  80653. (function (BABYLON) {
  80654. var RayHelper = /** @class */ (function () {
  80655. function RayHelper(ray) {
  80656. this.ray = ray;
  80657. }
  80658. RayHelper.CreateAndShow = function (ray, scene, color) {
  80659. var helper = new RayHelper(ray);
  80660. helper.show(scene, color);
  80661. return helper;
  80662. };
  80663. RayHelper.prototype.show = function (scene, color) {
  80664. if (!this._renderFunction && this.ray) {
  80665. var ray = this.ray;
  80666. this._renderFunction = this._render.bind(this);
  80667. this._scene = scene;
  80668. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  80669. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  80670. if (this._renderFunction) {
  80671. this._scene.registerBeforeRender(this._renderFunction);
  80672. }
  80673. }
  80674. if (color && this._renderLine) {
  80675. this._renderLine.color.copyFrom(color);
  80676. }
  80677. };
  80678. RayHelper.prototype.hide = function () {
  80679. if (this._renderFunction && this._scene) {
  80680. this._scene.unregisterBeforeRender(this._renderFunction);
  80681. this._scene = null;
  80682. this._renderFunction = null;
  80683. if (this._renderLine) {
  80684. this._renderLine.dispose();
  80685. this._renderLine = null;
  80686. }
  80687. this._renderPoints = [];
  80688. }
  80689. };
  80690. RayHelper.prototype._render = function () {
  80691. var ray = this.ray;
  80692. if (!ray) {
  80693. return;
  80694. }
  80695. var point = this._renderPoints[1];
  80696. var len = Math.min(ray.length, 1000000);
  80697. point.copyFrom(ray.direction);
  80698. point.scaleInPlace(len);
  80699. point.addInPlace(ray.origin);
  80700. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  80701. };
  80702. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  80703. this._attachedToMesh = mesh;
  80704. var ray = this.ray;
  80705. if (!ray) {
  80706. return;
  80707. }
  80708. if (!ray.direction) {
  80709. ray.direction = BABYLON.Vector3.Zero();
  80710. }
  80711. if (!ray.origin) {
  80712. ray.origin = BABYLON.Vector3.Zero();
  80713. }
  80714. if (length) {
  80715. ray.length = length;
  80716. }
  80717. if (!meshSpaceOrigin) {
  80718. meshSpaceOrigin = BABYLON.Vector3.Zero();
  80719. }
  80720. if (!meshSpaceDirection) {
  80721. // -1 so that this will work with Mesh.lookAt
  80722. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  80723. }
  80724. if (!this._meshSpaceDirection) {
  80725. this._meshSpaceDirection = meshSpaceDirection.clone();
  80726. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  80727. }
  80728. else {
  80729. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  80730. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  80731. }
  80732. if (!this._updateToMeshFunction) {
  80733. this._updateToMeshFunction = this._updateToMesh.bind(this);
  80734. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  80735. }
  80736. this._updateToMesh();
  80737. };
  80738. RayHelper.prototype.detachFromMesh = function () {
  80739. if (this._attachedToMesh) {
  80740. if (this._updateToMeshFunction) {
  80741. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  80742. }
  80743. this._attachedToMesh = null;
  80744. this._updateToMeshFunction = null;
  80745. }
  80746. };
  80747. RayHelper.prototype._updateToMesh = function () {
  80748. var ray = this.ray;
  80749. if (!this._attachedToMesh || !ray) {
  80750. return;
  80751. }
  80752. if (this._attachedToMesh._isDisposed) {
  80753. this.detachFromMesh();
  80754. return;
  80755. }
  80756. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  80757. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  80758. };
  80759. RayHelper.prototype.dispose = function () {
  80760. this.hide();
  80761. this.detachFromMesh();
  80762. this.ray = null;
  80763. };
  80764. return RayHelper;
  80765. }());
  80766. BABYLON.RayHelper = RayHelper;
  80767. })(BABYLON || (BABYLON = {}));
  80768. //# sourceMappingURL=babylon.rayHelper.js.map
  80769. "use strict";
  80770. var BABYLON;
  80771. (function (BABYLON) {
  80772. // load the inspector using require, if not present in the global namespace.
  80773. var DebugLayer = /** @class */ (function () {
  80774. function DebugLayer(scene) {
  80775. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  80776. this._scene = scene;
  80777. // load inspector using require, if it doesn't exist on the global namespace.
  80778. }
  80779. /** Creates the inspector window. */
  80780. DebugLayer.prototype._createInspector = function (config) {
  80781. if (config === void 0) { config = {}; }
  80782. var popup = config.popup || false;
  80783. var initialTab = config.initialTab || 0;
  80784. var parentElement = config.parentElement || null;
  80785. if (!this._inspector) {
  80786. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  80787. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  80788. } // else nothing to do,; instance is already existing
  80789. };
  80790. DebugLayer.prototype.isVisible = function () {
  80791. if (!this._inspector) {
  80792. return false;
  80793. }
  80794. return true;
  80795. };
  80796. DebugLayer.prototype.hide = function () {
  80797. if (this._inspector) {
  80798. try {
  80799. this._inspector.dispose();
  80800. }
  80801. catch (e) {
  80802. // If the inspector has been removed directly from the inspector tool
  80803. }
  80804. this._inspector = null;
  80805. }
  80806. };
  80807. DebugLayer.prototype.show = function (config) {
  80808. if (config === void 0) { config = {}; }
  80809. if (typeof this.BJSINSPECTOR == 'undefined') {
  80810. // Load inspector and add it to the DOM
  80811. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  80812. }
  80813. else {
  80814. // Otherwise creates the inspector
  80815. this._createInspector(config);
  80816. }
  80817. };
  80818. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  80819. return DebugLayer;
  80820. }());
  80821. BABYLON.DebugLayer = DebugLayer;
  80822. })(BABYLON || (BABYLON = {}));
  80823. //# sourceMappingURL=babylon.debugLayer.js.map
  80824. "use strict";
  80825. var BABYLON;
  80826. (function (BABYLON) {
  80827. var BoundingBoxRenderer = /** @class */ (function () {
  80828. function BoundingBoxRenderer(scene) {
  80829. this.frontColor = new BABYLON.Color3(1, 1, 1);
  80830. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  80831. this.showBackLines = true;
  80832. this.renderList = new BABYLON.SmartArray(32);
  80833. this._vertexBuffers = {};
  80834. this._scene = scene;
  80835. }
  80836. BoundingBoxRenderer.prototype._prepareRessources = function () {
  80837. if (this._colorShader) {
  80838. return;
  80839. }
  80840. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  80841. attributes: [BABYLON.VertexBuffer.PositionKind],
  80842. uniforms: ["world", "viewProjection", "color"]
  80843. });
  80844. var engine = this._scene.getEngine();
  80845. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  80846. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  80847. this._createIndexBuffer();
  80848. };
  80849. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  80850. var engine = this._scene.getEngine();
  80851. 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]);
  80852. };
  80853. BoundingBoxRenderer.prototype._rebuild = function () {
  80854. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  80855. if (vb) {
  80856. vb._rebuild();
  80857. }
  80858. this._createIndexBuffer();
  80859. };
  80860. BoundingBoxRenderer.prototype.reset = function () {
  80861. this.renderList.reset();
  80862. };
  80863. BoundingBoxRenderer.prototype.render = function () {
  80864. if (this.renderList.length === 0) {
  80865. return;
  80866. }
  80867. this._prepareRessources();
  80868. if (!this._colorShader.isReady()) {
  80869. return;
  80870. }
  80871. var engine = this._scene.getEngine();
  80872. engine.setDepthWrite(false);
  80873. this._colorShader._preBind();
  80874. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  80875. var boundingBox = this.renderList.data[boundingBoxIndex];
  80876. var min = boundingBox.minimum;
  80877. var max = boundingBox.maximum;
  80878. var diff = max.subtract(min);
  80879. var median = min.add(diff.scale(0.5));
  80880. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  80881. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  80882. .multiply(boundingBox.getWorldMatrix());
  80883. // VBOs
  80884. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  80885. if (this.showBackLines) {
  80886. // Back
  80887. engine.setDepthFunctionToGreaterOrEqual();
  80888. this._scene.resetCachedMaterial();
  80889. this._colorShader.setColor4("color", this.backColor.toColor4());
  80890. this._colorShader.bind(worldMatrix);
  80891. // Draw order
  80892. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  80893. }
  80894. // Front
  80895. engine.setDepthFunctionToLess();
  80896. this._scene.resetCachedMaterial();
  80897. this._colorShader.setColor4("color", this.frontColor.toColor4());
  80898. this._colorShader.bind(worldMatrix);
  80899. // Draw order
  80900. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  80901. }
  80902. this._colorShader.unbind();
  80903. engine.setDepthFunctionToLessOrEqual();
  80904. engine.setDepthWrite(true);
  80905. };
  80906. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  80907. this._prepareRessources();
  80908. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  80909. return;
  80910. }
  80911. var engine = this._scene.getEngine();
  80912. engine.setDepthWrite(false);
  80913. engine.setColorWrite(false);
  80914. this._colorShader._preBind();
  80915. var boundingBox = mesh._boundingInfo.boundingBox;
  80916. var min = boundingBox.minimum;
  80917. var max = boundingBox.maximum;
  80918. var diff = max.subtract(min);
  80919. var median = min.add(diff.scale(0.5));
  80920. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  80921. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  80922. .multiply(boundingBox.getWorldMatrix());
  80923. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  80924. engine.setDepthFunctionToLess();
  80925. this._scene.resetCachedMaterial();
  80926. this._colorShader.bind(worldMatrix);
  80927. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  80928. this._colorShader.unbind();
  80929. engine.setDepthFunctionToLessOrEqual();
  80930. engine.setDepthWrite(true);
  80931. engine.setColorWrite(true);
  80932. };
  80933. BoundingBoxRenderer.prototype.dispose = function () {
  80934. if (!this._colorShader) {
  80935. return;
  80936. }
  80937. this.renderList.dispose();
  80938. this._colorShader.dispose();
  80939. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  80940. if (buffer) {
  80941. buffer.dispose();
  80942. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  80943. }
  80944. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  80945. };
  80946. return BoundingBoxRenderer;
  80947. }());
  80948. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  80949. })(BABYLON || (BABYLON = {}));
  80950. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  80951. "use strict";
  80952. var BABYLON;
  80953. (function (BABYLON) {
  80954. var MorphTarget = /** @class */ (function () {
  80955. function MorphTarget(name, influence) {
  80956. if (influence === void 0) { influence = 0; }
  80957. this.name = name;
  80958. this.animations = new Array();
  80959. this._positions = null;
  80960. this._normals = null;
  80961. this._tangents = null;
  80962. this.onInfluenceChanged = new BABYLON.Observable();
  80963. this.influence = influence;
  80964. }
  80965. Object.defineProperty(MorphTarget.prototype, "influence", {
  80966. get: function () {
  80967. return this._influence;
  80968. },
  80969. set: function (influence) {
  80970. if (this._influence === influence) {
  80971. return;
  80972. }
  80973. var previous = this._influence;
  80974. this._influence = influence;
  80975. if (this.onInfluenceChanged.hasObservers) {
  80976. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  80977. }
  80978. },
  80979. enumerable: true,
  80980. configurable: true
  80981. });
  80982. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  80983. get: function () {
  80984. return !!this._positions;
  80985. },
  80986. enumerable: true,
  80987. configurable: true
  80988. });
  80989. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  80990. get: function () {
  80991. return !!this._normals;
  80992. },
  80993. enumerable: true,
  80994. configurable: true
  80995. });
  80996. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  80997. get: function () {
  80998. return !!this._tangents;
  80999. },
  81000. enumerable: true,
  81001. configurable: true
  81002. });
  81003. MorphTarget.prototype.setPositions = function (data) {
  81004. this._positions = data;
  81005. };
  81006. MorphTarget.prototype.getPositions = function () {
  81007. return this._positions;
  81008. };
  81009. MorphTarget.prototype.setNormals = function (data) {
  81010. this._normals = data;
  81011. };
  81012. MorphTarget.prototype.getNormals = function () {
  81013. return this._normals;
  81014. };
  81015. MorphTarget.prototype.setTangents = function (data) {
  81016. this._tangents = data;
  81017. };
  81018. MorphTarget.prototype.getTangents = function () {
  81019. return this._tangents;
  81020. };
  81021. /**
  81022. * Serializes the current target into a Serialization object.
  81023. * Returns the serialized object.
  81024. */
  81025. MorphTarget.prototype.serialize = function () {
  81026. var serializationObject = {};
  81027. serializationObject.name = this.name;
  81028. serializationObject.influence = this.influence;
  81029. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  81030. if (this.hasNormals) {
  81031. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  81032. }
  81033. if (this.hasTangents) {
  81034. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  81035. }
  81036. // Animations
  81037. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  81038. return serializationObject;
  81039. };
  81040. // Statics
  81041. MorphTarget.Parse = function (serializationObject) {
  81042. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  81043. result.setPositions(serializationObject.positions);
  81044. if (serializationObject.normals) {
  81045. result.setNormals(serializationObject.normals);
  81046. }
  81047. if (serializationObject.tangents) {
  81048. result.setTangents(serializationObject.tangents);
  81049. }
  81050. // Animations
  81051. if (serializationObject.animations) {
  81052. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  81053. var parsedAnimation = serializationObject.animations[animationIndex];
  81054. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  81055. }
  81056. }
  81057. return result;
  81058. };
  81059. MorphTarget.FromMesh = function (mesh, name, influence) {
  81060. if (!name) {
  81061. name = mesh.name;
  81062. }
  81063. var result = new MorphTarget(name, influence);
  81064. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  81065. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  81066. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  81067. }
  81068. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  81069. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  81070. }
  81071. return result;
  81072. };
  81073. return MorphTarget;
  81074. }());
  81075. BABYLON.MorphTarget = MorphTarget;
  81076. })(BABYLON || (BABYLON = {}));
  81077. //# sourceMappingURL=babylon.morphTarget.js.map
  81078. "use strict";
  81079. var BABYLON;
  81080. (function (BABYLON) {
  81081. var MorphTargetManager = /** @class */ (function () {
  81082. function MorphTargetManager(scene) {
  81083. if (scene === void 0) { scene = null; }
  81084. this._targets = new Array();
  81085. this._targetObservable = new Array();
  81086. this._activeTargets = new BABYLON.SmartArray(16);
  81087. this._supportsNormals = false;
  81088. this._supportsTangents = false;
  81089. this._vertexCount = 0;
  81090. this._uniqueId = 0;
  81091. this._tempInfluences = new Array();
  81092. if (!scene) {
  81093. scene = BABYLON.Engine.LastCreatedScene;
  81094. }
  81095. this._scene = scene;
  81096. if (this._scene) {
  81097. this._scene.morphTargetManagers.push(this);
  81098. this._uniqueId = this._scene.getUniqueId();
  81099. }
  81100. }
  81101. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  81102. get: function () {
  81103. return this._uniqueId;
  81104. },
  81105. enumerable: true,
  81106. configurable: true
  81107. });
  81108. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  81109. get: function () {
  81110. return this._vertexCount;
  81111. },
  81112. enumerable: true,
  81113. configurable: true
  81114. });
  81115. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  81116. get: function () {
  81117. return this._supportsNormals;
  81118. },
  81119. enumerable: true,
  81120. configurable: true
  81121. });
  81122. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  81123. get: function () {
  81124. return this._supportsTangents;
  81125. },
  81126. enumerable: true,
  81127. configurable: true
  81128. });
  81129. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  81130. get: function () {
  81131. return this._targets.length;
  81132. },
  81133. enumerable: true,
  81134. configurable: true
  81135. });
  81136. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  81137. get: function () {
  81138. return this._activeTargets.length;
  81139. },
  81140. enumerable: true,
  81141. configurable: true
  81142. });
  81143. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  81144. get: function () {
  81145. return this._influences;
  81146. },
  81147. enumerable: true,
  81148. configurable: true
  81149. });
  81150. MorphTargetManager.prototype.getActiveTarget = function (index) {
  81151. return this._activeTargets.data[index];
  81152. };
  81153. MorphTargetManager.prototype.getTarget = function (index) {
  81154. return this._targets[index];
  81155. };
  81156. MorphTargetManager.prototype.addTarget = function (target) {
  81157. var _this = this;
  81158. this._targets.push(target);
  81159. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  81160. _this._syncActiveTargets(needUpdate);
  81161. }));
  81162. this._syncActiveTargets(true);
  81163. };
  81164. MorphTargetManager.prototype.removeTarget = function (target) {
  81165. var index = this._targets.indexOf(target);
  81166. if (index >= 0) {
  81167. this._targets.splice(index, 1);
  81168. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  81169. this._syncActiveTargets(true);
  81170. }
  81171. };
  81172. /**
  81173. * Serializes the current manager into a Serialization object.
  81174. * Returns the serialized object.
  81175. */
  81176. MorphTargetManager.prototype.serialize = function () {
  81177. var serializationObject = {};
  81178. serializationObject.id = this.uniqueId;
  81179. serializationObject.targets = [];
  81180. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  81181. var target = _a[_i];
  81182. serializationObject.targets.push(target.serialize());
  81183. }
  81184. return serializationObject;
  81185. };
  81186. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  81187. var influenceCount = 0;
  81188. this._activeTargets.reset();
  81189. this._supportsNormals = true;
  81190. this._supportsTangents = true;
  81191. this._vertexCount = 0;
  81192. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  81193. var target = _a[_i];
  81194. this._activeTargets.push(target);
  81195. this._tempInfluences[influenceCount++] = target.influence;
  81196. var positions = target.getPositions();
  81197. if (positions) {
  81198. this._supportsNormals = this._supportsNormals && target.hasNormals;
  81199. this._supportsTangents = this._supportsTangents && target.hasTangents;
  81200. var vertexCount = positions.length / 3;
  81201. if (this._vertexCount === 0) {
  81202. this._vertexCount = vertexCount;
  81203. }
  81204. else if (this._vertexCount !== vertexCount) {
  81205. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  81206. return;
  81207. }
  81208. }
  81209. }
  81210. if (!this._influences || this._influences.length !== influenceCount) {
  81211. this._influences = new Float32Array(influenceCount);
  81212. }
  81213. for (var index = 0; index < influenceCount; index++) {
  81214. this._influences[index] = this._tempInfluences[index];
  81215. }
  81216. if (needUpdate && this._scene) {
  81217. // Flag meshes as dirty to resync with the active targets
  81218. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  81219. var mesh = _c[_b];
  81220. if (mesh.morphTargetManager === this) {
  81221. mesh._syncGeometryWithMorphTargetManager();
  81222. }
  81223. }
  81224. }
  81225. };
  81226. // Statics
  81227. MorphTargetManager.Parse = function (serializationObject, scene) {
  81228. var result = new MorphTargetManager(scene);
  81229. result._uniqueId = serializationObject.id;
  81230. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  81231. var targetData = _a[_i];
  81232. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  81233. }
  81234. return result;
  81235. };
  81236. return MorphTargetManager;
  81237. }());
  81238. BABYLON.MorphTargetManager = MorphTargetManager;
  81239. })(BABYLON || (BABYLON = {}));
  81240. //# sourceMappingURL=babylon.morphTargetManager.js.map
  81241. "use strict";
  81242. var BABYLON;
  81243. (function (BABYLON) {
  81244. var Octree = /** @class */ (function () {
  81245. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  81246. if (maxDepth === void 0) { maxDepth = 2; }
  81247. this.maxDepth = maxDepth;
  81248. this.dynamicContent = new Array();
  81249. this._maxBlockCapacity = maxBlockCapacity || 64;
  81250. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  81251. this._creationFunc = creationFunc;
  81252. }
  81253. // Methods
  81254. Octree.prototype.update = function (worldMin, worldMax, entries) {
  81255. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  81256. };
  81257. Octree.prototype.addMesh = function (entry) {
  81258. for (var index = 0; index < this.blocks.length; index++) {
  81259. var block = this.blocks[index];
  81260. block.addEntry(entry);
  81261. }
  81262. };
  81263. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  81264. this._selectionContent.reset();
  81265. for (var index = 0; index < this.blocks.length; index++) {
  81266. var block = this.blocks[index];
  81267. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  81268. }
  81269. if (allowDuplicate) {
  81270. this._selectionContent.concat(this.dynamicContent);
  81271. }
  81272. else {
  81273. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  81274. }
  81275. return this._selectionContent;
  81276. };
  81277. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  81278. this._selectionContent.reset();
  81279. for (var index = 0; index < this.blocks.length; index++) {
  81280. var block = this.blocks[index];
  81281. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  81282. }
  81283. if (allowDuplicate) {
  81284. this._selectionContent.concat(this.dynamicContent);
  81285. }
  81286. else {
  81287. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  81288. }
  81289. return this._selectionContent;
  81290. };
  81291. Octree.prototype.intersectsRay = function (ray) {
  81292. this._selectionContent.reset();
  81293. for (var index = 0; index < this.blocks.length; index++) {
  81294. var block = this.blocks[index];
  81295. block.intersectsRay(ray, this._selectionContent);
  81296. }
  81297. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  81298. return this._selectionContent;
  81299. };
  81300. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  81301. target.blocks = new Array();
  81302. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  81303. // Segmenting space
  81304. for (var x = 0; x < 2; x++) {
  81305. for (var y = 0; y < 2; y++) {
  81306. for (var z = 0; z < 2; z++) {
  81307. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  81308. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  81309. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  81310. block.addEntries(entries);
  81311. target.blocks.push(block);
  81312. }
  81313. }
  81314. }
  81315. };
  81316. Octree.CreationFuncForMeshes = function (entry, block) {
  81317. var boundingInfo = entry.getBoundingInfo();
  81318. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  81319. block.entries.push(entry);
  81320. }
  81321. };
  81322. Octree.CreationFuncForSubMeshes = function (entry, block) {
  81323. var boundingInfo = entry.getBoundingInfo();
  81324. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  81325. block.entries.push(entry);
  81326. }
  81327. };
  81328. return Octree;
  81329. }());
  81330. BABYLON.Octree = Octree;
  81331. })(BABYLON || (BABYLON = {}));
  81332. //# sourceMappingURL=babylon.octree.js.map
  81333. "use strict";
  81334. var BABYLON;
  81335. (function (BABYLON) {
  81336. var OctreeBlock = /** @class */ (function () {
  81337. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  81338. this.entries = new Array();
  81339. this._boundingVectors = new Array();
  81340. this._capacity = capacity;
  81341. this._depth = depth;
  81342. this._maxDepth = maxDepth;
  81343. this._creationFunc = creationFunc;
  81344. this._minPoint = minPoint;
  81345. this._maxPoint = maxPoint;
  81346. this._boundingVectors.push(minPoint.clone());
  81347. this._boundingVectors.push(maxPoint.clone());
  81348. this._boundingVectors.push(minPoint.clone());
  81349. this._boundingVectors[2].x = maxPoint.x;
  81350. this._boundingVectors.push(minPoint.clone());
  81351. this._boundingVectors[3].y = maxPoint.y;
  81352. this._boundingVectors.push(minPoint.clone());
  81353. this._boundingVectors[4].z = maxPoint.z;
  81354. this._boundingVectors.push(maxPoint.clone());
  81355. this._boundingVectors[5].z = minPoint.z;
  81356. this._boundingVectors.push(maxPoint.clone());
  81357. this._boundingVectors[6].x = minPoint.x;
  81358. this._boundingVectors.push(maxPoint.clone());
  81359. this._boundingVectors[7].y = minPoint.y;
  81360. }
  81361. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  81362. // Property
  81363. get: function () {
  81364. return this._capacity;
  81365. },
  81366. enumerable: true,
  81367. configurable: true
  81368. });
  81369. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  81370. get: function () {
  81371. return this._minPoint;
  81372. },
  81373. enumerable: true,
  81374. configurable: true
  81375. });
  81376. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  81377. get: function () {
  81378. return this._maxPoint;
  81379. },
  81380. enumerable: true,
  81381. configurable: true
  81382. });
  81383. // Methods
  81384. OctreeBlock.prototype.addEntry = function (entry) {
  81385. if (this.blocks) {
  81386. for (var index = 0; index < this.blocks.length; index++) {
  81387. var block = this.blocks[index];
  81388. block.addEntry(entry);
  81389. }
  81390. return;
  81391. }
  81392. this._creationFunc(entry, this);
  81393. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  81394. this.createInnerBlocks();
  81395. }
  81396. };
  81397. OctreeBlock.prototype.addEntries = function (entries) {
  81398. for (var index = 0; index < entries.length; index++) {
  81399. var mesh = entries[index];
  81400. this.addEntry(mesh);
  81401. }
  81402. };
  81403. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  81404. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  81405. if (this.blocks) {
  81406. for (var index = 0; index < this.blocks.length; index++) {
  81407. var block = this.blocks[index];
  81408. block.select(frustumPlanes, selection, allowDuplicate);
  81409. }
  81410. return;
  81411. }
  81412. if (allowDuplicate) {
  81413. selection.concat(this.entries);
  81414. }
  81415. else {
  81416. selection.concatWithNoDuplicate(this.entries);
  81417. }
  81418. }
  81419. };
  81420. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  81421. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  81422. if (this.blocks) {
  81423. for (var index = 0; index < this.blocks.length; index++) {
  81424. var block = this.blocks[index];
  81425. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  81426. }
  81427. return;
  81428. }
  81429. if (allowDuplicate) {
  81430. selection.concat(this.entries);
  81431. }
  81432. else {
  81433. selection.concatWithNoDuplicate(this.entries);
  81434. }
  81435. }
  81436. };
  81437. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  81438. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  81439. if (this.blocks) {
  81440. for (var index = 0; index < this.blocks.length; index++) {
  81441. var block = this.blocks[index];
  81442. block.intersectsRay(ray, selection);
  81443. }
  81444. return;
  81445. }
  81446. selection.concatWithNoDuplicate(this.entries);
  81447. }
  81448. };
  81449. OctreeBlock.prototype.createInnerBlocks = function () {
  81450. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  81451. };
  81452. return OctreeBlock;
  81453. }());
  81454. BABYLON.OctreeBlock = OctreeBlock;
  81455. })(BABYLON || (BABYLON = {}));
  81456. //# sourceMappingURL=babylon.octreeBlock.js.map
  81457. "use strict";
  81458. var BABYLON;
  81459. (function (BABYLON) {
  81460. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  81461. __extends(VRDistortionCorrectionPostProcess, _super);
  81462. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  81463. var _this = _super.call(this, name, "vrDistortionCorrection", [
  81464. 'LensCenter',
  81465. 'Scale',
  81466. 'ScaleIn',
  81467. 'HmdWarpParam'
  81468. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  81469. _this._isRightEye = isRightEye;
  81470. _this._distortionFactors = vrMetrics.distortionK;
  81471. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  81472. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  81473. _this.adaptScaleToCurrentViewport = true;
  81474. _this.onSizeChangedObservable.add(function () {
  81475. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  81476. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  81477. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  81478. });
  81479. _this.onApplyObservable.add(function (effect) {
  81480. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  81481. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  81482. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  81483. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  81484. });
  81485. return _this;
  81486. }
  81487. return VRDistortionCorrectionPostProcess;
  81488. }(BABYLON.PostProcess));
  81489. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  81490. })(BABYLON || (BABYLON = {}));
  81491. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  81492. "use strict";
  81493. var BABYLON;
  81494. (function (BABYLON) {
  81495. var AnaglyphPostProcess = /** @class */ (function (_super) {
  81496. __extends(AnaglyphPostProcess, _super);
  81497. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  81498. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  81499. _this._passedProcess = rigCameras[0]._rigPostProcess;
  81500. _this.onApplyObservable.add(function (effect) {
  81501. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  81502. });
  81503. return _this;
  81504. }
  81505. return AnaglyphPostProcess;
  81506. }(BABYLON.PostProcess));
  81507. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  81508. })(BABYLON || (BABYLON = {}));
  81509. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  81510. "use strict";
  81511. var BABYLON;
  81512. (function (BABYLON) {
  81513. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  81514. __extends(StereoscopicInterlacePostProcess, _super);
  81515. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  81516. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  81517. _this._passedProcess = rigCameras[0]._rigPostProcess;
  81518. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  81519. _this.onSizeChangedObservable.add(function () {
  81520. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  81521. });
  81522. _this.onApplyObservable.add(function (effect) {
  81523. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  81524. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  81525. });
  81526. return _this;
  81527. }
  81528. return StereoscopicInterlacePostProcess;
  81529. }(BABYLON.PostProcess));
  81530. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  81531. })(BABYLON || (BABYLON = {}));
  81532. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  81533. "use strict";
  81534. var BABYLON;
  81535. (function (BABYLON) {
  81536. /**
  81537. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  81538. * Screen rotation is taken into account.
  81539. */
  81540. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  81541. function FreeCameraDeviceOrientationInput() {
  81542. var _this = this;
  81543. this._screenOrientationAngle = 0;
  81544. this._screenQuaternion = new BABYLON.Quaternion();
  81545. this._alpha = 0;
  81546. this._beta = 0;
  81547. this._gamma = 0;
  81548. this._orientationChanged = function () {
  81549. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  81550. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  81551. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  81552. };
  81553. this._deviceOrientation = function (evt) {
  81554. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  81555. _this._beta = evt.beta !== null ? evt.beta : 0;
  81556. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  81557. };
  81558. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  81559. this._orientationChanged();
  81560. }
  81561. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  81562. get: function () {
  81563. return this._camera;
  81564. },
  81565. set: function (camera) {
  81566. this._camera = camera;
  81567. if (this._camera != null && !this._camera.rotationQuaternion) {
  81568. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  81569. }
  81570. },
  81571. enumerable: true,
  81572. configurable: true
  81573. });
  81574. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  81575. window.addEventListener("orientationchange", this._orientationChanged);
  81576. window.addEventListener("deviceorientation", this._deviceOrientation);
  81577. //In certain cases, the attach control is called AFTER orientation was changed,
  81578. //So this is needed.
  81579. this._orientationChanged();
  81580. };
  81581. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  81582. window.removeEventListener("orientationchange", this._orientationChanged);
  81583. window.removeEventListener("deviceorientation", this._deviceOrientation);
  81584. };
  81585. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  81586. //if no device orientation provided, don't update the rotation.
  81587. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  81588. if (!this._alpha)
  81589. return;
  81590. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  81591. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  81592. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  81593. //Mirror on XY Plane
  81594. this._camera.rotationQuaternion.z *= -1;
  81595. this._camera.rotationQuaternion.w *= -1;
  81596. };
  81597. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  81598. return "FreeCameraDeviceOrientationInput";
  81599. };
  81600. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  81601. return "deviceOrientation";
  81602. };
  81603. return FreeCameraDeviceOrientationInput;
  81604. }());
  81605. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  81606. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  81607. })(BABYLON || (BABYLON = {}));
  81608. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  81609. "use strict";
  81610. var BABYLON;
  81611. (function (BABYLON) {
  81612. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  81613. function ArcRotateCameraVRDeviceOrientationInput() {
  81614. this.alphaCorrection = 1;
  81615. this.betaCorrection = 1;
  81616. this.gammaCorrection = 1;
  81617. this._alpha = 0;
  81618. this._gamma = 0;
  81619. this._dirty = false;
  81620. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  81621. }
  81622. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  81623. this.camera.attachControl(element, noPreventDefault);
  81624. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  81625. };
  81626. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  81627. if (evt.alpha !== null) {
  81628. this._alpha = +evt.alpha | 0;
  81629. }
  81630. if (evt.gamma !== null) {
  81631. this._gamma = +evt.gamma | 0;
  81632. }
  81633. this._dirty = true;
  81634. };
  81635. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  81636. if (this._dirty) {
  81637. this._dirty = false;
  81638. if (this._gamma < 0) {
  81639. this._gamma = 180 + this._gamma;
  81640. }
  81641. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  81642. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  81643. }
  81644. };
  81645. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  81646. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  81647. };
  81648. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  81649. return "ArcRotateCameraVRDeviceOrientationInput";
  81650. };
  81651. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  81652. return "VRDeviceOrientation";
  81653. };
  81654. return ArcRotateCameraVRDeviceOrientationInput;
  81655. }());
  81656. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  81657. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  81658. })(BABYLON || (BABYLON = {}));
  81659. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  81660. "use strict";
  81661. var BABYLON;
  81662. (function (BABYLON) {
  81663. var VRCameraMetrics = /** @class */ (function () {
  81664. function VRCameraMetrics() {
  81665. this.compensateDistortion = true;
  81666. }
  81667. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  81668. get: function () {
  81669. return this.hResolution / (2 * this.vResolution);
  81670. },
  81671. enumerable: true,
  81672. configurable: true
  81673. });
  81674. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  81675. get: function () {
  81676. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  81677. },
  81678. enumerable: true,
  81679. configurable: true
  81680. });
  81681. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  81682. get: function () {
  81683. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  81684. var h = (4 * meters) / this.hScreenSize;
  81685. return BABYLON.Matrix.Translation(h, 0, 0);
  81686. },
  81687. enumerable: true,
  81688. configurable: true
  81689. });
  81690. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  81691. get: function () {
  81692. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  81693. var h = (4 * meters) / this.hScreenSize;
  81694. return BABYLON.Matrix.Translation(-h, 0, 0);
  81695. },
  81696. enumerable: true,
  81697. configurable: true
  81698. });
  81699. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  81700. get: function () {
  81701. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  81702. },
  81703. enumerable: true,
  81704. configurable: true
  81705. });
  81706. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  81707. get: function () {
  81708. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  81709. },
  81710. enumerable: true,
  81711. configurable: true
  81712. });
  81713. VRCameraMetrics.GetDefault = function () {
  81714. var result = new VRCameraMetrics();
  81715. result.hResolution = 1280;
  81716. result.vResolution = 800;
  81717. result.hScreenSize = 0.149759993;
  81718. result.vScreenSize = 0.0935999975;
  81719. result.vScreenCenter = 0.0467999987;
  81720. result.eyeToScreenDistance = 0.0410000011;
  81721. result.lensSeparationDistance = 0.0635000020;
  81722. result.interpupillaryDistance = 0.0640000030;
  81723. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  81724. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  81725. result.postProcessScaleFactor = 1.714605507808412;
  81726. result.lensCenterOffset = 0.151976421;
  81727. return result;
  81728. };
  81729. return VRCameraMetrics;
  81730. }());
  81731. BABYLON.VRCameraMetrics = VRCameraMetrics;
  81732. })(BABYLON || (BABYLON = {}));
  81733. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  81734. "use strict";
  81735. var BABYLON;
  81736. (function (BABYLON) {
  81737. /**
  81738. * This represents a WebVR camera.
  81739. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  81740. * @example http://doc.babylonjs.com/how_to/webvr_camera
  81741. */
  81742. var WebVRFreeCamera = /** @class */ (function (_super) {
  81743. __extends(WebVRFreeCamera, _super);
  81744. /**
  81745. * Instantiates a WebVRFreeCamera.
  81746. * @param name The name of the WebVRFreeCamera
  81747. * @param position The starting anchor position for the camera
  81748. * @param scene The scene the camera belongs to
  81749. * @param webVROptions a set of customizable options for the webVRCamera
  81750. */
  81751. function WebVRFreeCamera(name, position, scene, webVROptions) {
  81752. if (webVROptions === void 0) { webVROptions = {}; }
  81753. var _this = _super.call(this, name, position, scene) || this;
  81754. _this.webVROptions = webVROptions;
  81755. /**
  81756. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  81757. */
  81758. _this._vrDevice = null;
  81759. /**
  81760. * The rawPose of the vrDevice.
  81761. */
  81762. _this.rawPose = null;
  81763. _this._specsVersion = "1.1";
  81764. _this._attached = false;
  81765. _this._descendants = [];
  81766. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  81767. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  81768. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  81769. _this._standingMatrix = null;
  81770. /**
  81771. * Represents device position in babylon space.
  81772. */
  81773. _this.devicePosition = BABYLON.Vector3.Zero();
  81774. /**
  81775. * Represents device rotation in babylon space.
  81776. */
  81777. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  81778. /**
  81779. * The scale of the device to be used when translating from device space to babylon space.
  81780. */
  81781. _this.deviceScaleFactor = 1;
  81782. _this._deviceToWorld = BABYLON.Matrix.Identity();
  81783. _this._worldToDevice = BABYLON.Matrix.Identity();
  81784. /**
  81785. * References to the webVR controllers for the vrDevice.
  81786. */
  81787. _this.controllers = [];
  81788. /**
  81789. * Emits an event when a controller is attached.
  81790. */
  81791. _this.onControllersAttachedObservable = new BABYLON.Observable();
  81792. /**
  81793. * Emits an event when a controller's mesh has been loaded;
  81794. */
  81795. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  81796. /**
  81797. * If the rig cameras be used as parent instead of this camera.
  81798. */
  81799. _this.rigParenting = true;
  81800. _this._defaultHeight = undefined;
  81801. _this._workingVector = BABYLON.Vector3.Zero();
  81802. _this._oneVector = BABYLON.Vector3.One();
  81803. _this._workingMatrix = BABYLON.Matrix.Identity();
  81804. _this._cache.position = BABYLON.Vector3.Zero();
  81805. if (webVROptions.defaultHeight) {
  81806. _this._defaultHeight = webVROptions.defaultHeight;
  81807. _this.position.y = _this._defaultHeight;
  81808. }
  81809. _this.minZ = 0.1;
  81810. //legacy support - the compensation boolean was removed.
  81811. if (arguments.length === 5) {
  81812. _this.webVROptions = arguments[4];
  81813. }
  81814. // default webVR options
  81815. if (_this.webVROptions.trackPosition == undefined) {
  81816. _this.webVROptions.trackPosition = true;
  81817. }
  81818. if (_this.webVROptions.controllerMeshes == undefined) {
  81819. _this.webVROptions.controllerMeshes = true;
  81820. }
  81821. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  81822. _this.webVROptions.defaultLightingOnControllers = true;
  81823. }
  81824. _this.rotationQuaternion = new BABYLON.Quaternion();
  81825. if (_this.webVROptions && _this.webVROptions.positionScale) {
  81826. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  81827. }
  81828. //enable VR
  81829. var engine = _this.getEngine();
  81830. _this._onVREnabled = function (success) { if (success) {
  81831. _this.initControllers();
  81832. } };
  81833. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  81834. engine.initWebVR().add(function (event) {
  81835. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  81836. return;
  81837. }
  81838. _this._vrDevice = event.vrDisplay;
  81839. //reset the rig parameters.
  81840. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  81841. if (_this._attached) {
  81842. _this.getEngine().enableVR();
  81843. }
  81844. });
  81845. if (typeof (VRFrameData) !== "undefined")
  81846. _this._frameData = new VRFrameData();
  81847. /**
  81848. * The idea behind the following lines:
  81849. * objects that have the camera as parent should actually have the rig cameras as a parent.
  81850. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  81851. * the second will not show it correctly.
  81852. *
  81853. * To solve this - each object that has the camera as parent will be added to a protected array.
  81854. * When the rig camera renders, it will take this array and set all of those to be its children.
  81855. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  81856. * Amazing!
  81857. */
  81858. scene.onBeforeCameraRenderObservable.add(function (camera) {
  81859. if (camera.parent === _this && _this.rigParenting) {
  81860. _this._descendants = _this.getDescendants(true, function (n) {
  81861. // don't take the cameras or the controllers!
  81862. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  81863. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  81864. return !isController && !isRigCamera;
  81865. });
  81866. _this._descendants.forEach(function (node) {
  81867. node.parent = camera;
  81868. });
  81869. }
  81870. });
  81871. scene.onAfterCameraRenderObservable.add(function (camera) {
  81872. if (camera.parent === _this && _this.rigParenting) {
  81873. _this._descendants.forEach(function (node) {
  81874. node.parent = _this;
  81875. });
  81876. }
  81877. });
  81878. return _this;
  81879. }
  81880. /**
  81881. * Gets the device distance from the ground in meters.
  81882. * @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.
  81883. */
  81884. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  81885. if (this._standingMatrix) {
  81886. // Add standing matrix offset to get real offset from ground in room
  81887. this._standingMatrix.getTranslationToRef(this._workingVector);
  81888. return this._deviceRoomPosition.y + this._workingVector.y;
  81889. }
  81890. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  81891. return this._defaultHeight || 0;
  81892. };
  81893. /**
  81894. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  81895. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  81896. */
  81897. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  81898. var _this = this;
  81899. if (callback === void 0) { callback = function (bool) { }; }
  81900. // Use standing matrix if available
  81901. this.getEngine().initWebVRAsync().then(function (result) {
  81902. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  81903. callback(false);
  81904. }
  81905. else {
  81906. _this._standingMatrix = new BABYLON.Matrix();
  81907. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  81908. if (!_this.getScene().useRightHandedSystem) {
  81909. [2, 6, 8, 9, 14].forEach(function (num) {
  81910. if (_this._standingMatrix) {
  81911. _this._standingMatrix.m[num] *= -1;
  81912. }
  81913. });
  81914. }
  81915. callback(true);
  81916. }
  81917. });
  81918. };
  81919. /**
  81920. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  81921. * @returns A promise with a boolean set to if the standing matrix is supported.
  81922. */
  81923. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  81924. var _this = this;
  81925. return new Promise(function (res, rej) {
  81926. _this.useStandingMatrix(function (supported) {
  81927. res(supported);
  81928. });
  81929. });
  81930. };
  81931. /**
  81932. * Disposes the camera
  81933. */
  81934. WebVRFreeCamera.prototype.dispose = function () {
  81935. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  81936. _super.prototype.dispose.call(this);
  81937. };
  81938. /**
  81939. * Gets a vrController by name.
  81940. * @param name The name of the controller to retreive
  81941. * @returns the controller matching the name specified or null if not found
  81942. */
  81943. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  81944. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  81945. var gp = _a[_i];
  81946. if (gp.hand === name) {
  81947. return gp;
  81948. }
  81949. }
  81950. return null;
  81951. };
  81952. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  81953. /**
  81954. * The controller corrisponding to the users left hand.
  81955. */
  81956. get: function () {
  81957. if (!this._leftController) {
  81958. this._leftController = this.getControllerByName("left");
  81959. }
  81960. return this._leftController;
  81961. },
  81962. enumerable: true,
  81963. configurable: true
  81964. });
  81965. ;
  81966. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  81967. /**
  81968. * The controller corrisponding to the users right hand.
  81969. */
  81970. get: function () {
  81971. if (!this._rightController) {
  81972. this._rightController = this.getControllerByName("right");
  81973. }
  81974. return this._rightController;
  81975. },
  81976. enumerable: true,
  81977. configurable: true
  81978. });
  81979. ;
  81980. /**
  81981. * Casts a ray forward from the vrCamera's gaze.
  81982. * @param length Length of the ray (default: 100)
  81983. * @returns the ray corrisponding to the gaze
  81984. */
  81985. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  81986. if (length === void 0) { length = 100; }
  81987. if (this.leftCamera) {
  81988. // Use left eye to avoid computation to compute center on every call
  81989. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  81990. }
  81991. else {
  81992. return _super.prototype.getForwardRay.call(this, length);
  81993. }
  81994. };
  81995. /**
  81996. * Updates the camera based on device's frame data
  81997. */
  81998. WebVRFreeCamera.prototype._checkInputs = function () {
  81999. if (this._vrDevice && this._vrDevice.isPresenting) {
  82000. this._vrDevice.getFrameData(this._frameData);
  82001. this.updateFromDevice(this._frameData.pose);
  82002. }
  82003. _super.prototype._checkInputs.call(this);
  82004. };
  82005. /**
  82006. * Updates the poseControlled values based on the input device pose.
  82007. * @param poseData Pose coming from the device
  82008. */
  82009. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  82010. if (poseData && poseData.orientation) {
  82011. this.rawPose = poseData;
  82012. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  82013. if (this.getScene().useRightHandedSystem) {
  82014. this._deviceRoomRotationQuaternion.z *= -1;
  82015. this._deviceRoomRotationQuaternion.w *= -1;
  82016. }
  82017. if (this.webVROptions.trackPosition && this.rawPose.position) {
  82018. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  82019. if (this.getScene().useRightHandedSystem) {
  82020. this._deviceRoomPosition.z *= -1;
  82021. }
  82022. }
  82023. }
  82024. };
  82025. /**
  82026. * WebVR's attach control will start broadcasting frames to the device.
  82027. * Note that in certain browsers (chrome for example) this function must be called
  82028. * within a user-interaction callback. Example:
  82029. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  82030. *
  82031. * @param element html element to attach the vrDevice to
  82032. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  82033. */
  82034. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  82035. _super.prototype.attachControl.call(this, element, noPreventDefault);
  82036. this._attached = true;
  82037. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  82038. if (this._vrDevice) {
  82039. this.getEngine().enableVR();
  82040. }
  82041. };
  82042. /**
  82043. * Detaches the camera from the html element and disables VR
  82044. *
  82045. * @param element html element to detach from
  82046. */
  82047. WebVRFreeCamera.prototype.detachControl = function (element) {
  82048. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  82049. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  82050. _super.prototype.detachControl.call(this, element);
  82051. this._attached = false;
  82052. this.getEngine().disableVR();
  82053. };
  82054. /**
  82055. * @returns the name of this class
  82056. */
  82057. WebVRFreeCamera.prototype.getClassName = function () {
  82058. return "WebVRFreeCamera";
  82059. };
  82060. /**
  82061. * Calls resetPose on the vrDisplay
  82062. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  82063. */
  82064. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  82065. //uses the vrDisplay's "resetPose()".
  82066. //pitch and roll won't be affected.
  82067. this._vrDevice.resetPose();
  82068. };
  82069. /**
  82070. * Updates the rig cameras (left and right eye)
  82071. */
  82072. WebVRFreeCamera.prototype._updateRigCameras = function () {
  82073. var camLeft = this._rigCameras[0];
  82074. var camRight = this._rigCameras[1];
  82075. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  82076. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  82077. camLeft.position.copyFrom(this._deviceRoomPosition);
  82078. camRight.position.copyFrom(this._deviceRoomPosition);
  82079. };
  82080. /**
  82081. * Updates the cached values of the camera
  82082. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  82083. */
  82084. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  82085. var _this = this;
  82086. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  82087. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  82088. if (!this.updateCacheCalled) {
  82089. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  82090. this.updateCacheCalled = true;
  82091. this.update();
  82092. }
  82093. // Set working vector to the device position in room space rotated by the new rotation
  82094. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  82095. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  82096. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  82097. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  82098. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  82099. // Add translation from anchor position
  82100. this._deviceToWorld.getTranslationToRef(this._workingVector);
  82101. this._workingVector.addInPlace(this.position);
  82102. this._workingVector.subtractInPlace(this._cache.position);
  82103. this._deviceToWorld.setTranslation(this._workingVector);
  82104. // Set an inverted matrix to be used when updating the camera
  82105. this._deviceToWorld.invertToRef(this._worldToDevice);
  82106. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  82107. this.controllers.forEach(function (controller) {
  82108. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  82109. controller.update();
  82110. });
  82111. }
  82112. if (!ignoreParentClass) {
  82113. _super.prototype._updateCache.call(this);
  82114. }
  82115. this.updateCacheCalled = false;
  82116. };
  82117. /**
  82118. * Updates the current device position and rotation in the babylon world
  82119. */
  82120. WebVRFreeCamera.prototype.update = function () {
  82121. // Get current device position in babylon world
  82122. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  82123. // Get current device rotation in babylon world
  82124. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  82125. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  82126. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  82127. _super.prototype.update.call(this);
  82128. };
  82129. /**
  82130. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  82131. * @returns an identity matrix
  82132. */
  82133. WebVRFreeCamera.prototype._getViewMatrix = function () {
  82134. return BABYLON.Matrix.Identity();
  82135. };
  82136. /**
  82137. * This function is called by the two RIG cameras.
  82138. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  82139. */
  82140. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  82141. var _this = this;
  82142. // Update the parent camera prior to using a child camera to avoid desynchronization
  82143. var parentCamera = this._cameraRigParams["parentCamera"];
  82144. parentCamera._updateCache();
  82145. //WebVR 1.1
  82146. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  82147. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  82148. if (!this.getScene().useRightHandedSystem) {
  82149. [2, 6, 8, 9, 14].forEach(function (num) {
  82150. _this._webvrViewMatrix.m[num] *= -1;
  82151. });
  82152. }
  82153. // update the camera rotation matrix
  82154. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  82155. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  82156. // Computing target and final matrix
  82157. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  82158. // should the view matrix be updated with scale and position offset?
  82159. if (parentCamera.deviceScaleFactor !== 1) {
  82160. this._webvrViewMatrix.invert();
  82161. // scale the position, if set
  82162. if (parentCamera.deviceScaleFactor) {
  82163. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  82164. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  82165. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  82166. }
  82167. this._webvrViewMatrix.invert();
  82168. }
  82169. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  82170. return this._webvrViewMatrix;
  82171. };
  82172. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  82173. var _this = this;
  82174. var parentCamera = this.parent;
  82175. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  82176. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  82177. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  82178. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  82179. //babylon compatible matrix
  82180. if (!this.getScene().useRightHandedSystem) {
  82181. [8, 9, 10, 11].forEach(function (num) {
  82182. _this._projectionMatrix.m[num] *= -1;
  82183. });
  82184. }
  82185. return this._projectionMatrix;
  82186. };
  82187. /**
  82188. * Initializes the controllers and their meshes
  82189. */
  82190. WebVRFreeCamera.prototype.initControllers = function () {
  82191. var _this = this;
  82192. this.controllers = [];
  82193. var manager = this.getScene().gamepadManager;
  82194. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  82195. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  82196. var webVrController = gamepad;
  82197. if (webVrController.defaultModel) {
  82198. webVrController.defaultModel.setEnabled(false);
  82199. }
  82200. if (webVrController.hand === "right") {
  82201. _this._rightController = null;
  82202. }
  82203. if (webVrController.hand === "left") {
  82204. _this._leftController = null;
  82205. }
  82206. var controllerIndex = _this.controllers.indexOf(webVrController);
  82207. if (controllerIndex !== -1) {
  82208. _this.controllers.splice(controllerIndex, 1);
  82209. }
  82210. }
  82211. });
  82212. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  82213. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  82214. var webVrController_1 = gamepad;
  82215. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  82216. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  82217. if (_this.webVROptions.controllerMeshes) {
  82218. if (webVrController_1.defaultModel) {
  82219. webVrController_1.defaultModel.setEnabled(true);
  82220. }
  82221. else {
  82222. // Load the meshes
  82223. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  82224. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  82225. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  82226. if (_this.webVROptions.defaultLightingOnControllers) {
  82227. if (!_this._lightOnControllers) {
  82228. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  82229. }
  82230. var activateLightOnSubMeshes_1 = function (mesh, light) {
  82231. var children = mesh.getChildren();
  82232. if (children.length !== 0) {
  82233. children.forEach(function (mesh) {
  82234. light.includedOnlyMeshes.push(mesh);
  82235. activateLightOnSubMeshes_1(mesh, light);
  82236. });
  82237. }
  82238. };
  82239. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  82240. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  82241. }
  82242. });
  82243. }
  82244. }
  82245. webVrController_1.attachToPoseControlledCamera(_this);
  82246. // since this is async - sanity check. Is the controller already stored?
  82247. if (_this.controllers.indexOf(webVrController_1) === -1) {
  82248. //add to the controllers array
  82249. _this.controllers.push(webVrController_1);
  82250. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  82251. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  82252. // So we're overriding setting left & right manually to be sure
  82253. var firstViveWandDetected = false;
  82254. for (var i = 0; i < _this.controllers.length; i++) {
  82255. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  82256. if (!firstViveWandDetected) {
  82257. firstViveWandDetected = true;
  82258. _this.controllers[i].hand = "left";
  82259. }
  82260. else {
  82261. _this.controllers[i].hand = "right";
  82262. }
  82263. }
  82264. }
  82265. //did we find enough controllers? Great! let the developer know.
  82266. if (_this.controllers.length >= 2) {
  82267. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  82268. }
  82269. }
  82270. }
  82271. });
  82272. };
  82273. return WebVRFreeCamera;
  82274. }(BABYLON.FreeCamera));
  82275. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  82276. })(BABYLON || (BABYLON = {}));
  82277. //# sourceMappingURL=babylon.webVRCamera.js.map
  82278. "use strict";
  82279. var BABYLON;
  82280. (function (BABYLON) {
  82281. // We're mainly based on the logic defined into the FreeCamera code
  82282. /**
  82283. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  82284. * being tilted forward or back and left or right.
  82285. */
  82286. var DeviceOrientationCamera = /** @class */ (function (_super) {
  82287. __extends(DeviceOrientationCamera, _super);
  82288. /**
  82289. * Creates a new device orientation camera. @see DeviceOrientationCamera
  82290. * @param name The name of the camera
  82291. * @param position The start position camera
  82292. * @param scene The scene the camera belongs to
  82293. */
  82294. function DeviceOrientationCamera(name, position, scene) {
  82295. var _this = _super.call(this, name, position, scene) || this;
  82296. _this._quaternionCache = new BABYLON.Quaternion();
  82297. _this.inputs.addDeviceOrientation();
  82298. return _this;
  82299. }
  82300. /**
  82301. * Gets the current instance class name ("DeviceOrientationCamera").
  82302. * This helps avoiding instanceof at run time.
  82303. * @returns the class name
  82304. */
  82305. DeviceOrientationCamera.prototype.getClassName = function () {
  82306. return "DeviceOrientationCamera";
  82307. };
  82308. /**
  82309. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  82310. */
  82311. DeviceOrientationCamera.prototype._checkInputs = function () {
  82312. _super.prototype._checkInputs.call(this);
  82313. this._quaternionCache.copyFrom(this.rotationQuaternion);
  82314. if (this._initialQuaternion) {
  82315. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  82316. }
  82317. };
  82318. /**
  82319. * Reset the camera to its default orientation on the specified axis only.
  82320. * @param axis The axis to reset
  82321. */
  82322. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  82323. var _this = this;
  82324. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  82325. //can only work if this camera has a rotation quaternion already.
  82326. if (!this.rotationQuaternion)
  82327. return;
  82328. if (!this._initialQuaternion) {
  82329. this._initialQuaternion = new BABYLON.Quaternion();
  82330. }
  82331. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  82332. ['x', 'y', 'z'].forEach(function (axisName) {
  82333. if (!axis[axisName]) {
  82334. _this._initialQuaternion[axisName] = 0;
  82335. }
  82336. else {
  82337. _this._initialQuaternion[axisName] *= -1;
  82338. }
  82339. });
  82340. this._initialQuaternion.normalize();
  82341. //force rotation update
  82342. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  82343. };
  82344. return DeviceOrientationCamera;
  82345. }(BABYLON.FreeCamera));
  82346. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  82347. })(BABYLON || (BABYLON = {}));
  82348. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  82349. "use strict";
  82350. var BABYLON;
  82351. (function (BABYLON) {
  82352. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  82353. __extends(VRDeviceOrientationFreeCamera, _super);
  82354. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  82355. if (compensateDistortion === void 0) { compensateDistortion = true; }
  82356. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  82357. var _this = _super.call(this, name, position, scene) || this;
  82358. vrCameraMetrics.compensateDistortion = compensateDistortion;
  82359. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  82360. return _this;
  82361. }
  82362. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  82363. return "VRDeviceOrientationFreeCamera";
  82364. };
  82365. return VRDeviceOrientationFreeCamera;
  82366. }(BABYLON.DeviceOrientationCamera));
  82367. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  82368. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  82369. __extends(VRDeviceOrientationGamepadCamera, _super);
  82370. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  82371. if (compensateDistortion === void 0) { compensateDistortion = true; }
  82372. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  82373. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  82374. _this.inputs.addGamepad();
  82375. return _this;
  82376. }
  82377. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  82378. return "VRDeviceOrientationGamepadCamera";
  82379. };
  82380. return VRDeviceOrientationGamepadCamera;
  82381. }(VRDeviceOrientationFreeCamera));
  82382. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  82383. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  82384. __extends(VRDeviceOrientationArcRotateCamera, _super);
  82385. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  82386. if (compensateDistortion === void 0) { compensateDistortion = true; }
  82387. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  82388. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  82389. vrCameraMetrics.compensateDistortion = compensateDistortion;
  82390. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  82391. _this.inputs.addVRDeviceOrientation();
  82392. return _this;
  82393. }
  82394. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  82395. return "VRDeviceOrientationArcRotateCamera";
  82396. };
  82397. return VRDeviceOrientationArcRotateCamera;
  82398. }(BABYLON.ArcRotateCamera));
  82399. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  82400. })(BABYLON || (BABYLON = {}));
  82401. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  82402. "use strict";
  82403. var BABYLON;
  82404. (function (BABYLON) {
  82405. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  82406. __extends(AnaglyphFreeCamera, _super);
  82407. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  82408. var _this = _super.call(this, name, position, scene) || this;
  82409. _this.interaxialDistance = interaxialDistance;
  82410. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  82411. return _this;
  82412. }
  82413. AnaglyphFreeCamera.prototype.getClassName = function () {
  82414. return "AnaglyphFreeCamera";
  82415. };
  82416. return AnaglyphFreeCamera;
  82417. }(BABYLON.FreeCamera));
  82418. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  82419. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  82420. __extends(AnaglyphArcRotateCamera, _super);
  82421. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  82422. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  82423. _this.interaxialDistance = interaxialDistance;
  82424. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  82425. return _this;
  82426. }
  82427. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  82428. return "AnaglyphArcRotateCamera";
  82429. };
  82430. return AnaglyphArcRotateCamera;
  82431. }(BABYLON.ArcRotateCamera));
  82432. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  82433. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  82434. __extends(AnaglyphGamepadCamera, _super);
  82435. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  82436. var _this = _super.call(this, name, position, scene) || this;
  82437. _this.interaxialDistance = interaxialDistance;
  82438. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  82439. return _this;
  82440. }
  82441. AnaglyphGamepadCamera.prototype.getClassName = function () {
  82442. return "AnaglyphGamepadCamera";
  82443. };
  82444. return AnaglyphGamepadCamera;
  82445. }(BABYLON.GamepadCamera));
  82446. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  82447. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  82448. __extends(AnaglyphUniversalCamera, _super);
  82449. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  82450. var _this = _super.call(this, name, position, scene) || this;
  82451. _this.interaxialDistance = interaxialDistance;
  82452. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  82453. return _this;
  82454. }
  82455. AnaglyphUniversalCamera.prototype.getClassName = function () {
  82456. return "AnaglyphUniversalCamera";
  82457. };
  82458. return AnaglyphUniversalCamera;
  82459. }(BABYLON.UniversalCamera));
  82460. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  82461. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  82462. __extends(StereoscopicFreeCamera, _super);
  82463. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  82464. var _this = _super.call(this, name, position, scene) || this;
  82465. _this.interaxialDistance = interaxialDistance;
  82466. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  82467. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  82468. return _this;
  82469. }
  82470. StereoscopicFreeCamera.prototype.getClassName = function () {
  82471. return "StereoscopicFreeCamera";
  82472. };
  82473. return StereoscopicFreeCamera;
  82474. }(BABYLON.FreeCamera));
  82475. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  82476. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  82477. __extends(StereoscopicArcRotateCamera, _super);
  82478. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  82479. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  82480. _this.interaxialDistance = interaxialDistance;
  82481. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  82482. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  82483. return _this;
  82484. }
  82485. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  82486. return "StereoscopicArcRotateCamera";
  82487. };
  82488. return StereoscopicArcRotateCamera;
  82489. }(BABYLON.ArcRotateCamera));
  82490. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  82491. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  82492. __extends(StereoscopicGamepadCamera, _super);
  82493. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  82494. var _this = _super.call(this, name, position, scene) || this;
  82495. _this.interaxialDistance = interaxialDistance;
  82496. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  82497. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  82498. return _this;
  82499. }
  82500. StereoscopicGamepadCamera.prototype.getClassName = function () {
  82501. return "StereoscopicGamepadCamera";
  82502. };
  82503. return StereoscopicGamepadCamera;
  82504. }(BABYLON.GamepadCamera));
  82505. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  82506. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  82507. __extends(StereoscopicUniversalCamera, _super);
  82508. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  82509. var _this = _super.call(this, name, position, scene) || this;
  82510. _this.interaxialDistance = interaxialDistance;
  82511. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  82512. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  82513. return _this;
  82514. }
  82515. StereoscopicUniversalCamera.prototype.getClassName = function () {
  82516. return "StereoscopicUniversalCamera";
  82517. };
  82518. return StereoscopicUniversalCamera;
  82519. }(BABYLON.UniversalCamera));
  82520. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  82521. })(BABYLON || (BABYLON = {}));
  82522. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  82523. "use strict";
  82524. var BABYLON;
  82525. (function (BABYLON) {
  82526. var VRExperienceHelperGazer = /** @class */ (function () {
  82527. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  82528. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  82529. this.scene = scene;
  82530. this._pointerDownOnMeshAsked = false;
  82531. this._isActionableMesh = false;
  82532. this._teleportationRequestInitiated = false;
  82533. this._teleportationBackRequestInitiated = false;
  82534. this._dpadPressed = true;
  82535. this._activePointer = false;
  82536. this._id = VRExperienceHelperGazer._idCounter++;
  82537. // Gaze tracker
  82538. if (!gazeTrackerToClone) {
  82539. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  82540. this._gazeTracker.bakeCurrentTransformIntoVertices();
  82541. this._gazeTracker.isPickable = false;
  82542. this._gazeTracker.isVisible = false;
  82543. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  82544. targetMat.specularColor = BABYLON.Color3.Black();
  82545. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  82546. targetMat.backFaceCulling = false;
  82547. this._gazeTracker.material = targetMat;
  82548. }
  82549. else {
  82550. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  82551. }
  82552. }
  82553. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  82554. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  82555. };
  82556. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  82557. this._pointerDownOnMeshAsked = true;
  82558. if (this._currentMeshSelected && this._currentHit) {
  82559. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  82560. }
  82561. };
  82562. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  82563. if (this._currentMeshSelected && this._currentHit) {
  82564. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  82565. }
  82566. this._pointerDownOnMeshAsked = false;
  82567. };
  82568. VRExperienceHelperGazer.prototype._activatePointer = function () {
  82569. this._activePointer = true;
  82570. };
  82571. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  82572. this._activePointer = false;
  82573. };
  82574. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  82575. };
  82576. VRExperienceHelperGazer.prototype.dispose = function () {
  82577. this._interactionsEnabled = false;
  82578. this._teleportationEnabled = false;
  82579. };
  82580. VRExperienceHelperGazer._idCounter = 0;
  82581. return VRExperienceHelperGazer;
  82582. }());
  82583. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  82584. __extends(VRExperienceHelperControllerGazer, _super);
  82585. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  82586. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  82587. _this.webVRController = webVRController;
  82588. // Laser pointer
  82589. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  82590. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  82591. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  82592. laserPointerMaterial.alpha = 0.6;
  82593. _this._laserPointer.material = laserPointerMaterial;
  82594. _this._laserPointer.rotation.x = Math.PI / 2;
  82595. _this._laserPointer.position.z = -0.5;
  82596. _this._laserPointer.isVisible = false;
  82597. if (!webVRController.mesh) {
  82598. // Create an empty mesh that is used prior to loading the high quality model
  82599. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  82600. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  82601. preloadPointerPose.rotation.x = -0.7;
  82602. preloadMesh.addChild(preloadPointerPose);
  82603. webVRController.attachToMesh(preloadMesh);
  82604. }
  82605. _this._setLaserPointerParent(webVRController.mesh);
  82606. return _this;
  82607. }
  82608. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  82609. return this.webVRController.getForwardRay(length);
  82610. };
  82611. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  82612. _super.prototype._activatePointer.call(this);
  82613. this._laserPointer.isVisible = true;
  82614. };
  82615. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  82616. _super.prototype._deactivatePointer.call(this);
  82617. this._laserPointer.isVisible = false;
  82618. };
  82619. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  82620. this._laserPointer.material.emissiveColor = color;
  82621. };
  82622. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  82623. var makeNotPick = function (root) {
  82624. root.name += " laserPointer";
  82625. root.getChildMeshes().forEach(function (c) {
  82626. makeNotPick(c);
  82627. });
  82628. };
  82629. makeNotPick(mesh);
  82630. var childMeshes = mesh.getChildMeshes();
  82631. this.webVRController._pointingPoseNode = null;
  82632. for (var i = 0; i < childMeshes.length; i++) {
  82633. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  82634. mesh = childMeshes[i];
  82635. this.webVRController._pointingPoseNode = mesh;
  82636. break;
  82637. }
  82638. }
  82639. this._laserPointer.parent = mesh;
  82640. };
  82641. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  82642. this._laserPointer.scaling.y = distance;
  82643. this._laserPointer.position.z = -distance / 2;
  82644. };
  82645. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  82646. _super.prototype.dispose.call(this);
  82647. this._laserPointer.dispose();
  82648. };
  82649. return VRExperienceHelperControllerGazer;
  82650. }(VRExperienceHelperGazer));
  82651. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  82652. __extends(VRExperienceHelperCameraGazer, _super);
  82653. function VRExperienceHelperCameraGazer(getCamera, scene) {
  82654. var _this = _super.call(this, scene) || this;
  82655. _this.getCamera = getCamera;
  82656. return _this;
  82657. }
  82658. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  82659. var camera = this.getCamera();
  82660. if (camera) {
  82661. return camera.getForwardRay(length);
  82662. }
  82663. else {
  82664. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  82665. }
  82666. };
  82667. return VRExperienceHelperCameraGazer;
  82668. }(VRExperienceHelperGazer));
  82669. /**
  82670. * Helps to quickly add VR support to an existing scene.
  82671. * See http://doc.babylonjs.com/how_to/webvr_helper
  82672. */
  82673. var VRExperienceHelper = /** @class */ (function () {
  82674. /**
  82675. * Instantiates a VRExperienceHelper.
  82676. * Helps to quickly add VR support to an existing scene.
  82677. * @param scene The scene the VRExperienceHelper belongs to.
  82678. * @param webVROptions Options to modify the vr experience helper's behavior.
  82679. */
  82680. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  82681. if (webVROptions === void 0) { webVROptions = {}; }
  82682. var _this = this;
  82683. this.webVROptions = webVROptions;
  82684. // Can the system support WebVR, even if a headset isn't plugged in?
  82685. this._webVRsupported = false;
  82686. // If WebVR is supported, is a headset plugged in and are we ready to present?
  82687. this._webVRready = false;
  82688. // Are we waiting for the requestPresent callback to complete?
  82689. this._webVRrequesting = false;
  82690. // Are we presenting to the headset right now?
  82691. this._webVRpresenting = false;
  82692. // Are we presenting in the fullscreen fallback?
  82693. this._fullscreenVRpresenting = false;
  82694. /**
  82695. * Observable raised when entering VR.
  82696. */
  82697. this.onEnteringVRObservable = new BABYLON.Observable();
  82698. /**
  82699. * Observable raised when exiting VR.
  82700. */
  82701. this.onExitingVRObservable = new BABYLON.Observable();
  82702. /**
  82703. * Observable raised when controller mesh is loaded.
  82704. */
  82705. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  82706. this._useCustomVRButton = false;
  82707. this._teleportationRequested = false;
  82708. this._teleportActive = false;
  82709. this._floorMeshesCollection = [];
  82710. this._rotationAllowed = true;
  82711. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  82712. this._rotationRightAsked = false;
  82713. this._rotationLeftAsked = false;
  82714. this._isDefaultTeleportationTarget = true;
  82715. this._teleportationFillColor = "#444444";
  82716. this._teleportationBorderColor = "#FFFFFF";
  82717. this._rotationAngle = 0;
  82718. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  82719. this._padSensibilityUp = 0.65;
  82720. this._padSensibilityDown = 0.35;
  82721. this.leftController = null;
  82722. this.rightController = null;
  82723. /**
  82724. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  82725. */
  82726. this.onNewMeshSelected = new BABYLON.Observable();
  82727. /**
  82728. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  82729. */
  82730. this.onNewMeshPicked = new BABYLON.Observable();
  82731. /**
  82732. * Observable raised before camera teleportation
  82733. */
  82734. this.onBeforeCameraTeleport = new BABYLON.Observable();
  82735. /**
  82736. * Observable raised after camera teleportation
  82737. */
  82738. this.onAfterCameraTeleport = new BABYLON.Observable();
  82739. /**
  82740. * Observable raised when current selected mesh gets unselected
  82741. */
  82742. this.onSelectedMeshUnselected = new BABYLON.Observable();
  82743. /**
  82744. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  82745. */
  82746. this.teleportationEnabled = true;
  82747. this._teleportationInitialized = false;
  82748. this._interactionsEnabled = false;
  82749. this._interactionsRequested = false;
  82750. this._displayGaze = true;
  82751. this._displayLaserPointer = true;
  82752. this._onResize = function () {
  82753. _this.moveButtonToBottomRight();
  82754. if (_this._fullscreenVRpresenting && _this._webVRready) {
  82755. _this.exitVR();
  82756. }
  82757. };
  82758. this._onFullscreenChange = function () {
  82759. if (document.fullscreen !== undefined) {
  82760. _this._fullscreenVRpresenting = document.fullscreen;
  82761. }
  82762. else if (document.mozFullScreen !== undefined) {
  82763. _this._fullscreenVRpresenting = document.mozFullScreen;
  82764. }
  82765. else if (document.webkitIsFullScreen !== undefined) {
  82766. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  82767. }
  82768. else if (document.msIsFullScreen !== undefined) {
  82769. _this._fullscreenVRpresenting = document.msIsFullScreen;
  82770. }
  82771. if (!_this._fullscreenVRpresenting && _this._canvas) {
  82772. _this.exitVR();
  82773. if (!_this._useCustomVRButton) {
  82774. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  82775. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  82776. }
  82777. }
  82778. };
  82779. this.beforeRender = function () {
  82780. if (_this.leftController && _this.leftController._activePointer) {
  82781. _this._castRayAndSelectObject(_this.leftController);
  82782. }
  82783. if (_this.rightController && _this.rightController._activePointer) {
  82784. _this._castRayAndSelectObject(_this.rightController);
  82785. }
  82786. if (!(_this.leftController && _this.leftController._activePointer) && !(_this.rightController && _this.rightController._activePointer)) {
  82787. _this._castRayAndSelectObject(_this._cameraGazer);
  82788. }
  82789. else {
  82790. _this._cameraGazer._gazeTracker.isVisible = false;
  82791. }
  82792. };
  82793. this._onNewGamepadConnected = function (gamepad) {
  82794. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  82795. if (gamepad.leftStick) {
  82796. gamepad.onleftstickchanged(function (stickValues) {
  82797. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  82798. // Listening to classic/xbox gamepad only if no VR controller is active
  82799. if ((!_this.leftController && !_this.rightController) ||
  82800. ((_this.leftController && !_this.leftController._activePointer) &&
  82801. (_this.rightController && !_this.rightController._activePointer))) {
  82802. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  82803. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  82804. }
  82805. }
  82806. });
  82807. }
  82808. if (gamepad.rightStick) {
  82809. gamepad.onrightstickchanged(function (stickValues) {
  82810. if (_this._teleportationInitialized) {
  82811. _this._checkRotate(stickValues, _this._cameraGazer);
  82812. }
  82813. });
  82814. }
  82815. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  82816. gamepad.onbuttondown(function (buttonPressed) {
  82817. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  82818. _this._cameraGazer._selectionPointerDown();
  82819. }
  82820. });
  82821. gamepad.onbuttonup(function (buttonPressed) {
  82822. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  82823. _this._cameraGazer._selectionPointerUp();
  82824. }
  82825. });
  82826. }
  82827. }
  82828. else {
  82829. var webVRController = gamepad;
  82830. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  82831. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  82832. _this.rightController = controller;
  82833. }
  82834. else {
  82835. _this.leftController = controller;
  82836. }
  82837. _this._tryEnableInteractionOnController(controller);
  82838. }
  82839. };
  82840. // 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
  82841. this._tryEnableInteractionOnController = function (controller) {
  82842. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  82843. _this._enableInteractionOnController(controller);
  82844. }
  82845. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  82846. _this._enableTeleportationOnController(controller);
  82847. }
  82848. };
  82849. this._onNewGamepadDisconnected = function (gamepad) {
  82850. if (gamepad instanceof BABYLON.WebVRController) {
  82851. if (gamepad.hand === "left" && _this.leftController != null) {
  82852. _this.leftController.dispose();
  82853. _this.leftController = null;
  82854. }
  82855. if (gamepad.hand === "right" && _this.rightController != null) {
  82856. _this.rightController.dispose();
  82857. _this.rightController = null;
  82858. }
  82859. }
  82860. };
  82861. this._workingVector = BABYLON.Vector3.Zero();
  82862. this._workingQuaternion = BABYLON.Quaternion.Identity();
  82863. this._workingMatrix = BABYLON.Matrix.Identity();
  82864. this._scene = scene;
  82865. this._canvas = scene.getEngine().getRenderingCanvas();
  82866. // Parse options
  82867. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  82868. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  82869. }
  82870. if (webVROptions.createDeviceOrientationCamera === undefined) {
  82871. webVROptions.createDeviceOrientationCamera = true;
  82872. }
  82873. if (webVROptions.defaultHeight === undefined) {
  82874. webVROptions.defaultHeight = 1.7;
  82875. }
  82876. if (webVROptions.useCustomVRButton) {
  82877. this._useCustomVRButton = true;
  82878. if (webVROptions.customVRButton) {
  82879. this._btnVR = webVROptions.customVRButton;
  82880. }
  82881. }
  82882. if (webVROptions.rayLength) {
  82883. this._rayLength = webVROptions.rayLength;
  82884. }
  82885. this._defaultHeight = webVROptions.defaultHeight;
  82886. if (webVROptions.positionScale) {
  82887. this._rayLength *= webVROptions.positionScale;
  82888. this._defaultHeight *= webVROptions.positionScale;
  82889. }
  82890. // Set position
  82891. if (this._scene.activeCamera) {
  82892. this._position = this._scene.activeCamera.position.clone();
  82893. }
  82894. else {
  82895. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  82896. }
  82897. // Set non-vr camera
  82898. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  82899. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  82900. // Copy data from existing camera
  82901. if (this._scene.activeCamera) {
  82902. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  82903. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  82904. // Set rotation from previous camera
  82905. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  82906. var targetCamera = this._scene.activeCamera;
  82907. if (targetCamera.rotationQuaternion) {
  82908. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  82909. }
  82910. else {
  82911. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  82912. }
  82913. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  82914. }
  82915. }
  82916. this._scene.activeCamera = this._deviceOrientationCamera;
  82917. if (this._canvas) {
  82918. this._scene.activeCamera.attachControl(this._canvas);
  82919. }
  82920. }
  82921. else {
  82922. this._existingCamera = this._scene.activeCamera;
  82923. }
  82924. // Create VR cameras
  82925. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  82926. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  82927. }
  82928. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  82929. this._webVRCamera.useStandingMatrix();
  82930. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  82931. // Create default button
  82932. if (!this._useCustomVRButton) {
  82933. this._btnVR = document.createElement("BUTTON");
  82934. this._btnVR.className = "babylonVRicon";
  82935. this._btnVR.id = "babylonVRiconbtn";
  82936. this._btnVR.title = "Click to switch to VR";
  82937. 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) }";
  82938. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  82939. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  82940. // css += ".babylonVRicon.vrdisplaysupported { }";
  82941. // css += ".babylonVRicon.vrdisplayready { }";
  82942. // css += ".babylonVRicon.vrdisplayrequesting { }";
  82943. var style = document.createElement('style');
  82944. style.appendChild(document.createTextNode(css));
  82945. document.getElementsByTagName('head')[0].appendChild(style);
  82946. this.moveButtonToBottomRight();
  82947. }
  82948. // VR button click event
  82949. if (this._btnVR) {
  82950. this._btnVR.addEventListener("click", function () {
  82951. if (!_this.isInVRMode) {
  82952. _this.enterVR();
  82953. }
  82954. else {
  82955. _this.exitVR();
  82956. }
  82957. });
  82958. }
  82959. // Window events
  82960. window.addEventListener("resize", this._onResize);
  82961. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  82962. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  82963. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  82964. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  82965. // Display vr button when headset is connected
  82966. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  82967. this.displayVRButton();
  82968. }
  82969. else {
  82970. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  82971. if (e.vrDisplay) {
  82972. _this.displayVRButton();
  82973. }
  82974. });
  82975. }
  82976. // Exiting VR mode using 'ESC' key on desktop
  82977. this._onKeyDown = function (event) {
  82978. if (event.keyCode === 27 && _this.isInVRMode) {
  82979. _this.exitVR();
  82980. }
  82981. };
  82982. document.addEventListener("keydown", this._onKeyDown);
  82983. // Exiting VR mode double tapping the touch screen
  82984. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  82985. if (_this.isInVRMode) {
  82986. _this.exitVR();
  82987. if (_this._fullscreenVRpresenting) {
  82988. _this._scene.getEngine().switchFullscreen(true);
  82989. }
  82990. }
  82991. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  82992. // Listen for WebVR display changes
  82993. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  82994. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  82995. this._onVRRequestPresentStart = function () {
  82996. _this._webVRrequesting = true;
  82997. _this.updateButtonVisibility();
  82998. };
  82999. this._onVRRequestPresentComplete = function (success) {
  83000. _this._webVRrequesting = false;
  83001. _this.updateButtonVisibility();
  83002. };
  83003. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  83004. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  83005. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  83006. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  83007. scene.onDisposeObservable.add(function () {
  83008. _this.dispose();
  83009. });
  83010. // Gamepad connection events
  83011. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  83012. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  83013. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  83014. this.updateButtonVisibility();
  83015. //create easing functions
  83016. this._circleEase = new BABYLON.CircleEase();
  83017. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  83018. }
  83019. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  83020. /** Return this.onEnteringVRObservable
  83021. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  83022. */
  83023. get: function () {
  83024. return this.onEnteringVRObservable;
  83025. },
  83026. enumerable: true,
  83027. configurable: true
  83028. });
  83029. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  83030. /** Return this.onExitingVRObservable
  83031. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  83032. */
  83033. get: function () {
  83034. return this.onExitingVRObservable;
  83035. },
  83036. enumerable: true,
  83037. configurable: true
  83038. });
  83039. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  83040. /** Return this.onControllerMeshLoadedObservable
  83041. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  83042. */
  83043. get: function () {
  83044. return this.onControllerMeshLoadedObservable;
  83045. },
  83046. enumerable: true,
  83047. configurable: true
  83048. });
  83049. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  83050. /**
  83051. * The mesh used to display where the user is going to teleport.
  83052. */
  83053. get: function () {
  83054. return this._teleportationTarget;
  83055. },
  83056. /**
  83057. * Sets the mesh to be used to display where the user is going to teleport.
  83058. */
  83059. set: function (value) {
  83060. if (value) {
  83061. value.name = "teleportationTarget";
  83062. this._isDefaultTeleportationTarget = false;
  83063. this._teleportationTarget = value;
  83064. }
  83065. },
  83066. enumerable: true,
  83067. configurable: true
  83068. });
  83069. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  83070. /**
  83071. * The mesh used to display where the user is selecting,
  83072. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  83073. * See http://doc.babylonjs.com/resources/baking_transformations
  83074. */
  83075. get: function () {
  83076. return this._cameraGazer._gazeTracker;
  83077. },
  83078. set: function (value) {
  83079. if (value) {
  83080. this._cameraGazer._gazeTracker = value;
  83081. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  83082. this._cameraGazer._gazeTracker.isPickable = false;
  83083. this._cameraGazer._gazeTracker.isVisible = false;
  83084. this._cameraGazer._gazeTracker.name = "gazeTracker";
  83085. if (this.leftController) {
  83086. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  83087. }
  83088. if (this.rightController) {
  83089. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  83090. }
  83091. }
  83092. },
  83093. enumerable: true,
  83094. configurable: true
  83095. });
  83096. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  83097. /**
  83098. * If the ray of the gaze should be displayed.
  83099. */
  83100. get: function () {
  83101. return this._displayGaze;
  83102. },
  83103. /**
  83104. * Sets if the ray of the gaze should be displayed.
  83105. */
  83106. set: function (value) {
  83107. this._displayGaze = value;
  83108. if (!value) {
  83109. this._cameraGazer._gazeTracker.isVisible = false;
  83110. if (this.leftController) {
  83111. this.leftController._gazeTracker.isVisible = false;
  83112. }
  83113. if (this.rightController) {
  83114. this.rightController._gazeTracker.isVisible = false;
  83115. }
  83116. }
  83117. },
  83118. enumerable: true,
  83119. configurable: true
  83120. });
  83121. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  83122. /**
  83123. * If the ray of the LaserPointer should be displayed.
  83124. */
  83125. get: function () {
  83126. return this._displayLaserPointer;
  83127. },
  83128. /**
  83129. * Sets if the ray of the LaserPointer should be displayed.
  83130. */
  83131. set: function (value) {
  83132. this._displayLaserPointer = value;
  83133. if (!value) {
  83134. if (this.rightController) {
  83135. this.rightController._deactivatePointer();
  83136. this.rightController._gazeTracker.isVisible = false;
  83137. }
  83138. if (this.leftController) {
  83139. this.leftController._deactivatePointer();
  83140. this.leftController._gazeTracker.isVisible = false;
  83141. }
  83142. }
  83143. else {
  83144. if (this.rightController) {
  83145. this.rightController._activatePointer();
  83146. }
  83147. else if (this.leftController) {
  83148. this.leftController._activatePointer();
  83149. }
  83150. }
  83151. },
  83152. enumerable: true,
  83153. configurable: true
  83154. });
  83155. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  83156. /**
  83157. * The deviceOrientationCamera used as the camera when not in VR.
  83158. */
  83159. get: function () {
  83160. return this._deviceOrientationCamera;
  83161. },
  83162. enumerable: true,
  83163. configurable: true
  83164. });
  83165. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  83166. /**
  83167. * Based on the current WebVR support, returns the current VR camera used.
  83168. */
  83169. get: function () {
  83170. if (this._webVRready) {
  83171. return this._webVRCamera;
  83172. }
  83173. else {
  83174. return this._scene.activeCamera;
  83175. }
  83176. },
  83177. enumerable: true,
  83178. configurable: true
  83179. });
  83180. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  83181. /**
  83182. * The webVRCamera which is used when in VR.
  83183. */
  83184. get: function () {
  83185. return this._webVRCamera;
  83186. },
  83187. enumerable: true,
  83188. configurable: true
  83189. });
  83190. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  83191. /**
  83192. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  83193. */
  83194. get: function () {
  83195. return this._vrDeviceOrientationCamera;
  83196. },
  83197. enumerable: true,
  83198. configurable: true
  83199. });
  83200. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  83201. get: function () {
  83202. var result = this._cameraGazer._teleportationRequestInitiated
  83203. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  83204. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  83205. return result;
  83206. },
  83207. enumerable: true,
  83208. configurable: true
  83209. });
  83210. // Raised when one of the controller has loaded successfully its associated default mesh
  83211. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  83212. if (this.leftController && this.leftController.webVRController == webVRController) {
  83213. if (webVRController.mesh) {
  83214. this.leftController._setLaserPointerParent(webVRController.mesh);
  83215. }
  83216. }
  83217. if (this.rightController && this.rightController.webVRController == webVRController) {
  83218. if (webVRController.mesh) {
  83219. this.rightController._setLaserPointerParent(webVRController.mesh);
  83220. }
  83221. }
  83222. try {
  83223. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  83224. }
  83225. catch (err) {
  83226. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  83227. }
  83228. };
  83229. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  83230. /**
  83231. * Gets a value indicating if we are currently in VR mode.
  83232. */
  83233. get: function () {
  83234. return this._webVRpresenting || this._fullscreenVRpresenting;
  83235. },
  83236. enumerable: true,
  83237. configurable: true
  83238. });
  83239. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  83240. var vrDisplay = this._scene.getEngine().getVRDevice();
  83241. if (vrDisplay) {
  83242. var wasPresenting = this._webVRpresenting;
  83243. // A VR display is connected
  83244. this._webVRpresenting = vrDisplay.isPresenting;
  83245. if (wasPresenting && !this._webVRpresenting)
  83246. this.exitVR();
  83247. }
  83248. else {
  83249. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  83250. }
  83251. this.updateButtonVisibility();
  83252. };
  83253. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  83254. this._webVRsupported = eventArgs.vrSupported;
  83255. this._webVRready = !!eventArgs.vrDisplay;
  83256. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  83257. this.updateButtonVisibility();
  83258. };
  83259. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  83260. if (this._canvas && !this._useCustomVRButton) {
  83261. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  83262. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  83263. }
  83264. };
  83265. VRExperienceHelper.prototype.displayVRButton = function () {
  83266. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  83267. document.body.appendChild(this._btnVR);
  83268. this._btnVRDisplayed = true;
  83269. }
  83270. };
  83271. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  83272. if (!this._btnVR || this._useCustomVRButton) {
  83273. return;
  83274. }
  83275. this._btnVR.className = "babylonVRicon";
  83276. if (this.isInVRMode) {
  83277. this._btnVR.className += " vrdisplaypresenting";
  83278. }
  83279. else {
  83280. if (this._webVRready)
  83281. this._btnVR.className += " vrdisplayready";
  83282. if (this._webVRsupported)
  83283. this._btnVR.className += " vrdisplaysupported";
  83284. if (this._webVRrequesting)
  83285. this._btnVR.className += " vrdisplayrequesting";
  83286. }
  83287. };
  83288. /**
  83289. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  83290. * Otherwise, will use the fullscreen API.
  83291. */
  83292. VRExperienceHelper.prototype.enterVR = function () {
  83293. if (this.onEnteringVRObservable) {
  83294. try {
  83295. this.onEnteringVRObservable.notifyObservers(this);
  83296. }
  83297. catch (err) {
  83298. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  83299. }
  83300. }
  83301. if (this._scene.activeCamera) {
  83302. this._position = this._scene.activeCamera.position.clone();
  83303. // make sure that we return to the last active camera
  83304. this._existingCamera = this._scene.activeCamera;
  83305. }
  83306. if (this._webVRrequesting)
  83307. return;
  83308. // If WebVR is supported and a headset is connected
  83309. if (this._webVRready) {
  83310. if (!this._webVRpresenting) {
  83311. this._webVRCamera.position = this._position;
  83312. this._scene.activeCamera = this._webVRCamera;
  83313. }
  83314. }
  83315. else if (this._vrDeviceOrientationCamera) {
  83316. this._vrDeviceOrientationCamera.position = this._position;
  83317. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  83318. this._scene.getEngine().switchFullscreen(true);
  83319. this.updateButtonVisibility();
  83320. }
  83321. if (this._scene.activeCamera && this._canvas) {
  83322. this._scene.activeCamera.attachControl(this._canvas);
  83323. }
  83324. if (this._interactionsEnabled) {
  83325. this._scene.registerBeforeRender(this.beforeRender);
  83326. }
  83327. };
  83328. /**
  83329. * Attempt to exit VR, or fullscreen.
  83330. */
  83331. VRExperienceHelper.prototype.exitVR = function () {
  83332. if (this.onExitingVRObservable) {
  83333. try {
  83334. this.onExitingVRObservable.notifyObservers(this);
  83335. }
  83336. catch (err) {
  83337. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  83338. }
  83339. }
  83340. if (this._webVRpresenting) {
  83341. this._scene.getEngine().disableVR();
  83342. }
  83343. if (this._scene.activeCamera) {
  83344. this._position = this._scene.activeCamera.position.clone();
  83345. }
  83346. if (this._deviceOrientationCamera) {
  83347. this._deviceOrientationCamera.position = this._position;
  83348. this._scene.activeCamera = this._deviceOrientationCamera;
  83349. if (this._canvas) {
  83350. this._scene.activeCamera.attachControl(this._canvas);
  83351. }
  83352. }
  83353. else if (this._existingCamera) {
  83354. this._existingCamera.position = this._position;
  83355. this._scene.activeCamera = this._existingCamera;
  83356. }
  83357. this.updateButtonVisibility();
  83358. if (this._interactionsEnabled) {
  83359. this._scene.unregisterBeforeRender(this.beforeRender);
  83360. }
  83361. };
  83362. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  83363. /**
  83364. * The position of the vr experience helper.
  83365. */
  83366. get: function () {
  83367. return this._position;
  83368. },
  83369. /**
  83370. * Sets the position of the vr experience helper.
  83371. */
  83372. set: function (value) {
  83373. this._position = value;
  83374. if (this._scene.activeCamera) {
  83375. this._scene.activeCamera.position = value;
  83376. }
  83377. },
  83378. enumerable: true,
  83379. configurable: true
  83380. });
  83381. /**
  83382. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  83383. */
  83384. VRExperienceHelper.prototype.enableInteractions = function () {
  83385. var _this = this;
  83386. if (!this._interactionsEnabled) {
  83387. this._interactionsRequested = true;
  83388. if (this.leftController) {
  83389. this._enableInteractionOnController(this.leftController);
  83390. }
  83391. if (this.rightController) {
  83392. this._enableInteractionOnController(this.rightController);
  83393. }
  83394. this.raySelectionPredicate = function (mesh) {
  83395. return mesh.isVisible;
  83396. };
  83397. this.meshSelectionPredicate = function (mesh) {
  83398. return true;
  83399. };
  83400. this._raySelectionPredicate = function (mesh) {
  83401. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  83402. && mesh.name.indexOf("teleportationTarget") === -1
  83403. && mesh.name.indexOf("torusTeleportation") === -1
  83404. && mesh.name.indexOf("laserPointer") === -1)) {
  83405. return _this.raySelectionPredicate(mesh);
  83406. }
  83407. return false;
  83408. };
  83409. this._interactionsEnabled = true;
  83410. }
  83411. };
  83412. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  83413. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  83414. if (this._floorMeshesCollection[i].id === mesh.id) {
  83415. return true;
  83416. }
  83417. }
  83418. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  83419. return true;
  83420. }
  83421. return false;
  83422. };
  83423. /**
  83424. * Adds a floor mesh to be used for teleportation.
  83425. * @param floorMesh the mesh to be used for teleportation.
  83426. */
  83427. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  83428. if (!this._floorMeshesCollection) {
  83429. return;
  83430. }
  83431. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  83432. return;
  83433. }
  83434. this._floorMeshesCollection.push(floorMesh);
  83435. };
  83436. /**
  83437. * Removes a floor mesh from being used for teleportation.
  83438. * @param floorMesh the mesh to be removed.
  83439. */
  83440. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  83441. if (!this._floorMeshesCollection) {
  83442. return;
  83443. }
  83444. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  83445. if (meshIndex !== -1) {
  83446. this._floorMeshesCollection.splice(meshIndex, 1);
  83447. }
  83448. };
  83449. /**
  83450. * Enables interactions and teleportation using the VR controllers and gaze.
  83451. * @param vrTeleportationOptions options to modify teleportation behavior.
  83452. */
  83453. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  83454. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  83455. if (!this._teleportationInitialized) {
  83456. this._teleportationRequested = true;
  83457. this.enableInteractions();
  83458. if (vrTeleportationOptions.floorMeshName) {
  83459. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  83460. }
  83461. if (vrTeleportationOptions.floorMeshes) {
  83462. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  83463. }
  83464. if (this.leftController != null) {
  83465. this._enableTeleportationOnController(this.leftController);
  83466. }
  83467. if (this.rightController != null) {
  83468. this._enableTeleportationOnController(this.rightController);
  83469. }
  83470. // Creates an image processing post process for the vignette not relying
  83471. // on the main scene configuration for image processing to reduce setup and spaces
  83472. // (gamma/linear) conflicts.
  83473. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  83474. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  83475. imageProcessingConfiguration.vignetteEnabled = true;
  83476. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  83477. this._webVRCamera.detachPostProcess(this._postProcessMove);
  83478. this._teleportationInitialized = true;
  83479. if (this._isDefaultTeleportationTarget) {
  83480. this._createTeleportationCircles();
  83481. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  83482. }
  83483. }
  83484. };
  83485. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  83486. var _this = this;
  83487. var controllerMesh = controller.webVRController.mesh;
  83488. if (controllerMesh) {
  83489. controller._interactionsEnabled = true;
  83490. controller._activatePointer();
  83491. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  83492. // Enabling / disabling laserPointer
  83493. if (_this._displayLaserPointer && stateObject.value === 1) {
  83494. if (controller._activePointer) {
  83495. controller._deactivatePointer();
  83496. }
  83497. else {
  83498. controller._activatePointer();
  83499. }
  83500. if (_this.displayGaze) {
  83501. controller._gazeTracker.isVisible = controller._activePointer;
  83502. }
  83503. }
  83504. });
  83505. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  83506. if (!controller._pointerDownOnMeshAsked) {
  83507. if (stateObject.value > _this._padSensibilityUp) {
  83508. controller._selectionPointerDown();
  83509. }
  83510. }
  83511. else if (stateObject.value < _this._padSensibilityDown) {
  83512. controller._selectionPointerUp();
  83513. }
  83514. });
  83515. }
  83516. };
  83517. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  83518. // Dont teleport if another gaze already requested teleportation
  83519. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  83520. return;
  83521. }
  83522. if (!gazer._teleportationRequestInitiated) {
  83523. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  83524. gazer._activatePointer();
  83525. gazer._teleportationRequestInitiated = true;
  83526. }
  83527. }
  83528. else {
  83529. // Listening to the proper controller values changes to confirm teleportation
  83530. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  83531. if (this._teleportActive) {
  83532. this._teleportCamera(this._haloCenter);
  83533. }
  83534. gazer._teleportationRequestInitiated = false;
  83535. }
  83536. }
  83537. };
  83538. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  83539. // Only rotate when user is not currently selecting a teleportation location
  83540. if (gazer._teleportationRequestInitiated) {
  83541. return;
  83542. }
  83543. if (!this._rotationLeftAsked) {
  83544. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  83545. this._rotationLeftAsked = true;
  83546. if (this._rotationAllowed) {
  83547. this._rotateCamera(false);
  83548. }
  83549. }
  83550. }
  83551. else {
  83552. if (stateObject.x > -this._padSensibilityDown) {
  83553. this._rotationLeftAsked = false;
  83554. }
  83555. }
  83556. if (!this._rotationRightAsked) {
  83557. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  83558. this._rotationRightAsked = true;
  83559. if (this._rotationAllowed) {
  83560. this._rotateCamera(true);
  83561. }
  83562. }
  83563. }
  83564. else {
  83565. if (stateObject.x < this._padSensibilityDown) {
  83566. this._rotationRightAsked = false;
  83567. }
  83568. }
  83569. };
  83570. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  83571. // Only teleport backwards when user is not currently selecting a teleportation location
  83572. if (gazer._teleportationRequestInitiated) {
  83573. return;
  83574. }
  83575. // Teleport backwards
  83576. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  83577. if (!gazer._teleportationBackRequestInitiated) {
  83578. if (!this.currentVRCamera) {
  83579. return;
  83580. }
  83581. // Get rotation and position of the current camera
  83582. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  83583. var position = this.currentVRCamera.position;
  83584. // If the camera has device position, use that instead
  83585. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  83586. rotation = this.currentVRCamera.deviceRotationQuaternion;
  83587. position = this.currentVRCamera.devicePosition;
  83588. }
  83589. // Get matrix with only the y rotation of the device rotation
  83590. rotation.toEulerAnglesToRef(this._workingVector);
  83591. this._workingVector.z = 0;
  83592. this._workingVector.x = 0;
  83593. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  83594. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  83595. // Rotate backwards ray by device rotation to cast at the ground behind the user
  83596. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  83597. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  83598. var ray = new BABYLON.Ray(position, this._workingVector);
  83599. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  83600. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  83601. this._teleportCamera(hit.pickedPoint);
  83602. }
  83603. gazer._teleportationBackRequestInitiated = true;
  83604. }
  83605. }
  83606. else {
  83607. gazer._teleportationBackRequestInitiated = false;
  83608. }
  83609. };
  83610. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  83611. var _this = this;
  83612. var controllerMesh = controller.webVRController.mesh;
  83613. if (controllerMesh) {
  83614. if (!controller._interactionsEnabled) {
  83615. this._enableInteractionOnController(controller);
  83616. }
  83617. controller._interactionsEnabled = true;
  83618. controller._teleportationEnabled = true;
  83619. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  83620. controller._dpadPressed = false;
  83621. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  83622. controller._dpadPressed = stateObject.pressed;
  83623. if (!controller._dpadPressed) {
  83624. _this._rotationLeftAsked = false;
  83625. _this._rotationRightAsked = false;
  83626. controller._teleportationBackRequestInitiated = false;
  83627. }
  83628. });
  83629. }
  83630. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  83631. if (_this.teleportationEnabled) {
  83632. _this._checkTeleportBackwards(stateObject, controller);
  83633. _this._checkTeleportWithRay(stateObject, controller);
  83634. }
  83635. _this._checkRotate(stateObject, controller);
  83636. });
  83637. }
  83638. };
  83639. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  83640. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  83641. this._teleportationTarget.isPickable = false;
  83642. var length = 512;
  83643. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  83644. dynamicTexture.hasAlpha = true;
  83645. var context = dynamicTexture.getContext();
  83646. var centerX = length / 2;
  83647. var centerY = length / 2;
  83648. var radius = 200;
  83649. context.beginPath();
  83650. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  83651. context.fillStyle = this._teleportationFillColor;
  83652. context.fill();
  83653. context.lineWidth = 10;
  83654. context.strokeStyle = this._teleportationBorderColor;
  83655. context.stroke();
  83656. context.closePath();
  83657. dynamicTexture.update();
  83658. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  83659. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  83660. this._teleportationTarget.material = teleportationCircleMaterial;
  83661. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  83662. torus.isPickable = false;
  83663. torus.parent = this._teleportationTarget;
  83664. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  83665. var keys = [];
  83666. keys.push({
  83667. frame: 0,
  83668. value: 0
  83669. });
  83670. keys.push({
  83671. frame: 30,
  83672. value: 0.4
  83673. });
  83674. keys.push({
  83675. frame: 60,
  83676. value: 0
  83677. });
  83678. animationInnerCircle.setKeys(keys);
  83679. var easingFunction = new BABYLON.SineEase();
  83680. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  83681. animationInnerCircle.setEasingFunction(easingFunction);
  83682. torus.animations = [];
  83683. torus.animations.push(animationInnerCircle);
  83684. this._scene.beginAnimation(torus, 0, 60, true);
  83685. this._hideTeleportationTarget();
  83686. };
  83687. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  83688. this._teleportActive = true;
  83689. if (this._teleportationInitialized) {
  83690. this._teleportationTarget.isVisible = true;
  83691. if (this._isDefaultTeleportationTarget) {
  83692. this._teleportationTarget.getChildren()[0].isVisible = true;
  83693. }
  83694. }
  83695. };
  83696. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  83697. this._teleportActive = false;
  83698. if (this._teleportationInitialized) {
  83699. this._teleportationTarget.isVisible = false;
  83700. if (this._isDefaultTeleportationTarget) {
  83701. this._teleportationTarget.getChildren()[0].isVisible = false;
  83702. }
  83703. }
  83704. };
  83705. VRExperienceHelper.prototype._rotateCamera = function (right) {
  83706. var _this = this;
  83707. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  83708. return;
  83709. }
  83710. if (right) {
  83711. this._rotationAngle++;
  83712. }
  83713. else {
  83714. this._rotationAngle--;
  83715. }
  83716. this.currentVRCamera.animations = [];
  83717. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  83718. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  83719. var animationRotationKeys = [];
  83720. animationRotationKeys.push({
  83721. frame: 0,
  83722. value: this.currentVRCamera.rotationQuaternion
  83723. });
  83724. animationRotationKeys.push({
  83725. frame: 6,
  83726. value: target
  83727. });
  83728. animationRotation.setKeys(animationRotationKeys);
  83729. animationRotation.setEasingFunction(this._circleEase);
  83730. this.currentVRCamera.animations.push(animationRotation);
  83731. this._postProcessMove.animations = [];
  83732. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  83733. var vignetteWeightKeys = [];
  83734. vignetteWeightKeys.push({
  83735. frame: 0,
  83736. value: 0
  83737. });
  83738. vignetteWeightKeys.push({
  83739. frame: 3,
  83740. value: 4
  83741. });
  83742. vignetteWeightKeys.push({
  83743. frame: 6,
  83744. value: 0
  83745. });
  83746. animationPP.setKeys(vignetteWeightKeys);
  83747. animationPP.setEasingFunction(this._circleEase);
  83748. this._postProcessMove.animations.push(animationPP);
  83749. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  83750. var vignetteStretchKeys = [];
  83751. vignetteStretchKeys.push({
  83752. frame: 0,
  83753. value: 0
  83754. });
  83755. vignetteStretchKeys.push({
  83756. frame: 3,
  83757. value: 10
  83758. });
  83759. vignetteStretchKeys.push({
  83760. frame: 6,
  83761. value: 0
  83762. });
  83763. animationPP2.setKeys(vignetteStretchKeys);
  83764. animationPP2.setEasingFunction(this._circleEase);
  83765. this._postProcessMove.animations.push(animationPP2);
  83766. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  83767. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  83768. this._postProcessMove.samples = 4;
  83769. this._webVRCamera.attachPostProcess(this._postProcessMove);
  83770. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  83771. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  83772. });
  83773. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  83774. };
  83775. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer) {
  83776. if (hit.pickedPoint) {
  83777. if (gazer._teleportationRequestInitiated) {
  83778. this._displayTeleportationTarget();
  83779. this._haloCenter.copyFrom(hit.pickedPoint);
  83780. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  83781. }
  83782. var pickNormal = hit.getNormal(true, false);
  83783. if (pickNormal) {
  83784. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  83785. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  83786. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  83787. }
  83788. this._teleportationTarget.position.y += 0.1;
  83789. }
  83790. };
  83791. VRExperienceHelper.prototype._teleportCamera = function (location) {
  83792. var _this = this;
  83793. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  83794. return;
  83795. }
  83796. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  83797. // offset of the headset from the anchor.
  83798. if (this.webVRCamera.leftCamera) {
  83799. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  83800. this._workingVector.subtractInPlace(this.webVRCamera.position);
  83801. location.subtractToRef(this._workingVector, this._workingVector);
  83802. }
  83803. else {
  83804. this._workingVector.copyFrom(location);
  83805. }
  83806. // Add height to account for user's height offset
  83807. if (this.isInVRMode) {
  83808. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  83809. }
  83810. else {
  83811. this._workingVector.y += this._defaultHeight;
  83812. }
  83813. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  83814. // Create animation from the camera's position to the new location
  83815. this.currentVRCamera.animations = [];
  83816. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  83817. var animationCameraTeleportationKeys = [{
  83818. frame: 0,
  83819. value: this.currentVRCamera.position
  83820. },
  83821. {
  83822. frame: 11,
  83823. value: this._workingVector
  83824. }
  83825. ];
  83826. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  83827. animationCameraTeleportation.setEasingFunction(this._circleEase);
  83828. this.currentVRCamera.animations.push(animationCameraTeleportation);
  83829. this._postProcessMove.animations = [];
  83830. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  83831. var vignetteWeightKeys = [];
  83832. vignetteWeightKeys.push({
  83833. frame: 0,
  83834. value: 0
  83835. });
  83836. vignetteWeightKeys.push({
  83837. frame: 5,
  83838. value: 8
  83839. });
  83840. vignetteWeightKeys.push({
  83841. frame: 11,
  83842. value: 0
  83843. });
  83844. animationPP.setKeys(vignetteWeightKeys);
  83845. this._postProcessMove.animations.push(animationPP);
  83846. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  83847. var vignetteStretchKeys = [];
  83848. vignetteStretchKeys.push({
  83849. frame: 0,
  83850. value: 0
  83851. });
  83852. vignetteStretchKeys.push({
  83853. frame: 5,
  83854. value: 10
  83855. });
  83856. vignetteStretchKeys.push({
  83857. frame: 11,
  83858. value: 0
  83859. });
  83860. animationPP2.setKeys(vignetteStretchKeys);
  83861. this._postProcessMove.animations.push(animationPP2);
  83862. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  83863. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  83864. this._webVRCamera.attachPostProcess(this._postProcessMove);
  83865. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  83866. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  83867. });
  83868. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  83869. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  83870. });
  83871. this._hideTeleportationTarget();
  83872. };
  83873. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  83874. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  83875. return;
  83876. }
  83877. var hit = this._scene.pickWithRay(gazer._getForwardRay(this._rayLength), this._raySelectionPredicate);
  83878. // Moving the gazeTracker on the mesh face targetted
  83879. if (hit && hit.pickedPoint) {
  83880. if (this._displayGaze) {
  83881. var multiplier = 1;
  83882. gazer._gazeTracker.isVisible = true;
  83883. if (gazer._isActionableMesh) {
  83884. multiplier = 3;
  83885. }
  83886. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  83887. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  83888. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  83889. var pickNormal = hit.getNormal();
  83890. // To avoid z-fighting
  83891. var deltaFighting = 0.002;
  83892. if (pickNormal) {
  83893. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  83894. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  83895. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  83896. }
  83897. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  83898. if (gazer._gazeTracker.position.x < 0) {
  83899. gazer._gazeTracker.position.x += deltaFighting;
  83900. }
  83901. else {
  83902. gazer._gazeTracker.position.x -= deltaFighting;
  83903. }
  83904. if (gazer._gazeTracker.position.y < 0) {
  83905. gazer._gazeTracker.position.y += deltaFighting;
  83906. }
  83907. else {
  83908. gazer._gazeTracker.position.y -= deltaFighting;
  83909. }
  83910. if (gazer._gazeTracker.position.z < 0) {
  83911. gazer._gazeTracker.position.z += deltaFighting;
  83912. }
  83913. else {
  83914. gazer._gazeTracker.position.z -= deltaFighting;
  83915. }
  83916. }
  83917. // Changing the size of the laser pointer based on the distance from the targetted point
  83918. gazer._updatePointerDistance(hit.distance);
  83919. }
  83920. else {
  83921. gazer._gazeTracker.isVisible = false;
  83922. }
  83923. if (hit && hit.pickedMesh) {
  83924. gazer._currentHit = hit;
  83925. if (gazer._pointerDownOnMeshAsked) {
  83926. this._scene.simulatePointerMove(gazer._currentHit, { pointerId: gazer._id });
  83927. }
  83928. // The object selected is the floor, we're in a teleportation scenario
  83929. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  83930. // Moving the teleportation area to this targetted point
  83931. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  83932. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  83933. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  83934. }
  83935. gazer._currentMeshSelected = null;
  83936. if (gazer._teleportationRequestInitiated) {
  83937. this._moveTeleportationSelectorTo(hit, gazer);
  83938. }
  83939. return;
  83940. }
  83941. // If not, we're in a selection scenario
  83942. //this._teleportationAllowed = false;
  83943. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  83944. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  83945. this.onNewMeshPicked.notifyObservers(hit);
  83946. gazer._currentMeshSelected = hit.pickedMesh;
  83947. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  83948. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  83949. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  83950. gazer._isActionableMesh = true;
  83951. }
  83952. else {
  83953. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  83954. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  83955. gazer._isActionableMesh = false;
  83956. }
  83957. try {
  83958. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  83959. }
  83960. catch (err) {
  83961. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  83962. }
  83963. }
  83964. else {
  83965. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  83966. gazer._currentMeshSelected = null;
  83967. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  83968. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  83969. }
  83970. }
  83971. }
  83972. else {
  83973. gazer._currentHit = null;
  83974. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  83975. gazer._currentMeshSelected = null;
  83976. //this._teleportationAllowed = false;
  83977. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  83978. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  83979. }
  83980. };
  83981. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  83982. if (mesh) {
  83983. this.onSelectedMeshUnselected.notifyObservers(mesh);
  83984. }
  83985. };
  83986. /**
  83987. * Sets the color of the laser ray from the vr controllers.
  83988. * @param color new color for the ray.
  83989. */
  83990. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  83991. if (this.leftController) {
  83992. this.leftController._setLaserPointerColor(color);
  83993. }
  83994. if (this.rightController) {
  83995. this.rightController._setLaserPointerColor(color);
  83996. }
  83997. };
  83998. /**
  83999. * Sets the color of the ray from the vr headsets gaze.
  84000. * @param color new color for the ray.
  84001. */
  84002. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  84003. if (!this._cameraGazer._gazeTracker.material) {
  84004. return;
  84005. }
  84006. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  84007. if (this.leftController) {
  84008. this.leftController._gazeTracker.material.emissiveColor = color;
  84009. }
  84010. if (this.rightController) {
  84011. this.rightController._gazeTracker.material.emissiveColor = color;
  84012. }
  84013. };
  84014. /**
  84015. * Exits VR and disposes of the vr experience helper
  84016. */
  84017. VRExperienceHelper.prototype.dispose = function () {
  84018. if (this.isInVRMode) {
  84019. this.exitVR();
  84020. }
  84021. if (this._postProcessMove) {
  84022. this._postProcessMove.dispose();
  84023. }
  84024. if (this._webVRCamera) {
  84025. this._webVRCamera.dispose();
  84026. }
  84027. if (this._vrDeviceOrientationCamera) {
  84028. this._vrDeviceOrientationCamera.dispose();
  84029. }
  84030. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  84031. document.body.removeChild(this._btnVR);
  84032. }
  84033. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  84034. this._deviceOrientationCamera.dispose();
  84035. }
  84036. if (this._cameraGazer) {
  84037. this._cameraGazer.dispose();
  84038. }
  84039. if (this.leftController) {
  84040. this.leftController.dispose();
  84041. }
  84042. if (this.rightController) {
  84043. this.rightController.dispose();
  84044. }
  84045. if (this._teleportationTarget) {
  84046. this._teleportationTarget.dispose();
  84047. }
  84048. this._floorMeshesCollection = [];
  84049. document.removeEventListener("keydown", this._onKeyDown);
  84050. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  84051. window.removeEventListener("resize", this._onResize);
  84052. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  84053. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  84054. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  84055. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  84056. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  84057. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  84058. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  84059. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  84060. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  84061. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  84062. this._scene.unregisterBeforeRender(this.beforeRender);
  84063. };
  84064. /**
  84065. * Gets the name of the VRExperienceHelper class
  84066. * @returns "VRExperienceHelper"
  84067. */
  84068. VRExperienceHelper.prototype.getClassName = function () {
  84069. return "VRExperienceHelper";
  84070. };
  84071. return VRExperienceHelper;
  84072. }());
  84073. BABYLON.VRExperienceHelper = VRExperienceHelper;
  84074. })(BABYLON || (BABYLON = {}));
  84075. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  84076. "use strict";
  84077. // Mainly based on these 2 articles :
  84078. // 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
  84079. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  84080. var BABYLON;
  84081. (function (BABYLON) {
  84082. var JoystickAxis;
  84083. (function (JoystickAxis) {
  84084. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  84085. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  84086. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  84087. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  84088. var VirtualJoystick = /** @class */ (function () {
  84089. function VirtualJoystick(leftJoystick) {
  84090. var _this = this;
  84091. if (leftJoystick) {
  84092. this._leftJoystick = true;
  84093. }
  84094. else {
  84095. this._leftJoystick = false;
  84096. }
  84097. VirtualJoystick._globalJoystickIndex++;
  84098. // By default left & right arrow keys are moving the X
  84099. // and up & down keys are moving the Y
  84100. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  84101. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  84102. this.reverseLeftRight = false;
  84103. this.reverseUpDown = false;
  84104. // collections of pointers
  84105. this._touches = new BABYLON.StringDictionary();
  84106. this.deltaPosition = BABYLON.Vector3.Zero();
  84107. this._joystickSensibility = 25;
  84108. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  84109. this._onResize = function (evt) {
  84110. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  84111. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  84112. if (VirtualJoystick.vjCanvas) {
  84113. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  84114. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  84115. }
  84116. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  84117. };
  84118. // injecting a canvas element on top of the canvas 3D game
  84119. if (!VirtualJoystick.vjCanvas) {
  84120. window.addEventListener("resize", this._onResize, false);
  84121. VirtualJoystick.vjCanvas = document.createElement("canvas");
  84122. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  84123. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  84124. VirtualJoystick.vjCanvas.width = window.innerWidth;
  84125. VirtualJoystick.vjCanvas.height = window.innerHeight;
  84126. VirtualJoystick.vjCanvas.style.width = "100%";
  84127. VirtualJoystick.vjCanvas.style.height = "100%";
  84128. VirtualJoystick.vjCanvas.style.position = "absolute";
  84129. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  84130. VirtualJoystick.vjCanvas.style.top = "0px";
  84131. VirtualJoystick.vjCanvas.style.left = "0px";
  84132. VirtualJoystick.vjCanvas.style.zIndex = "5";
  84133. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  84134. // Support for jQuery PEP polyfill
  84135. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  84136. var context = VirtualJoystick.vjCanvas.getContext('2d');
  84137. if (!context) {
  84138. throw new Error("Unable to create canvas for virtual joystick");
  84139. }
  84140. VirtualJoystick.vjCanvasContext = context;
  84141. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  84142. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  84143. document.body.appendChild(VirtualJoystick.vjCanvas);
  84144. }
  84145. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  84146. this.pressed = false;
  84147. // default joystick color
  84148. this._joystickColor = "cyan";
  84149. this._joystickPointerID = -1;
  84150. // current joystick position
  84151. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  84152. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  84153. // origin joystick position
  84154. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  84155. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  84156. this._onPointerDownHandlerRef = function (evt) {
  84157. _this._onPointerDown(evt);
  84158. };
  84159. this._onPointerMoveHandlerRef = function (evt) {
  84160. _this._onPointerMove(evt);
  84161. };
  84162. this._onPointerUpHandlerRef = function (evt) {
  84163. _this._onPointerUp(evt);
  84164. };
  84165. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  84166. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  84167. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  84168. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  84169. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  84170. evt.preventDefault(); // Disables system menu
  84171. }, false);
  84172. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  84173. }
  84174. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  84175. this._joystickSensibility = newJoystickSensibility;
  84176. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  84177. };
  84178. VirtualJoystick.prototype._onPointerDown = function (e) {
  84179. var positionOnScreenCondition;
  84180. e.preventDefault();
  84181. if (this._leftJoystick === true) {
  84182. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  84183. }
  84184. else {
  84185. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  84186. }
  84187. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  84188. // First contact will be dedicated to the virtual joystick
  84189. this._joystickPointerID = e.pointerId;
  84190. this._joystickPointerStartPos.x = e.clientX;
  84191. this._joystickPointerStartPos.y = e.clientY;
  84192. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  84193. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  84194. this._deltaJoystickVector.x = 0;
  84195. this._deltaJoystickVector.y = 0;
  84196. this.pressed = true;
  84197. this._touches.add(e.pointerId.toString(), e);
  84198. }
  84199. else {
  84200. // You can only trigger the action buttons with a joystick declared
  84201. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  84202. this._action();
  84203. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  84204. }
  84205. }
  84206. };
  84207. VirtualJoystick.prototype._onPointerMove = function (e) {
  84208. // If the current pointer is the one associated to the joystick (first touch contact)
  84209. if (this._joystickPointerID == e.pointerId) {
  84210. this._joystickPointerPos.x = e.clientX;
  84211. this._joystickPointerPos.y = e.clientY;
  84212. this._deltaJoystickVector = this._joystickPointerPos.clone();
  84213. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  84214. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  84215. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  84216. switch (this._axisTargetedByLeftAndRight) {
  84217. case JoystickAxis.X:
  84218. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  84219. break;
  84220. case JoystickAxis.Y:
  84221. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  84222. break;
  84223. case JoystickAxis.Z:
  84224. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  84225. break;
  84226. }
  84227. var directionUpDown = this.reverseUpDown ? 1 : -1;
  84228. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  84229. switch (this._axisTargetedByUpAndDown) {
  84230. case JoystickAxis.X:
  84231. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  84232. break;
  84233. case JoystickAxis.Y:
  84234. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  84235. break;
  84236. case JoystickAxis.Z:
  84237. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  84238. break;
  84239. }
  84240. }
  84241. else {
  84242. var data = this._touches.get(e.pointerId.toString());
  84243. if (data) {
  84244. data.x = e.clientX;
  84245. data.y = e.clientY;
  84246. }
  84247. }
  84248. };
  84249. VirtualJoystick.prototype._onPointerUp = function (e) {
  84250. if (this._joystickPointerID == e.pointerId) {
  84251. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  84252. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  84253. this._joystickPointerID = -1;
  84254. this.pressed = false;
  84255. }
  84256. else {
  84257. var touch = this._touches.get(e.pointerId.toString());
  84258. if (touch) {
  84259. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  84260. }
  84261. }
  84262. this._deltaJoystickVector.x = 0;
  84263. this._deltaJoystickVector.y = 0;
  84264. this._touches.remove(e.pointerId.toString());
  84265. };
  84266. /**
  84267. * Change the color of the virtual joystick
  84268. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  84269. */
  84270. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  84271. this._joystickColor = newColor;
  84272. };
  84273. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  84274. this._action = action;
  84275. };
  84276. // Define which axis you'd like to control for left & right
  84277. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  84278. switch (axis) {
  84279. case JoystickAxis.X:
  84280. case JoystickAxis.Y:
  84281. case JoystickAxis.Z:
  84282. this._axisTargetedByLeftAndRight = axis;
  84283. break;
  84284. default:
  84285. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  84286. break;
  84287. }
  84288. };
  84289. // Define which axis you'd like to control for up & down
  84290. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  84291. switch (axis) {
  84292. case JoystickAxis.X:
  84293. case JoystickAxis.Y:
  84294. case JoystickAxis.Z:
  84295. this._axisTargetedByUpAndDown = axis;
  84296. break;
  84297. default:
  84298. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  84299. break;
  84300. }
  84301. };
  84302. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  84303. var _this = this;
  84304. if (this.pressed) {
  84305. this._touches.forEach(function (key, touch) {
  84306. if (touch.pointerId === _this._joystickPointerID) {
  84307. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  84308. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  84309. VirtualJoystick.vjCanvasContext.beginPath();
  84310. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  84311. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  84312. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  84313. VirtualJoystick.vjCanvasContext.stroke();
  84314. VirtualJoystick.vjCanvasContext.closePath();
  84315. VirtualJoystick.vjCanvasContext.beginPath();
  84316. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  84317. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  84318. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  84319. VirtualJoystick.vjCanvasContext.stroke();
  84320. VirtualJoystick.vjCanvasContext.closePath();
  84321. VirtualJoystick.vjCanvasContext.beginPath();
  84322. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  84323. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  84324. VirtualJoystick.vjCanvasContext.stroke();
  84325. VirtualJoystick.vjCanvasContext.closePath();
  84326. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  84327. }
  84328. else {
  84329. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  84330. VirtualJoystick.vjCanvasContext.beginPath();
  84331. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  84332. VirtualJoystick.vjCanvasContext.beginPath();
  84333. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  84334. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  84335. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  84336. VirtualJoystick.vjCanvasContext.stroke();
  84337. VirtualJoystick.vjCanvasContext.closePath();
  84338. touch.prevX = touch.x;
  84339. touch.prevY = touch.y;
  84340. }
  84341. ;
  84342. });
  84343. }
  84344. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  84345. };
  84346. VirtualJoystick.prototype.releaseCanvas = function () {
  84347. if (VirtualJoystick.vjCanvas) {
  84348. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  84349. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  84350. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  84351. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  84352. window.removeEventListener("resize", this._onResize);
  84353. document.body.removeChild(VirtualJoystick.vjCanvas);
  84354. VirtualJoystick.vjCanvas = null;
  84355. }
  84356. };
  84357. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  84358. VirtualJoystick._globalJoystickIndex = 0;
  84359. return VirtualJoystick;
  84360. }());
  84361. BABYLON.VirtualJoystick = VirtualJoystick;
  84362. })(BABYLON || (BABYLON = {}));
  84363. //# sourceMappingURL=babylon.virtualJoystick.js.map
  84364. "use strict";
  84365. var BABYLON;
  84366. (function (BABYLON) {
  84367. // We're mainly based on the logic defined into the FreeCamera code
  84368. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  84369. __extends(VirtualJoysticksCamera, _super);
  84370. function VirtualJoysticksCamera(name, position, scene) {
  84371. var _this = _super.call(this, name, position, scene) || this;
  84372. _this.inputs.addVirtualJoystick();
  84373. return _this;
  84374. }
  84375. VirtualJoysticksCamera.prototype.getClassName = function () {
  84376. return "VirtualJoysticksCamera";
  84377. };
  84378. return VirtualJoysticksCamera;
  84379. }(BABYLON.FreeCamera));
  84380. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  84381. })(BABYLON || (BABYLON = {}));
  84382. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  84383. "use strict";
  84384. var BABYLON;
  84385. (function (BABYLON) {
  84386. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  84387. function FreeCameraVirtualJoystickInput() {
  84388. }
  84389. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  84390. return this._leftjoystick;
  84391. };
  84392. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  84393. return this._rightjoystick;
  84394. };
  84395. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  84396. if (this._leftjoystick) {
  84397. var camera = this.camera;
  84398. var speed = camera._computeLocalCameraSpeed() * 50;
  84399. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  84400. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  84401. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  84402. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  84403. if (!this._leftjoystick.pressed) {
  84404. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  84405. }
  84406. if (!this._rightjoystick.pressed) {
  84407. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  84408. }
  84409. }
  84410. };
  84411. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  84412. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  84413. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  84414. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  84415. this._leftjoystick.setJoystickSensibility(0.15);
  84416. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  84417. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  84418. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  84419. this._rightjoystick.reverseUpDown = true;
  84420. this._rightjoystick.setJoystickSensibility(0.05);
  84421. this._rightjoystick.setJoystickColor("yellow");
  84422. };
  84423. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  84424. this._leftjoystick.releaseCanvas();
  84425. this._rightjoystick.releaseCanvas();
  84426. };
  84427. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  84428. return "FreeCameraVirtualJoystickInput";
  84429. };
  84430. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  84431. return "virtualJoystick";
  84432. };
  84433. return FreeCameraVirtualJoystickInput;
  84434. }());
  84435. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  84436. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  84437. })(BABYLON || (BABYLON = {}));
  84438. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  84439. "use strict";
  84440. var BABYLON;
  84441. (function (BABYLON) {
  84442. var SimplificationSettings = /** @class */ (function () {
  84443. function SimplificationSettings(quality, distance, optimizeMesh) {
  84444. this.quality = quality;
  84445. this.distance = distance;
  84446. this.optimizeMesh = optimizeMesh;
  84447. }
  84448. return SimplificationSettings;
  84449. }());
  84450. BABYLON.SimplificationSettings = SimplificationSettings;
  84451. var SimplificationQueue = /** @class */ (function () {
  84452. function SimplificationQueue() {
  84453. this.running = false;
  84454. this._simplificationArray = [];
  84455. }
  84456. SimplificationQueue.prototype.addTask = function (task) {
  84457. this._simplificationArray.push(task);
  84458. };
  84459. SimplificationQueue.prototype.executeNext = function () {
  84460. var task = this._simplificationArray.pop();
  84461. if (task) {
  84462. this.running = true;
  84463. this.runSimplification(task);
  84464. }
  84465. else {
  84466. this.running = false;
  84467. }
  84468. };
  84469. SimplificationQueue.prototype.runSimplification = function (task) {
  84470. var _this = this;
  84471. if (task.parallelProcessing) {
  84472. //parallel simplifier
  84473. task.settings.forEach(function (setting) {
  84474. var simplifier = _this.getSimplifier(task);
  84475. simplifier.simplify(setting, function (newMesh) {
  84476. task.mesh.addLODLevel(setting.distance, newMesh);
  84477. newMesh.isVisible = true;
  84478. //check if it is the last
  84479. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  84480. //all done, run the success callback.
  84481. task.successCallback();
  84482. }
  84483. _this.executeNext();
  84484. });
  84485. });
  84486. }
  84487. else {
  84488. //single simplifier.
  84489. var simplifier = this.getSimplifier(task);
  84490. var runDecimation = function (setting, callback) {
  84491. simplifier.simplify(setting, function (newMesh) {
  84492. task.mesh.addLODLevel(setting.distance, newMesh);
  84493. newMesh.isVisible = true;
  84494. //run the next quality level
  84495. callback();
  84496. });
  84497. };
  84498. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  84499. runDecimation(task.settings[loop.index], function () {
  84500. loop.executeNext();
  84501. });
  84502. }, function () {
  84503. //execution ended, run the success callback.
  84504. if (task.successCallback) {
  84505. task.successCallback();
  84506. }
  84507. _this.executeNext();
  84508. });
  84509. }
  84510. };
  84511. SimplificationQueue.prototype.getSimplifier = function (task) {
  84512. switch (task.simplificationType) {
  84513. case SimplificationType.QUADRATIC:
  84514. default:
  84515. return new QuadraticErrorSimplification(task.mesh);
  84516. }
  84517. };
  84518. return SimplificationQueue;
  84519. }());
  84520. BABYLON.SimplificationQueue = SimplificationQueue;
  84521. /**
  84522. * The implemented types of simplification.
  84523. * At the moment only Quadratic Error Decimation is implemented.
  84524. */
  84525. var SimplificationType;
  84526. (function (SimplificationType) {
  84527. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  84528. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  84529. var DecimationTriangle = /** @class */ (function () {
  84530. function DecimationTriangle(vertices) {
  84531. this.vertices = vertices;
  84532. this.error = new Array(4);
  84533. this.deleted = false;
  84534. this.isDirty = false;
  84535. this.deletePending = false;
  84536. this.borderFactor = 0;
  84537. }
  84538. return DecimationTriangle;
  84539. }());
  84540. BABYLON.DecimationTriangle = DecimationTriangle;
  84541. var DecimationVertex = /** @class */ (function () {
  84542. function DecimationVertex(position, id) {
  84543. this.position = position;
  84544. this.id = id;
  84545. this.isBorder = true;
  84546. this.q = new QuadraticMatrix();
  84547. this.triangleCount = 0;
  84548. this.triangleStart = 0;
  84549. this.originalOffsets = [];
  84550. }
  84551. DecimationVertex.prototype.updatePosition = function (newPosition) {
  84552. this.position.copyFrom(newPosition);
  84553. };
  84554. return DecimationVertex;
  84555. }());
  84556. BABYLON.DecimationVertex = DecimationVertex;
  84557. var QuadraticMatrix = /** @class */ (function () {
  84558. function QuadraticMatrix(data) {
  84559. this.data = new Array(10);
  84560. for (var i = 0; i < 10; ++i) {
  84561. if (data && data[i]) {
  84562. this.data[i] = data[i];
  84563. }
  84564. else {
  84565. this.data[i] = 0;
  84566. }
  84567. }
  84568. }
  84569. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  84570. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  84571. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  84572. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  84573. return det;
  84574. };
  84575. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  84576. for (var i = 0; i < 10; ++i) {
  84577. this.data[i] += matrix.data[i];
  84578. }
  84579. };
  84580. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  84581. for (var i = 0; i < 10; ++i) {
  84582. this.data[i] += data[i];
  84583. }
  84584. };
  84585. QuadraticMatrix.prototype.add = function (matrix) {
  84586. var m = new QuadraticMatrix();
  84587. for (var i = 0; i < 10; ++i) {
  84588. m.data[i] = this.data[i] + matrix.data[i];
  84589. }
  84590. return m;
  84591. };
  84592. QuadraticMatrix.FromData = function (a, b, c, d) {
  84593. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  84594. };
  84595. //returning an array to avoid garbage collection
  84596. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  84597. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  84598. };
  84599. return QuadraticMatrix;
  84600. }());
  84601. BABYLON.QuadraticMatrix = QuadraticMatrix;
  84602. var Reference = /** @class */ (function () {
  84603. function Reference(vertexId, triangleId) {
  84604. this.vertexId = vertexId;
  84605. this.triangleId = triangleId;
  84606. }
  84607. return Reference;
  84608. }());
  84609. BABYLON.Reference = Reference;
  84610. /**
  84611. * An implementation of the Quadratic Error simplification algorithm.
  84612. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  84613. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  84614. * @author RaananW
  84615. */
  84616. var QuadraticErrorSimplification = /** @class */ (function () {
  84617. function QuadraticErrorSimplification(_mesh) {
  84618. this._mesh = _mesh;
  84619. this.syncIterations = 5000;
  84620. this.aggressiveness = 7;
  84621. this.decimationIterations = 100;
  84622. this.boundingBoxEpsilon = BABYLON.Epsilon;
  84623. }
  84624. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  84625. var _this = this;
  84626. this.initDecimatedMesh();
  84627. //iterating through the submeshes array, one after the other.
  84628. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  84629. _this.initWithMesh(loop.index, function () {
  84630. _this.runDecimation(settings, loop.index, function () {
  84631. loop.executeNext();
  84632. });
  84633. }, settings.optimizeMesh);
  84634. }, function () {
  84635. setTimeout(function () {
  84636. successCallback(_this._reconstructedMesh);
  84637. }, 0);
  84638. });
  84639. };
  84640. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  84641. var _this = this;
  84642. var targetCount = ~~(this.triangles.length * settings.quality);
  84643. var deletedTriangles = 0;
  84644. var triangleCount = this.triangles.length;
  84645. var iterationFunction = function (iteration, callback) {
  84646. setTimeout(function () {
  84647. if (iteration % 5 === 0) {
  84648. _this.updateMesh(iteration === 0);
  84649. }
  84650. for (var i = 0; i < _this.triangles.length; ++i) {
  84651. _this.triangles[i].isDirty = false;
  84652. }
  84653. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  84654. var trianglesIterator = function (i) {
  84655. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  84656. var t = _this.triangles[tIdx];
  84657. if (!t)
  84658. return;
  84659. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  84660. return;
  84661. }
  84662. for (var j = 0; j < 3; ++j) {
  84663. if (t.error[j] < threshold) {
  84664. var deleted0 = [];
  84665. var deleted1 = [];
  84666. var v0 = t.vertices[j];
  84667. var v1 = t.vertices[(j + 1) % 3];
  84668. if (v0.isBorder || v1.isBorder)
  84669. continue;
  84670. var p = BABYLON.Vector3.Zero();
  84671. var n = BABYLON.Vector3.Zero();
  84672. var uv = BABYLON.Vector2.Zero();
  84673. var color = new BABYLON.Color4(0, 0, 0, 1);
  84674. _this.calculateError(v0, v1, p, n, uv, color);
  84675. var delTr = new Array();
  84676. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  84677. continue;
  84678. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  84679. continue;
  84680. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  84681. continue;
  84682. var uniqueArray = new Array();
  84683. delTr.forEach(function (deletedT) {
  84684. if (uniqueArray.indexOf(deletedT) === -1) {
  84685. deletedT.deletePending = true;
  84686. uniqueArray.push(deletedT);
  84687. }
  84688. });
  84689. if (uniqueArray.length % 2 !== 0) {
  84690. continue;
  84691. }
  84692. v0.q = v1.q.add(v0.q);
  84693. v0.updatePosition(p);
  84694. var tStart = _this.references.length;
  84695. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  84696. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  84697. var tCount = _this.references.length - tStart;
  84698. if (tCount <= v0.triangleCount) {
  84699. if (tCount) {
  84700. for (var c = 0; c < tCount; c++) {
  84701. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  84702. }
  84703. }
  84704. }
  84705. else {
  84706. v0.triangleStart = tStart;
  84707. }
  84708. v0.triangleCount = tCount;
  84709. break;
  84710. }
  84711. }
  84712. };
  84713. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  84714. }, 0);
  84715. };
  84716. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  84717. if (triangleCount - deletedTriangles <= targetCount)
  84718. loop.breakLoop();
  84719. else {
  84720. iterationFunction(loop.index, function () {
  84721. loop.executeNext();
  84722. });
  84723. }
  84724. }, function () {
  84725. setTimeout(function () {
  84726. //reconstruct this part of the mesh
  84727. _this.reconstructMesh(submeshIndex);
  84728. successCallback();
  84729. }, 0);
  84730. });
  84731. };
  84732. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  84733. var _this = this;
  84734. this.vertices = [];
  84735. this.triangles = [];
  84736. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  84737. var indices = this._mesh.getIndices();
  84738. var submesh = this._mesh.subMeshes[submeshIndex];
  84739. var findInVertices = function (positionToSearch) {
  84740. if (optimizeMesh) {
  84741. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  84742. if (_this.vertices[ii].position.equals(positionToSearch)) {
  84743. return _this.vertices[ii];
  84744. }
  84745. }
  84746. }
  84747. return null;
  84748. };
  84749. var vertexReferences = [];
  84750. var vertexInit = function (i) {
  84751. if (!positionData) {
  84752. return;
  84753. }
  84754. var offset = i + submesh.verticesStart;
  84755. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  84756. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  84757. vertex.originalOffsets.push(offset);
  84758. if (vertex.id === _this.vertices.length) {
  84759. _this.vertices.push(vertex);
  84760. }
  84761. vertexReferences.push(vertex.id);
  84762. };
  84763. //var totalVertices = mesh.getTotalVertices();
  84764. var totalVertices = submesh.verticesCount;
  84765. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  84766. var indicesInit = function (i) {
  84767. if (!indices) {
  84768. return;
  84769. }
  84770. var offset = (submesh.indexStart / 3) + i;
  84771. var pos = (offset * 3);
  84772. var i0 = indices[pos + 0];
  84773. var i1 = indices[pos + 1];
  84774. var i2 = indices[pos + 2];
  84775. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  84776. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  84777. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  84778. var triangle = new DecimationTriangle([v0, v1, v2]);
  84779. triangle.originalOffset = pos;
  84780. _this.triangles.push(triangle);
  84781. };
  84782. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  84783. _this.init(callback);
  84784. });
  84785. });
  84786. };
  84787. QuadraticErrorSimplification.prototype.init = function (callback) {
  84788. var _this = this;
  84789. var triangleInit1 = function (i) {
  84790. var t = _this.triangles[i];
  84791. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  84792. for (var j = 0; j < 3; j++) {
  84793. 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))));
  84794. }
  84795. };
  84796. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  84797. var triangleInit2 = function (i) {
  84798. var t = _this.triangles[i];
  84799. for (var j = 0; j < 3; ++j) {
  84800. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  84801. }
  84802. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  84803. };
  84804. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  84805. callback();
  84806. });
  84807. });
  84808. };
  84809. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  84810. var newTriangles = [];
  84811. var i;
  84812. for (i = 0; i < this.vertices.length; ++i) {
  84813. this.vertices[i].triangleCount = 0;
  84814. }
  84815. var t;
  84816. var j;
  84817. for (i = 0; i < this.triangles.length; ++i) {
  84818. if (!this.triangles[i].deleted) {
  84819. t = this.triangles[i];
  84820. for (j = 0; j < 3; ++j) {
  84821. t.vertices[j].triangleCount = 1;
  84822. }
  84823. newTriangles.push(t);
  84824. }
  84825. }
  84826. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  84827. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  84828. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  84829. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  84830. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  84831. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  84832. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  84833. var vertexCount = 0;
  84834. for (i = 0; i < this.vertices.length; ++i) {
  84835. var vertex = this.vertices[i];
  84836. vertex.id = vertexCount;
  84837. if (vertex.triangleCount) {
  84838. vertex.originalOffsets.forEach(function (originalOffset) {
  84839. if (!normalData) {
  84840. return;
  84841. }
  84842. newPositionData.push(vertex.position.x);
  84843. newPositionData.push(vertex.position.y);
  84844. newPositionData.push(vertex.position.z);
  84845. newNormalData.push(normalData[originalOffset * 3]);
  84846. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  84847. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  84848. if (uvs && uvs.length) {
  84849. newUVsData.push(uvs[(originalOffset * 2)]);
  84850. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  84851. }
  84852. else if (colorsData && colorsData.length) {
  84853. newColorsData.push(colorsData[(originalOffset * 4)]);
  84854. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  84855. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  84856. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  84857. }
  84858. ++vertexCount;
  84859. });
  84860. }
  84861. }
  84862. var startingIndex = this._reconstructedMesh.getTotalIndices();
  84863. var startingVertex = this._reconstructedMesh.getTotalVertices();
  84864. var submeshesArray = this._reconstructedMesh.subMeshes;
  84865. this._reconstructedMesh.subMeshes = [];
  84866. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  84867. var originalIndices = this._mesh.getIndices();
  84868. for (i = 0; i < newTriangles.length; ++i) {
  84869. t = newTriangles[i]; //now get the new referencing point for each vertex
  84870. [0, 1, 2].forEach(function (idx) {
  84871. var id = originalIndices[t.originalOffset + idx];
  84872. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  84873. if (offset < 0)
  84874. offset = 0;
  84875. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  84876. });
  84877. }
  84878. //overwriting the old vertex buffers and indices.
  84879. this._reconstructedMesh.setIndices(newIndicesArray);
  84880. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  84881. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  84882. if (newUVsData.length > 0)
  84883. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  84884. if (newColorsData.length > 0)
  84885. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  84886. //create submesh
  84887. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  84888. if (submeshIndex > 0) {
  84889. this._reconstructedMesh.subMeshes = [];
  84890. submeshesArray.forEach(function (submesh) {
  84891. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  84892. });
  84893. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  84894. }
  84895. };
  84896. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  84897. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  84898. this._reconstructedMesh.material = this._mesh.material;
  84899. this._reconstructedMesh.parent = this._mesh.parent;
  84900. this._reconstructedMesh.isVisible = false;
  84901. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  84902. };
  84903. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  84904. for (var i = 0; i < vertex1.triangleCount; ++i) {
  84905. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  84906. if (t.deleted)
  84907. continue;
  84908. var s = this.references[vertex1.triangleStart + i].vertexId;
  84909. var v1 = t.vertices[(s + 1) % 3];
  84910. var v2 = t.vertices[(s + 2) % 3];
  84911. if ((v1 === vertex2 || v2 === vertex2)) {
  84912. deletedArray[i] = true;
  84913. delTr.push(t);
  84914. continue;
  84915. }
  84916. var d1 = v1.position.subtract(point);
  84917. d1 = d1.normalize();
  84918. var d2 = v2.position.subtract(point);
  84919. d2 = d2.normalize();
  84920. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  84921. return true;
  84922. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  84923. deletedArray[i] = false;
  84924. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  84925. return true;
  84926. }
  84927. return false;
  84928. };
  84929. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  84930. var newDeleted = deletedTriangles;
  84931. for (var i = 0; i < vertex.triangleCount; ++i) {
  84932. var ref = this.references[vertex.triangleStart + i];
  84933. var t = this.triangles[ref.triangleId];
  84934. if (t.deleted)
  84935. continue;
  84936. if (deletedArray[i] && t.deletePending) {
  84937. t.deleted = true;
  84938. newDeleted++;
  84939. continue;
  84940. }
  84941. t.vertices[ref.vertexId] = origVertex;
  84942. t.isDirty = true;
  84943. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  84944. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  84945. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  84946. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  84947. this.references.push(ref);
  84948. }
  84949. return newDeleted;
  84950. };
  84951. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  84952. for (var i = 0; i < this.vertices.length; ++i) {
  84953. var vCount = [];
  84954. var vId = [];
  84955. var v = this.vertices[i];
  84956. var j;
  84957. for (j = 0; j < v.triangleCount; ++j) {
  84958. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  84959. for (var ii = 0; ii < 3; ii++) {
  84960. var ofs = 0;
  84961. var vv = triangle.vertices[ii];
  84962. while (ofs < vCount.length) {
  84963. if (vId[ofs] === vv.id)
  84964. break;
  84965. ++ofs;
  84966. }
  84967. if (ofs === vCount.length) {
  84968. vCount.push(1);
  84969. vId.push(vv.id);
  84970. }
  84971. else {
  84972. vCount[ofs]++;
  84973. }
  84974. }
  84975. }
  84976. for (j = 0; j < vCount.length; ++j) {
  84977. if (vCount[j] === 1) {
  84978. this.vertices[vId[j]].isBorder = true;
  84979. }
  84980. else {
  84981. this.vertices[vId[j]].isBorder = false;
  84982. }
  84983. }
  84984. }
  84985. };
  84986. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  84987. if (identifyBorders === void 0) { identifyBorders = false; }
  84988. var i;
  84989. if (!identifyBorders) {
  84990. var newTrianglesVector = [];
  84991. for (i = 0; i < this.triangles.length; ++i) {
  84992. if (!this.triangles[i].deleted) {
  84993. newTrianglesVector.push(this.triangles[i]);
  84994. }
  84995. }
  84996. this.triangles = newTrianglesVector;
  84997. }
  84998. for (i = 0; i < this.vertices.length; ++i) {
  84999. this.vertices[i].triangleCount = 0;
  85000. this.vertices[i].triangleStart = 0;
  85001. }
  85002. var t;
  85003. var j;
  85004. var v;
  85005. for (i = 0; i < this.triangles.length; ++i) {
  85006. t = this.triangles[i];
  85007. for (j = 0; j < 3; ++j) {
  85008. v = t.vertices[j];
  85009. v.triangleCount++;
  85010. }
  85011. }
  85012. var tStart = 0;
  85013. for (i = 0; i < this.vertices.length; ++i) {
  85014. this.vertices[i].triangleStart = tStart;
  85015. tStart += this.vertices[i].triangleCount;
  85016. this.vertices[i].triangleCount = 0;
  85017. }
  85018. var newReferences = new Array(this.triangles.length * 3);
  85019. for (i = 0; i < this.triangles.length; ++i) {
  85020. t = this.triangles[i];
  85021. for (j = 0; j < 3; ++j) {
  85022. v = t.vertices[j];
  85023. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  85024. v.triangleCount++;
  85025. }
  85026. }
  85027. this.references = newReferences;
  85028. if (identifyBorders) {
  85029. this.identifyBorder();
  85030. }
  85031. };
  85032. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  85033. var x = point.x;
  85034. var y = point.y;
  85035. var z = point.z;
  85036. 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
  85037. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  85038. };
  85039. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  85040. var q = vertex1.q.add(vertex2.q);
  85041. var border = vertex1.isBorder && vertex2.isBorder;
  85042. var error = 0;
  85043. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  85044. if (qDet !== 0 && !border) {
  85045. if (!pointResult) {
  85046. pointResult = BABYLON.Vector3.Zero();
  85047. }
  85048. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  85049. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  85050. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  85051. error = this.vertexError(q, pointResult);
  85052. }
  85053. else {
  85054. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  85055. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  85056. var error1 = this.vertexError(q, vertex1.position);
  85057. var error2 = this.vertexError(q, vertex2.position);
  85058. var error3 = this.vertexError(q, p3);
  85059. error = Math.min(error1, error2, error3);
  85060. if (error === error1) {
  85061. if (pointResult) {
  85062. pointResult.copyFrom(vertex1.position);
  85063. }
  85064. }
  85065. else if (error === error2) {
  85066. if (pointResult) {
  85067. pointResult.copyFrom(vertex2.position);
  85068. }
  85069. }
  85070. else {
  85071. if (pointResult) {
  85072. pointResult.copyFrom(p3);
  85073. }
  85074. }
  85075. }
  85076. return error;
  85077. };
  85078. return QuadraticErrorSimplification;
  85079. }());
  85080. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  85081. })(BABYLON || (BABYLON = {}));
  85082. //# sourceMappingURL=babylon.meshSimplification.js.map
  85083. "use strict";
  85084. var BABYLON;
  85085. (function (BABYLON) {
  85086. var MeshLODLevel = /** @class */ (function () {
  85087. function MeshLODLevel(distance, mesh) {
  85088. this.distance = distance;
  85089. this.mesh = mesh;
  85090. }
  85091. return MeshLODLevel;
  85092. }());
  85093. BABYLON.MeshLODLevel = MeshLODLevel;
  85094. })(BABYLON || (BABYLON = {}));
  85095. //# sourceMappingURL=babylon.meshLODLevel.js.map
  85096. "use strict";
  85097. var BABYLON;
  85098. (function (BABYLON) {
  85099. /**
  85100. * Defines the root class used to create scene optimization to use with SceneOptimizer
  85101. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85102. */
  85103. var SceneOptimization = /** @class */ (function () {
  85104. /**
  85105. * Creates the SceneOptimization object
  85106. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  85107. * @param desc defines the description associated with the optimization
  85108. */
  85109. function SceneOptimization(
  85110. /**
  85111. * Defines the priority of this optimization (0 by default which means first in the list)
  85112. */
  85113. priority) {
  85114. if (priority === void 0) { priority = 0; }
  85115. this.priority = priority;
  85116. }
  85117. /**
  85118. * Gets a string describing the action executed by the current optimization
  85119. * @returns description string
  85120. */
  85121. SceneOptimization.prototype.getDescription = function () {
  85122. return "";
  85123. };
  85124. /**
  85125. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85126. * @param scene defines the current scene where to apply this optimization
  85127. * @param optimizer defines the current optimizer
  85128. * @returns true if everything that can be done was applied
  85129. */
  85130. SceneOptimization.prototype.apply = function (scene, optimizer) {
  85131. return true;
  85132. };
  85133. ;
  85134. return SceneOptimization;
  85135. }());
  85136. BABYLON.SceneOptimization = SceneOptimization;
  85137. /**
  85138. * Defines an optimization used to reduce the size of render target textures
  85139. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85140. */
  85141. var TextureOptimization = /** @class */ (function (_super) {
  85142. __extends(TextureOptimization, _super);
  85143. /**
  85144. * Creates the TextureOptimization object
  85145. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  85146. * @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
  85147. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  85148. */
  85149. function TextureOptimization(
  85150. /**
  85151. * Defines the priority of this optimization (0 by default which means first in the list)
  85152. */
  85153. priority,
  85154. /**
  85155. * 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
  85156. */
  85157. maximumSize,
  85158. /**
  85159. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  85160. */
  85161. step) {
  85162. if (priority === void 0) { priority = 0; }
  85163. if (maximumSize === void 0) { maximumSize = 1024; }
  85164. if (step === void 0) { step = 0.5; }
  85165. var _this = _super.call(this, priority) || this;
  85166. _this.priority = priority;
  85167. _this.maximumSize = maximumSize;
  85168. _this.step = step;
  85169. return _this;
  85170. }
  85171. /**
  85172. * Gets a string describing the action executed by the current optimization
  85173. * @returns description string
  85174. */
  85175. TextureOptimization.prototype.getDescription = function () {
  85176. return "Reducing render target texture size to " + this.maximumSize;
  85177. };
  85178. /**
  85179. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85180. * @param scene defines the current scene where to apply this optimization
  85181. * @param optimizer defines the current optimizer
  85182. * @returns true if everything that can be done was applied
  85183. */
  85184. TextureOptimization.prototype.apply = function (scene, optimizer) {
  85185. var allDone = true;
  85186. for (var index = 0; index < scene.textures.length; index++) {
  85187. var texture = scene.textures[index];
  85188. if (!texture.canRescale || texture.getContext) {
  85189. continue;
  85190. }
  85191. var currentSize = texture.getSize();
  85192. var maxDimension = Math.max(currentSize.width, currentSize.height);
  85193. if (maxDimension > this.maximumSize) {
  85194. texture.scale(this.step);
  85195. allDone = false;
  85196. }
  85197. }
  85198. return allDone;
  85199. };
  85200. return TextureOptimization;
  85201. }(SceneOptimization));
  85202. BABYLON.TextureOptimization = TextureOptimization;
  85203. /**
  85204. * Defines an optimization used to increase or decrease the rendering resolution
  85205. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85206. */
  85207. var HardwareScalingOptimization = /** @class */ (function (_super) {
  85208. __extends(HardwareScalingOptimization, _super);
  85209. /**
  85210. * Creates the HardwareScalingOptimization object
  85211. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  85212. * @param maximumScale defines the maximum scale to use (2 by default)
  85213. * @param step defines the step to use between two passes (0.5 by default)
  85214. */
  85215. function HardwareScalingOptimization(
  85216. /**
  85217. * Defines the priority of this optimization (0 by default which means first in the list)
  85218. */
  85219. priority,
  85220. /**
  85221. * Defines the maximum scale to use (2 by default)
  85222. */
  85223. maximumScale,
  85224. /**
  85225. * Defines the step to use between two passes (0.5 by default)
  85226. */
  85227. step) {
  85228. if (priority === void 0) { priority = 0; }
  85229. if (maximumScale === void 0) { maximumScale = 2; }
  85230. if (step === void 0) { step = 0.25; }
  85231. var _this = _super.call(this, priority) || this;
  85232. _this.priority = priority;
  85233. _this.maximumScale = maximumScale;
  85234. _this.step = step;
  85235. _this._currentScale = -1;
  85236. _this._directionOffset = 1;
  85237. return _this;
  85238. }
  85239. /**
  85240. * Gets a string describing the action executed by the current optimization
  85241. * @return description string
  85242. */
  85243. HardwareScalingOptimization.prototype.getDescription = function () {
  85244. return "Setting hardware scaling level to " + this._currentScale;
  85245. };
  85246. /**
  85247. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85248. * @param scene defines the current scene where to apply this optimization
  85249. * @param optimizer defines the current optimizer
  85250. * @returns true if everything that can be done was applied
  85251. */
  85252. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  85253. if (this._currentScale === -1) {
  85254. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  85255. if (this._currentScale > this.maximumScale) {
  85256. this._directionOffset = -1;
  85257. }
  85258. }
  85259. this._currentScale += this._directionOffset * this.step;
  85260. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  85261. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  85262. };
  85263. ;
  85264. return HardwareScalingOptimization;
  85265. }(SceneOptimization));
  85266. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  85267. /**
  85268. * Defines an optimization used to remove shadows
  85269. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85270. */
  85271. var ShadowsOptimization = /** @class */ (function (_super) {
  85272. __extends(ShadowsOptimization, _super);
  85273. function ShadowsOptimization() {
  85274. return _super !== null && _super.apply(this, arguments) || this;
  85275. }
  85276. /**
  85277. * Gets a string describing the action executed by the current optimization
  85278. * @return description string
  85279. */
  85280. ShadowsOptimization.prototype.getDescription = function () {
  85281. return "Turning shadows on/off";
  85282. };
  85283. /**
  85284. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85285. * @param scene defines the current scene where to apply this optimization
  85286. * @param optimizer defines the current optimizer
  85287. * @returns true if everything that can be done was applied
  85288. */
  85289. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  85290. scene.shadowsEnabled = optimizer.isInImprovementMode;
  85291. return true;
  85292. };
  85293. ;
  85294. return ShadowsOptimization;
  85295. }(SceneOptimization));
  85296. BABYLON.ShadowsOptimization = ShadowsOptimization;
  85297. /**
  85298. * Defines an optimization used to turn post-processes off
  85299. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85300. */
  85301. var PostProcessesOptimization = /** @class */ (function (_super) {
  85302. __extends(PostProcessesOptimization, _super);
  85303. function PostProcessesOptimization() {
  85304. return _super !== null && _super.apply(this, arguments) || this;
  85305. }
  85306. /**
  85307. * Gets a string describing the action executed by the current optimization
  85308. * @return description string
  85309. */
  85310. PostProcessesOptimization.prototype.getDescription = function () {
  85311. return "Turning post-processes on/off";
  85312. };
  85313. /**
  85314. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85315. * @param scene defines the current scene where to apply this optimization
  85316. * @param optimizer defines the current optimizer
  85317. * @returns true if everything that can be done was applied
  85318. */
  85319. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  85320. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  85321. return true;
  85322. };
  85323. ;
  85324. return PostProcessesOptimization;
  85325. }(SceneOptimization));
  85326. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  85327. /**
  85328. * Defines an optimization used to turn lens flares off
  85329. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85330. */
  85331. var LensFlaresOptimization = /** @class */ (function (_super) {
  85332. __extends(LensFlaresOptimization, _super);
  85333. function LensFlaresOptimization() {
  85334. return _super !== null && _super.apply(this, arguments) || this;
  85335. }
  85336. /**
  85337. * Gets a string describing the action executed by the current optimization
  85338. * @return description string
  85339. */
  85340. LensFlaresOptimization.prototype.getDescription = function () {
  85341. return "Turning lens flares on/off";
  85342. };
  85343. /**
  85344. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85345. * @param scene defines the current scene where to apply this optimization
  85346. * @param optimizer defines the current optimizer
  85347. * @returns true if everything that can be done was applied
  85348. */
  85349. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  85350. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  85351. return true;
  85352. };
  85353. ;
  85354. return LensFlaresOptimization;
  85355. }(SceneOptimization));
  85356. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  85357. /**
  85358. * Defines an optimization based on user defined callback.
  85359. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85360. */
  85361. var CustomOptimization = /** @class */ (function (_super) {
  85362. __extends(CustomOptimization, _super);
  85363. function CustomOptimization() {
  85364. return _super !== null && _super.apply(this, arguments) || this;
  85365. }
  85366. /**
  85367. * Gets a string describing the action executed by the current optimization
  85368. * @returns description string
  85369. */
  85370. CustomOptimization.prototype.getDescription = function () {
  85371. if (this.onGetDescription) {
  85372. return this.onGetDescription();
  85373. }
  85374. return "Running user defined callback";
  85375. };
  85376. /**
  85377. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85378. * @param scene defines the current scene where to apply this optimization
  85379. * @param optimizer defines the current optimizer
  85380. * @returns true if everything that can be done was applied
  85381. */
  85382. CustomOptimization.prototype.apply = function (scene, optimizer) {
  85383. if (this.onApply) {
  85384. return this.onApply(scene, optimizer);
  85385. }
  85386. return true;
  85387. };
  85388. ;
  85389. return CustomOptimization;
  85390. }(SceneOptimization));
  85391. BABYLON.CustomOptimization = CustomOptimization;
  85392. /**
  85393. * Defines an optimization used to turn particles off
  85394. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85395. */
  85396. var ParticlesOptimization = /** @class */ (function (_super) {
  85397. __extends(ParticlesOptimization, _super);
  85398. function ParticlesOptimization() {
  85399. return _super !== null && _super.apply(this, arguments) || this;
  85400. }
  85401. /**
  85402. * Gets a string describing the action executed by the current optimization
  85403. * @return description string
  85404. */
  85405. ParticlesOptimization.prototype.getDescription = function () {
  85406. return "Turning particles on/off";
  85407. };
  85408. /**
  85409. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85410. * @param scene defines the current scene where to apply this optimization
  85411. * @param optimizer defines the current optimizer
  85412. * @returns true if everything that can be done was applied
  85413. */
  85414. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  85415. scene.particlesEnabled = optimizer.isInImprovementMode;
  85416. return true;
  85417. };
  85418. ;
  85419. return ParticlesOptimization;
  85420. }(SceneOptimization));
  85421. BABYLON.ParticlesOptimization = ParticlesOptimization;
  85422. /**
  85423. * Defines an optimization used to turn render targets off
  85424. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85425. */
  85426. var RenderTargetsOptimization = /** @class */ (function (_super) {
  85427. __extends(RenderTargetsOptimization, _super);
  85428. function RenderTargetsOptimization() {
  85429. return _super !== null && _super.apply(this, arguments) || this;
  85430. }
  85431. /**
  85432. * Gets a string describing the action executed by the current optimization
  85433. * @return description string
  85434. */
  85435. RenderTargetsOptimization.prototype.getDescription = function () {
  85436. return "Turning render targets off";
  85437. };
  85438. /**
  85439. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85440. * @param scene defines the current scene where to apply this optimization
  85441. * @param optimizer defines the current optimizer
  85442. * @returns true if everything that can be done was applied
  85443. */
  85444. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  85445. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  85446. return true;
  85447. };
  85448. ;
  85449. return RenderTargetsOptimization;
  85450. }(SceneOptimization));
  85451. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  85452. /**
  85453. * Defines an optimization used to merge meshes with compatible materials
  85454. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85455. */
  85456. var MergeMeshesOptimization = /** @class */ (function (_super) {
  85457. __extends(MergeMeshesOptimization, _super);
  85458. function MergeMeshesOptimization() {
  85459. var _this = _super !== null && _super.apply(this, arguments) || this;
  85460. _this._canBeMerged = function (abstractMesh) {
  85461. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  85462. return false;
  85463. }
  85464. var mesh = abstractMesh;
  85465. if (!mesh.isVisible || !mesh.isEnabled()) {
  85466. return false;
  85467. }
  85468. if (mesh.instances.length > 0) {
  85469. return false;
  85470. }
  85471. if (mesh.skeleton || mesh.hasLODLevels) {
  85472. return false;
  85473. }
  85474. if (mesh.parent) {
  85475. return false;
  85476. }
  85477. return true;
  85478. };
  85479. return _this;
  85480. }
  85481. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  85482. /**
  85483. * Gets or sets a boolean which defines if optimization octree has to be updated
  85484. */
  85485. get: function () {
  85486. return MergeMeshesOptimization._UpdateSelectionTree;
  85487. },
  85488. /**
  85489. * Gets or sets a boolean which defines if optimization octree has to be updated
  85490. */
  85491. set: function (value) {
  85492. MergeMeshesOptimization._UpdateSelectionTree = value;
  85493. },
  85494. enumerable: true,
  85495. configurable: true
  85496. });
  85497. /**
  85498. * Gets a string describing the action executed by the current optimization
  85499. * @return description string
  85500. */
  85501. MergeMeshesOptimization.prototype.getDescription = function () {
  85502. return "Merging similar meshes together";
  85503. };
  85504. /**
  85505. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85506. * @param scene defines the current scene where to apply this optimization
  85507. * @param optimizer defines the current optimizer
  85508. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  85509. * @returns true if everything that can be done was applied
  85510. */
  85511. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  85512. var globalPool = scene.meshes.slice(0);
  85513. var globalLength = globalPool.length;
  85514. for (var index = 0; index < globalLength; index++) {
  85515. var currentPool = new Array();
  85516. var current = globalPool[index];
  85517. // Checks
  85518. if (!this._canBeMerged(current)) {
  85519. continue;
  85520. }
  85521. currentPool.push(current);
  85522. // Find compatible meshes
  85523. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  85524. var otherMesh = globalPool[subIndex];
  85525. if (!this._canBeMerged(otherMesh)) {
  85526. continue;
  85527. }
  85528. if (otherMesh.material !== current.material) {
  85529. continue;
  85530. }
  85531. if (otherMesh.checkCollisions !== current.checkCollisions) {
  85532. continue;
  85533. }
  85534. currentPool.push(otherMesh);
  85535. globalLength--;
  85536. globalPool.splice(subIndex, 1);
  85537. subIndex--;
  85538. }
  85539. if (currentPool.length < 2) {
  85540. continue;
  85541. }
  85542. // Merge meshes
  85543. BABYLON.Mesh.MergeMeshes(currentPool);
  85544. }
  85545. if (updateSelectionTree != undefined) {
  85546. if (updateSelectionTree) {
  85547. scene.createOrUpdateSelectionOctree();
  85548. }
  85549. }
  85550. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  85551. scene.createOrUpdateSelectionOctree();
  85552. }
  85553. return true;
  85554. };
  85555. ;
  85556. MergeMeshesOptimization._UpdateSelectionTree = false;
  85557. return MergeMeshesOptimization;
  85558. }(SceneOptimization));
  85559. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  85560. /**
  85561. * Defines a list of options used by SceneOptimizer
  85562. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85563. */
  85564. var SceneOptimizerOptions = /** @class */ (function () {
  85565. /**
  85566. * Creates a new list of options used by SceneOptimizer
  85567. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  85568. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  85569. */
  85570. function SceneOptimizerOptions(
  85571. /**
  85572. * Defines the target frame rate to reach (60 by default)
  85573. */
  85574. targetFrameRate,
  85575. /**
  85576. * Defines the interval between two checkes (2000ms by default)
  85577. */
  85578. trackerDuration) {
  85579. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  85580. if (trackerDuration === void 0) { trackerDuration = 2000; }
  85581. this.targetFrameRate = targetFrameRate;
  85582. this.trackerDuration = trackerDuration;
  85583. /**
  85584. * Gets the list of optimizations to apply
  85585. */
  85586. this.optimizations = new Array();
  85587. }
  85588. /**
  85589. * Add a new optimization
  85590. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  85591. * @returns the current SceneOptimizerOptions
  85592. */
  85593. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  85594. this.optimizations.push(optimization);
  85595. return this;
  85596. };
  85597. /**
  85598. * Add a new custom optimization
  85599. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  85600. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  85601. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  85602. * @returns the current SceneOptimizerOptions
  85603. */
  85604. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  85605. if (priority === void 0) { priority = 0; }
  85606. var optimization = new CustomOptimization(priority);
  85607. optimization.onApply = onApply;
  85608. optimization.onGetDescription = onGetDescription;
  85609. this.optimizations.push(optimization);
  85610. return this;
  85611. };
  85612. /**
  85613. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  85614. * @param targetFrameRate defines the target frame rate (60 by default)
  85615. * @returns a SceneOptimizerOptions object
  85616. */
  85617. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  85618. var result = new SceneOptimizerOptions(targetFrameRate);
  85619. var priority = 0;
  85620. result.addOptimization(new MergeMeshesOptimization(priority));
  85621. result.addOptimization(new ShadowsOptimization(priority));
  85622. result.addOptimization(new LensFlaresOptimization(priority));
  85623. // Next priority
  85624. priority++;
  85625. result.addOptimization(new PostProcessesOptimization(priority));
  85626. result.addOptimization(new ParticlesOptimization(priority));
  85627. // Next priority
  85628. priority++;
  85629. result.addOptimization(new TextureOptimization(priority, 1024));
  85630. return result;
  85631. };
  85632. /**
  85633. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  85634. * @param targetFrameRate defines the target frame rate (60 by default)
  85635. * @returns a SceneOptimizerOptions object
  85636. */
  85637. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  85638. var result = new SceneOptimizerOptions(targetFrameRate);
  85639. var priority = 0;
  85640. result.addOptimization(new MergeMeshesOptimization(priority));
  85641. result.addOptimization(new ShadowsOptimization(priority));
  85642. result.addOptimization(new LensFlaresOptimization(priority));
  85643. // Next priority
  85644. priority++;
  85645. result.addOptimization(new PostProcessesOptimization(priority));
  85646. result.addOptimization(new ParticlesOptimization(priority));
  85647. // Next priority
  85648. priority++;
  85649. result.addOptimization(new TextureOptimization(priority, 512));
  85650. // Next priority
  85651. priority++;
  85652. result.addOptimization(new RenderTargetsOptimization(priority));
  85653. // Next priority
  85654. priority++;
  85655. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  85656. return result;
  85657. };
  85658. /**
  85659. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  85660. * @param targetFrameRate defines the target frame rate (60 by default)
  85661. * @returns a SceneOptimizerOptions object
  85662. */
  85663. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  85664. var result = new SceneOptimizerOptions(targetFrameRate);
  85665. var priority = 0;
  85666. result.addOptimization(new MergeMeshesOptimization(priority));
  85667. result.addOptimization(new ShadowsOptimization(priority));
  85668. result.addOptimization(new LensFlaresOptimization(priority));
  85669. // Next priority
  85670. priority++;
  85671. result.addOptimization(new PostProcessesOptimization(priority));
  85672. result.addOptimization(new ParticlesOptimization(priority));
  85673. // Next priority
  85674. priority++;
  85675. result.addOptimization(new TextureOptimization(priority, 256));
  85676. // Next priority
  85677. priority++;
  85678. result.addOptimization(new RenderTargetsOptimization(priority));
  85679. // Next priority
  85680. priority++;
  85681. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  85682. return result;
  85683. };
  85684. return SceneOptimizerOptions;
  85685. }());
  85686. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  85687. /**
  85688. * Class used to run optimizations in order to reach a target frame rate
  85689. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85690. */
  85691. var SceneOptimizer = /** @class */ (function () {
  85692. /**
  85693. * Creates a new SceneOptimizer
  85694. * @param scene defines the scene to work on
  85695. * @param options defines the options to use with the SceneOptimizer
  85696. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  85697. * @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)
  85698. */
  85699. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  85700. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  85701. if (improvementMode === void 0) { improvementMode = false; }
  85702. var _this = this;
  85703. this._isRunning = false;
  85704. this._currentPriorityLevel = 0;
  85705. this._targetFrameRate = 60;
  85706. this._trackerDuration = 2000;
  85707. this._currentFrameRate = 0;
  85708. this._improvementMode = false;
  85709. /**
  85710. * Defines an observable called when the optimizer reaches the target frame rate
  85711. */
  85712. this.onSuccessObservable = new BABYLON.Observable();
  85713. /**
  85714. * Defines an observable called when the optimizer enables an optimization
  85715. */
  85716. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  85717. /**
  85718. * Defines an observable called when the optimizer is not able to reach the target frame rate
  85719. */
  85720. this.onFailureObservable = new BABYLON.Observable();
  85721. if (!options) {
  85722. this._options = new SceneOptimizerOptions();
  85723. }
  85724. else {
  85725. this._options = options;
  85726. }
  85727. if (this._options.targetFrameRate) {
  85728. this._targetFrameRate = this._options.targetFrameRate;
  85729. }
  85730. if (this._options.trackerDuration) {
  85731. this._trackerDuration = this._options.trackerDuration;
  85732. }
  85733. if (autoGeneratePriorities) {
  85734. var priority = 0;
  85735. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  85736. var optim = _a[_i];
  85737. optim.priority = priority++;
  85738. }
  85739. }
  85740. this._improvementMode = improvementMode;
  85741. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  85742. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  85743. _this._sceneDisposeObserver = null;
  85744. _this.dispose();
  85745. });
  85746. }
  85747. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  85748. /**
  85749. * Gets a boolean indicating if the optimizer is in improvement mode
  85750. */
  85751. get: function () {
  85752. return this._improvementMode;
  85753. },
  85754. enumerable: true,
  85755. configurable: true
  85756. });
  85757. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  85758. /**
  85759. * Gets the current priority level (0 at start)
  85760. */
  85761. get: function () {
  85762. return this._currentPriorityLevel;
  85763. },
  85764. enumerable: true,
  85765. configurable: true
  85766. });
  85767. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  85768. /**
  85769. * Gets the current frame rate checked by the SceneOptimizer
  85770. */
  85771. get: function () {
  85772. return this._currentFrameRate;
  85773. },
  85774. enumerable: true,
  85775. configurable: true
  85776. });
  85777. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  85778. /**
  85779. * Gets or sets the current target frame rate (60 by default)
  85780. */
  85781. get: function () {
  85782. return this._targetFrameRate;
  85783. },
  85784. /**
  85785. * Gets or sets the current target frame rate (60 by default)
  85786. */
  85787. set: function (value) {
  85788. this._targetFrameRate = value;
  85789. },
  85790. enumerable: true,
  85791. configurable: true
  85792. });
  85793. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  85794. /**
  85795. * Gets or sets the current interval between two checks (every 2000ms by default)
  85796. */
  85797. get: function () {
  85798. return this._trackerDuration;
  85799. },
  85800. /**
  85801. * Gets or sets the current interval between two checks (every 2000ms by default)
  85802. */
  85803. set: function (value) {
  85804. this._trackerDuration = value;
  85805. },
  85806. enumerable: true,
  85807. configurable: true
  85808. });
  85809. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  85810. /**
  85811. * Gets the list of active optimizations
  85812. */
  85813. get: function () {
  85814. return this._options.optimizations;
  85815. },
  85816. enumerable: true,
  85817. configurable: true
  85818. });
  85819. /**
  85820. * Stops the current optimizer
  85821. */
  85822. SceneOptimizer.prototype.stop = function () {
  85823. this._isRunning = false;
  85824. };
  85825. /**
  85826. * Reset the optimizer to initial step (current priority level = 0)
  85827. */
  85828. SceneOptimizer.prototype.reset = function () {
  85829. this._currentPriorityLevel = 0;
  85830. };
  85831. /**
  85832. * Start the optimizer. By default it will try to reach a specific framerate
  85833. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  85834. */
  85835. SceneOptimizer.prototype.start = function () {
  85836. var _this = this;
  85837. if (this._isRunning) {
  85838. return;
  85839. }
  85840. this._isRunning = true;
  85841. // Let's wait for the scene to be ready before running our check
  85842. this._scene.executeWhenReady(function () {
  85843. setTimeout(function () {
  85844. _this._checkCurrentState();
  85845. }, _this._trackerDuration);
  85846. });
  85847. };
  85848. SceneOptimizer.prototype._checkCurrentState = function () {
  85849. var _this = this;
  85850. if (!this._isRunning) {
  85851. return;
  85852. }
  85853. var scene = this._scene;
  85854. var options = this._options;
  85855. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  85856. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  85857. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  85858. this._isRunning = false;
  85859. this.onSuccessObservable.notifyObservers(this);
  85860. return;
  85861. }
  85862. // Apply current level of optimizations
  85863. var allDone = true;
  85864. var noOptimizationApplied = true;
  85865. for (var index = 0; index < options.optimizations.length; index++) {
  85866. var optimization = options.optimizations[index];
  85867. if (optimization.priority === this._currentPriorityLevel) {
  85868. noOptimizationApplied = false;
  85869. allDone = allDone && optimization.apply(scene, this);
  85870. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  85871. }
  85872. }
  85873. // If no optimization was applied, this is a failure :(
  85874. if (noOptimizationApplied) {
  85875. this._isRunning = false;
  85876. this.onFailureObservable.notifyObservers(this);
  85877. return;
  85878. }
  85879. // If all optimizations were done, move to next level
  85880. if (allDone) {
  85881. this._currentPriorityLevel++;
  85882. }
  85883. // Let's the system running for a specific amount of time before checking FPS
  85884. scene.executeWhenReady(function () {
  85885. setTimeout(function () {
  85886. _this._checkCurrentState();
  85887. }, _this._trackerDuration);
  85888. });
  85889. };
  85890. /**
  85891. * Release all resources
  85892. */
  85893. SceneOptimizer.prototype.dispose = function () {
  85894. this.stop();
  85895. this.onSuccessObservable.clear();
  85896. this.onFailureObservable.clear();
  85897. this.onNewOptimizationAppliedObservable.clear();
  85898. if (this._sceneDisposeObserver) {
  85899. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  85900. }
  85901. };
  85902. /**
  85903. * Helper function to create a SceneOptimizer with one single line of code
  85904. * @param scene defines the scene to work on
  85905. * @param options defines the options to use with the SceneOptimizer
  85906. * @param onSuccess defines a callback to call on success
  85907. * @param onFailure defines a callback to call on failure
  85908. * @returns the new SceneOptimizer object
  85909. */
  85910. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  85911. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  85912. if (onSuccess) {
  85913. optimizer.onSuccessObservable.add(function () {
  85914. onSuccess();
  85915. });
  85916. }
  85917. if (onFailure) {
  85918. optimizer.onFailureObservable.add(function () {
  85919. onFailure();
  85920. });
  85921. }
  85922. optimizer.start();
  85923. return optimizer;
  85924. };
  85925. return SceneOptimizer;
  85926. }());
  85927. BABYLON.SceneOptimizer = SceneOptimizer;
  85928. })(BABYLON || (BABYLON = {}));
  85929. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  85930. "use strict";
  85931. var BABYLON;
  85932. (function (BABYLON) {
  85933. var OutlineRenderer = /** @class */ (function () {
  85934. function OutlineRenderer(scene) {
  85935. this.zOffset = 1;
  85936. this._scene = scene;
  85937. }
  85938. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  85939. var _this = this;
  85940. if (useOverlay === void 0) { useOverlay = false; }
  85941. var scene = this._scene;
  85942. var engine = this._scene.getEngine();
  85943. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  85944. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  85945. return;
  85946. }
  85947. var mesh = subMesh.getRenderingMesh();
  85948. var material = subMesh.getMaterial();
  85949. if (!material || !scene.activeCamera) {
  85950. return;
  85951. }
  85952. engine.enableEffect(this._effect);
  85953. // Logarithmic depth
  85954. if (material.useLogarithmicDepth) {
  85955. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  85956. }
  85957. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  85958. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  85959. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  85960. // Bones
  85961. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  85962. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  85963. }
  85964. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  85965. // Alpha test
  85966. if (material && material.needAlphaTesting()) {
  85967. var alphaTexture = material.getAlphaTestTexture();
  85968. if (alphaTexture) {
  85969. this._effect.setTexture("diffuseSampler", alphaTexture);
  85970. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  85971. }
  85972. }
  85973. engine.setZOffset(-this.zOffset);
  85974. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  85975. engine.setZOffset(0);
  85976. };
  85977. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  85978. var defines = [];
  85979. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  85980. var mesh = subMesh.getMesh();
  85981. var material = subMesh.getMaterial();
  85982. if (material) {
  85983. // Alpha test
  85984. if (material.needAlphaTesting()) {
  85985. defines.push("#define ALPHATEST");
  85986. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  85987. attribs.push(BABYLON.VertexBuffer.UVKind);
  85988. defines.push("#define UV1");
  85989. }
  85990. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  85991. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  85992. defines.push("#define UV2");
  85993. }
  85994. }
  85995. //Logarithmic depth
  85996. if (material.useLogarithmicDepth) {
  85997. defines.push("#define LOGARITHMICDEPTH");
  85998. }
  85999. }
  86000. // Bones
  86001. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  86002. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  86003. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  86004. if (mesh.numBoneInfluencers > 4) {
  86005. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  86006. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  86007. }
  86008. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  86009. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  86010. }
  86011. else {
  86012. defines.push("#define NUM_BONE_INFLUENCERS 0");
  86013. }
  86014. // Instances
  86015. if (useInstances) {
  86016. defines.push("#define INSTANCES");
  86017. attribs.push("world0");
  86018. attribs.push("world1");
  86019. attribs.push("world2");
  86020. attribs.push("world3");
  86021. }
  86022. // Get correct effect
  86023. var join = defines.join("\n");
  86024. if (this._cachedDefines !== join) {
  86025. this._cachedDefines = join;
  86026. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  86027. }
  86028. return this._effect.isReady();
  86029. };
  86030. return OutlineRenderer;
  86031. }());
  86032. BABYLON.OutlineRenderer = OutlineRenderer;
  86033. })(BABYLON || (BABYLON = {}));
  86034. //# sourceMappingURL=babylon.outlineRenderer.js.map
  86035. "use strict";
  86036. var BABYLON;
  86037. (function (BABYLON) {
  86038. var FaceAdjacencies = /** @class */ (function () {
  86039. function FaceAdjacencies() {
  86040. this.edges = new Array();
  86041. this.edgesConnectedCount = 0;
  86042. }
  86043. return FaceAdjacencies;
  86044. }());
  86045. var EdgesRenderer = /** @class */ (function () {
  86046. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  86047. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  86048. if (epsilon === void 0) { epsilon = 0.95; }
  86049. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  86050. this.edgesWidthScalerForOrthographic = 1000.0;
  86051. this.edgesWidthScalerForPerspective = 50.0;
  86052. this._linesPositions = new Array();
  86053. this._linesNormals = new Array();
  86054. this._linesIndices = new Array();
  86055. this._buffers = {};
  86056. this._checkVerticesInsteadOfIndices = false;
  86057. this._source = source;
  86058. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  86059. this._epsilon = epsilon;
  86060. this._prepareRessources();
  86061. this._generateEdgesLines();
  86062. }
  86063. EdgesRenderer.prototype._prepareRessources = function () {
  86064. if (this._lineShader) {
  86065. return;
  86066. }
  86067. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  86068. attributes: ["position", "normal"],
  86069. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  86070. });
  86071. this._lineShader.disableDepthWrite = true;
  86072. this._lineShader.backFaceCulling = false;
  86073. };
  86074. EdgesRenderer.prototype._rebuild = function () {
  86075. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  86076. if (buffer) {
  86077. buffer._rebuild();
  86078. }
  86079. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  86080. if (buffer) {
  86081. buffer._rebuild();
  86082. }
  86083. var scene = this._source.getScene();
  86084. var engine = scene.getEngine();
  86085. this._ib = engine.createIndexBuffer(this._linesIndices);
  86086. };
  86087. EdgesRenderer.prototype.dispose = function () {
  86088. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  86089. if (buffer) {
  86090. buffer.dispose();
  86091. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  86092. }
  86093. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  86094. if (buffer) {
  86095. buffer.dispose();
  86096. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  86097. }
  86098. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  86099. this._lineShader.dispose();
  86100. };
  86101. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  86102. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  86103. return 0;
  86104. }
  86105. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  86106. return 1;
  86107. }
  86108. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  86109. return 2;
  86110. }
  86111. return -1;
  86112. };
  86113. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  86114. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  86115. return 0;
  86116. }
  86117. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  86118. return 1;
  86119. }
  86120. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  86121. return 2;
  86122. }
  86123. return -1;
  86124. };
  86125. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  86126. var needToCreateLine;
  86127. if (edge === undefined) {
  86128. needToCreateLine = true;
  86129. }
  86130. else {
  86131. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  86132. needToCreateLine = dotProduct < this._epsilon;
  86133. }
  86134. if (needToCreateLine) {
  86135. var offset = this._linesPositions.length / 3;
  86136. var normal = p0.subtract(p1);
  86137. normal.normalize();
  86138. // Positions
  86139. this._linesPositions.push(p0.x);
  86140. this._linesPositions.push(p0.y);
  86141. this._linesPositions.push(p0.z);
  86142. this._linesPositions.push(p0.x);
  86143. this._linesPositions.push(p0.y);
  86144. this._linesPositions.push(p0.z);
  86145. this._linesPositions.push(p1.x);
  86146. this._linesPositions.push(p1.y);
  86147. this._linesPositions.push(p1.z);
  86148. this._linesPositions.push(p1.x);
  86149. this._linesPositions.push(p1.y);
  86150. this._linesPositions.push(p1.z);
  86151. // Normals
  86152. this._linesNormals.push(p1.x);
  86153. this._linesNormals.push(p1.y);
  86154. this._linesNormals.push(p1.z);
  86155. this._linesNormals.push(-1);
  86156. this._linesNormals.push(p1.x);
  86157. this._linesNormals.push(p1.y);
  86158. this._linesNormals.push(p1.z);
  86159. this._linesNormals.push(1);
  86160. this._linesNormals.push(p0.x);
  86161. this._linesNormals.push(p0.y);
  86162. this._linesNormals.push(p0.z);
  86163. this._linesNormals.push(-1);
  86164. this._linesNormals.push(p0.x);
  86165. this._linesNormals.push(p0.y);
  86166. this._linesNormals.push(p0.z);
  86167. this._linesNormals.push(1);
  86168. // Indices
  86169. this._linesIndices.push(offset);
  86170. this._linesIndices.push(offset + 1);
  86171. this._linesIndices.push(offset + 2);
  86172. this._linesIndices.push(offset);
  86173. this._linesIndices.push(offset + 2);
  86174. this._linesIndices.push(offset + 3);
  86175. }
  86176. };
  86177. EdgesRenderer.prototype._generateEdgesLines = function () {
  86178. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  86179. var indices = this._source.getIndices();
  86180. if (!indices || !positions) {
  86181. return;
  86182. }
  86183. // First let's find adjacencies
  86184. var adjacencies = new Array();
  86185. var faceNormals = new Array();
  86186. var index;
  86187. var faceAdjacencies;
  86188. // Prepare faces
  86189. for (index = 0; index < indices.length; index += 3) {
  86190. faceAdjacencies = new FaceAdjacencies();
  86191. var p0Index = indices[index];
  86192. var p1Index = indices[index + 1];
  86193. var p2Index = indices[index + 2];
  86194. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  86195. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  86196. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  86197. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  86198. faceNormal.normalize();
  86199. faceNormals.push(faceNormal);
  86200. adjacencies.push(faceAdjacencies);
  86201. }
  86202. // Scan
  86203. for (index = 0; index < adjacencies.length; index++) {
  86204. faceAdjacencies = adjacencies[index];
  86205. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  86206. var otherFaceAdjacencies = adjacencies[otherIndex];
  86207. if (faceAdjacencies.edgesConnectedCount === 3) {
  86208. break;
  86209. }
  86210. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  86211. continue;
  86212. }
  86213. var otherP0 = indices[otherIndex * 3];
  86214. var otherP1 = indices[otherIndex * 3 + 1];
  86215. var otherP2 = indices[otherIndex * 3 + 2];
  86216. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  86217. var otherEdgeIndex = 0;
  86218. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  86219. continue;
  86220. }
  86221. switch (edgeIndex) {
  86222. case 0:
  86223. if (this._checkVerticesInsteadOfIndices) {
  86224. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  86225. }
  86226. else {
  86227. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  86228. }
  86229. break;
  86230. case 1:
  86231. if (this._checkVerticesInsteadOfIndices) {
  86232. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  86233. }
  86234. else {
  86235. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  86236. }
  86237. break;
  86238. case 2:
  86239. if (this._checkVerticesInsteadOfIndices) {
  86240. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  86241. }
  86242. else {
  86243. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  86244. }
  86245. break;
  86246. }
  86247. if (otherEdgeIndex === -1) {
  86248. continue;
  86249. }
  86250. faceAdjacencies.edges[edgeIndex] = otherIndex;
  86251. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  86252. faceAdjacencies.edgesConnectedCount++;
  86253. otherFaceAdjacencies.edgesConnectedCount++;
  86254. if (faceAdjacencies.edgesConnectedCount === 3) {
  86255. break;
  86256. }
  86257. }
  86258. }
  86259. }
  86260. // Create lines
  86261. for (index = 0; index < adjacencies.length; index++) {
  86262. // 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
  86263. var current = adjacencies[index];
  86264. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  86265. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  86266. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  86267. }
  86268. // Merge into a single mesh
  86269. var engine = this._source.getScene().getEngine();
  86270. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  86271. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  86272. this._ib = engine.createIndexBuffer(this._linesIndices);
  86273. this._indicesCount = this._linesIndices.length;
  86274. };
  86275. EdgesRenderer.prototype.render = function () {
  86276. var scene = this._source.getScene();
  86277. if (!this._lineShader.isReady() || !scene.activeCamera) {
  86278. return;
  86279. }
  86280. var engine = scene.getEngine();
  86281. this._lineShader._preBind();
  86282. // VBOs
  86283. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  86284. scene.resetCachedMaterial();
  86285. this._lineShader.setColor4("color", this._source.edgesColor);
  86286. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  86287. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  86288. }
  86289. else {
  86290. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  86291. }
  86292. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  86293. this._lineShader.bind(this._source.getWorldMatrix());
  86294. // Draw order
  86295. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  86296. this._lineShader.unbind();
  86297. engine.setDepthWrite(true);
  86298. };
  86299. return EdgesRenderer;
  86300. }());
  86301. BABYLON.EdgesRenderer = EdgesRenderer;
  86302. })(BABYLON || (BABYLON = {}));
  86303. //# sourceMappingURL=babylon.edgesRenderer.js.map
  86304. "use strict";
  86305. var __assign = (this && this.__assign) || Object.assign || function(t) {
  86306. for (var s, i = 1, n = arguments.length; i < n; i++) {
  86307. s = arguments[i];
  86308. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  86309. t[p] = s[p];
  86310. }
  86311. return t;
  86312. };
  86313. var BABYLON;
  86314. (function (BABYLON) {
  86315. /**
  86316. * The effect layer Helps adding post process effect blended with the main pass.
  86317. *
  86318. * This can be for instance use to generate glow or higlight effects on the scene.
  86319. *
  86320. * The effect layer class can not be used directly and is intented to inherited from to be
  86321. * customized per effects.
  86322. */
  86323. var EffectLayer = /** @class */ (function () {
  86324. /**
  86325. * Instantiates a new effect Layer and references it in the scene.
  86326. * @param name The name of the layer
  86327. * @param scene The scene to use the layer in
  86328. */
  86329. function EffectLayer(
  86330. /** The Friendly of the effect in the scene */
  86331. name, scene) {
  86332. this.name = name;
  86333. this._vertexBuffers = {};
  86334. this._maxSize = 0;
  86335. this._mainTextureDesiredSize = { width: 0, height: 0 };
  86336. this._shouldRender = true;
  86337. this._postProcesses = [];
  86338. this._textures = [];
  86339. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  86340. /**
  86341. * The clear color of the texture used to generate the glow map.
  86342. */
  86343. this.neutralColor = new BABYLON.Color4();
  86344. /**
  86345. * Specifies wether the highlight layer is enabled or not.
  86346. */
  86347. this.isEnabled = true;
  86348. /**
  86349. * An event triggered when the effect layer has been disposed.
  86350. */
  86351. this.onDisposeObservable = new BABYLON.Observable();
  86352. /**
  86353. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  86354. */
  86355. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  86356. /**
  86357. * An event triggered when the generated texture is being merged in the scene.
  86358. */
  86359. this.onBeforeComposeObservable = new BABYLON.Observable();
  86360. /**
  86361. * An event triggered when the generated texture has been merged in the scene.
  86362. */
  86363. this.onAfterComposeObservable = new BABYLON.Observable();
  86364. /**
  86365. * An event triggered when the efffect layer changes its size.
  86366. */
  86367. this.onSizeChangedObservable = new BABYLON.Observable();
  86368. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  86369. this._engine = scene.getEngine();
  86370. this._maxSize = this._engine.getCaps().maxTextureSize;
  86371. this._scene.effectLayers.push(this);
  86372. // Generate Buffers
  86373. this._generateIndexBuffer();
  86374. this._genrateVertexBuffer();
  86375. }
  86376. Object.defineProperty(EffectLayer.prototype, "camera", {
  86377. /**
  86378. * Gets the camera attached to the layer.
  86379. */
  86380. get: function () {
  86381. return this._effectLayerOptions.camera;
  86382. },
  86383. enumerable: true,
  86384. configurable: true
  86385. });
  86386. /**
  86387. * Initializes the effect layer with the required options.
  86388. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  86389. */
  86390. EffectLayer.prototype._init = function (options) {
  86391. // Adapt options
  86392. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  86393. this._setMainTextureSize();
  86394. this._createMainTexture();
  86395. this._createTextureAndPostProcesses();
  86396. this._mergeEffect = this._createMergeEffect();
  86397. };
  86398. /**
  86399. * Generates the index buffer of the full screen quad blending to the main canvas.
  86400. */
  86401. EffectLayer.prototype._generateIndexBuffer = function () {
  86402. // Indices
  86403. var indices = [];
  86404. indices.push(0);
  86405. indices.push(1);
  86406. indices.push(2);
  86407. indices.push(0);
  86408. indices.push(2);
  86409. indices.push(3);
  86410. this._indexBuffer = this._engine.createIndexBuffer(indices);
  86411. };
  86412. /**
  86413. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  86414. */
  86415. EffectLayer.prototype._genrateVertexBuffer = function () {
  86416. // VBO
  86417. var vertices = [];
  86418. vertices.push(1, 1);
  86419. vertices.push(-1, 1);
  86420. vertices.push(-1, -1);
  86421. vertices.push(1, -1);
  86422. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  86423. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  86424. };
  86425. /**
  86426. * Sets the main texture desired size which is the closest power of two
  86427. * of the engine canvas size.
  86428. */
  86429. EffectLayer.prototype._setMainTextureSize = function () {
  86430. if (this._effectLayerOptions.mainTextureFixedSize) {
  86431. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  86432. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  86433. }
  86434. else {
  86435. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  86436. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  86437. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  86438. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  86439. }
  86440. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  86441. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  86442. };
  86443. /**
  86444. * Creates the main texture for the effect layer.
  86445. */
  86446. EffectLayer.prototype._createMainTexture = function () {
  86447. var _this = this;
  86448. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  86449. width: this._mainTextureDesiredSize.width,
  86450. height: this._mainTextureDesiredSize.height
  86451. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  86452. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  86453. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86454. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86455. this._mainTexture.anisotropicFilteringLevel = 1;
  86456. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  86457. this._mainTexture.renderParticles = false;
  86458. this._mainTexture.renderList = null;
  86459. this._mainTexture.ignoreCameraViewport = true;
  86460. // Custom render function
  86461. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  86462. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  86463. var index;
  86464. var engine = _this._scene.getEngine();
  86465. if (depthOnlySubMeshes.length) {
  86466. engine.setColorWrite(false);
  86467. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  86468. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  86469. }
  86470. engine.setColorWrite(true);
  86471. }
  86472. for (index = 0; index < opaqueSubMeshes.length; index++) {
  86473. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  86474. }
  86475. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  86476. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  86477. }
  86478. for (index = 0; index < transparentSubMeshes.length; index++) {
  86479. _this._renderSubMesh(transparentSubMeshes.data[index]);
  86480. }
  86481. };
  86482. this._mainTexture.onClearObservable.add(function (engine) {
  86483. engine.clear(_this.neutralColor, true, true, true);
  86484. });
  86485. };
  86486. /**
  86487. * Checks for the readiness of the element composing the layer.
  86488. * @param subMesh the mesh to check for
  86489. * @param useInstances specify wether or not to use instances to render the mesh
  86490. * @param emissiveTexture the associated emissive texture used to generate the glow
  86491. * @return true if ready otherwise, false
  86492. */
  86493. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  86494. var material = subMesh.getMaterial();
  86495. if (!material) {
  86496. return false;
  86497. }
  86498. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  86499. return false;
  86500. }
  86501. var defines = [];
  86502. var attribs = [BABYLON.VertexBuffer.PositionKind];
  86503. var mesh = subMesh.getMesh();
  86504. var uv1 = false;
  86505. var uv2 = false;
  86506. // Alpha test
  86507. if (material && material.needAlphaTesting()) {
  86508. var alphaTexture = material.getAlphaTestTexture();
  86509. if (alphaTexture) {
  86510. defines.push("#define ALPHATEST");
  86511. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  86512. alphaTexture.coordinatesIndex === 1) {
  86513. defines.push("#define DIFFUSEUV2");
  86514. uv2 = true;
  86515. }
  86516. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  86517. defines.push("#define DIFFUSEUV1");
  86518. uv1 = true;
  86519. }
  86520. }
  86521. }
  86522. // Emissive
  86523. if (emissiveTexture) {
  86524. defines.push("#define EMISSIVE");
  86525. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  86526. emissiveTexture.coordinatesIndex === 1) {
  86527. defines.push("#define EMISSIVEUV2");
  86528. uv2 = true;
  86529. }
  86530. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  86531. defines.push("#define EMISSIVEUV1");
  86532. uv1 = true;
  86533. }
  86534. }
  86535. if (uv1) {
  86536. attribs.push(BABYLON.VertexBuffer.UVKind);
  86537. defines.push("#define UV1");
  86538. }
  86539. if (uv2) {
  86540. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  86541. defines.push("#define UV2");
  86542. }
  86543. // Bones
  86544. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  86545. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  86546. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  86547. if (mesh.numBoneInfluencers > 4) {
  86548. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  86549. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  86550. }
  86551. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  86552. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  86553. }
  86554. else {
  86555. defines.push("#define NUM_BONE_INFLUENCERS 0");
  86556. }
  86557. // Morph targets
  86558. var manager = mesh.morphTargetManager;
  86559. var morphInfluencers = 0;
  86560. if (manager) {
  86561. if (manager.numInfluencers > 0) {
  86562. defines.push("#define MORPHTARGETS");
  86563. morphInfluencers = manager.numInfluencers;
  86564. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  86565. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  86566. }
  86567. }
  86568. // Instances
  86569. if (useInstances) {
  86570. defines.push("#define INSTANCES");
  86571. attribs.push("world0");
  86572. attribs.push("world1");
  86573. attribs.push("world2");
  86574. attribs.push("world3");
  86575. }
  86576. // Get correct effect
  86577. var join = defines.join("\n");
  86578. if (this._cachedDefines !== join) {
  86579. this._cachedDefines = join;
  86580. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  86581. }
  86582. return this._effectLayerMapGenerationEffect.isReady();
  86583. };
  86584. /**
  86585. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  86586. */
  86587. EffectLayer.prototype.render = function () {
  86588. var currentEffect = this._mergeEffect;
  86589. // Check
  86590. if (!currentEffect.isReady())
  86591. return;
  86592. for (var i = 0; i < this._postProcesses.length; i++) {
  86593. if (!this._postProcesses[i].isReady()) {
  86594. return;
  86595. }
  86596. }
  86597. var engine = this._scene.getEngine();
  86598. this.onBeforeComposeObservable.notifyObservers(this);
  86599. // Render
  86600. engine.enableEffect(currentEffect);
  86601. engine.setState(false);
  86602. // VBOs
  86603. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  86604. // Cache
  86605. var previousAlphaMode = engine.getAlphaMode();
  86606. // Go Blend.
  86607. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  86608. // Blends the map on the main canvas.
  86609. this._internalRender(currentEffect);
  86610. // Restore Alpha
  86611. engine.setAlphaMode(previousAlphaMode);
  86612. this.onAfterComposeObservable.notifyObservers(this);
  86613. // Handle size changes.
  86614. var size = this._mainTexture.getSize();
  86615. this._setMainTextureSize();
  86616. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  86617. // Recreate RTT and post processes on size change.
  86618. this.onSizeChangedObservable.notifyObservers(this);
  86619. this._disposeTextureAndPostProcesses();
  86620. this._createMainTexture();
  86621. this._createTextureAndPostProcesses();
  86622. }
  86623. };
  86624. /**
  86625. * Determine if a given mesh will be used in the current effect.
  86626. * @param mesh mesh to test
  86627. * @returns true if the mesh will be used
  86628. */
  86629. EffectLayer.prototype.hasMesh = function (mesh) {
  86630. return true;
  86631. };
  86632. /**
  86633. * Returns true if the layer contains information to display, otherwise false.
  86634. * @returns true if the glow layer should be rendered
  86635. */
  86636. EffectLayer.prototype.shouldRender = function () {
  86637. return this.isEnabled && this._shouldRender;
  86638. };
  86639. /**
  86640. * Returns true if the mesh should render, otherwise false.
  86641. * @param mesh The mesh to render
  86642. * @returns true if it should render otherwise false
  86643. */
  86644. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  86645. return true;
  86646. };
  86647. /**
  86648. * Returns true if the mesh should render, otherwise false.
  86649. * @param mesh The mesh to render
  86650. * @returns true if it should render otherwise false
  86651. */
  86652. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  86653. return true;
  86654. };
  86655. /**
  86656. * Renders the submesh passed in parameter to the generation map.
  86657. */
  86658. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  86659. var _this = this;
  86660. if (!this.shouldRender()) {
  86661. return;
  86662. }
  86663. var material = subMesh.getMaterial();
  86664. var mesh = subMesh.getRenderingMesh();
  86665. var scene = this._scene;
  86666. var engine = scene.getEngine();
  86667. if (!material) {
  86668. return;
  86669. }
  86670. // Do not block in blend mode.
  86671. if (material.needAlphaBlendingForMesh(mesh)) {
  86672. return;
  86673. }
  86674. // Culling
  86675. engine.setState(material.backFaceCulling);
  86676. // Managing instances
  86677. var batch = mesh._getInstancesRenderList(subMesh._id);
  86678. if (batch.mustReturn) {
  86679. return;
  86680. }
  86681. // Early Exit per mesh
  86682. if (!this._shouldRenderMesh(mesh)) {
  86683. return;
  86684. }
  86685. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  86686. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  86687. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  86688. engine.enableEffect(this._effectLayerMapGenerationEffect);
  86689. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  86690. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  86691. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  86692. // Alpha test
  86693. if (material && material.needAlphaTesting()) {
  86694. var alphaTexture = material.getAlphaTestTexture();
  86695. if (alphaTexture) {
  86696. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  86697. var textureMatrix = alphaTexture.getTextureMatrix();
  86698. if (textureMatrix) {
  86699. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  86700. }
  86701. }
  86702. }
  86703. // Glow emissive only
  86704. if (this._emissiveTextureAndColor.texture) {
  86705. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  86706. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  86707. }
  86708. // Bones
  86709. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  86710. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  86711. }
  86712. // Morph targets
  86713. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  86714. // Draw
  86715. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  86716. }
  86717. else {
  86718. // Need to reset refresh rate of the shadowMap
  86719. this._mainTexture.resetRefreshCounter();
  86720. }
  86721. };
  86722. /**
  86723. * Rebuild the required buffers.
  86724. * @ignore Internal use only.
  86725. */
  86726. EffectLayer.prototype._rebuild = function () {
  86727. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  86728. if (vb) {
  86729. vb._rebuild();
  86730. }
  86731. this._generateIndexBuffer();
  86732. };
  86733. /**
  86734. * Dispose only the render target textures and post process.
  86735. */
  86736. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  86737. this._mainTexture.dispose();
  86738. for (var i = 0; i < this._postProcesses.length; i++) {
  86739. if (this._postProcesses[i]) {
  86740. this._postProcesses[i].dispose();
  86741. }
  86742. }
  86743. this._postProcesses = [];
  86744. for (var i = 0; i < this._textures.length; i++) {
  86745. if (this._textures[i]) {
  86746. this._textures[i].dispose();
  86747. }
  86748. }
  86749. this._textures = [];
  86750. };
  86751. /**
  86752. * Dispose the highlight layer and free resources.
  86753. */
  86754. EffectLayer.prototype.dispose = function () {
  86755. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  86756. if (vertexBuffer) {
  86757. vertexBuffer.dispose();
  86758. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  86759. }
  86760. if (this._indexBuffer) {
  86761. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  86762. this._indexBuffer = null;
  86763. }
  86764. // Clean textures and post processes
  86765. this._disposeTextureAndPostProcesses();
  86766. // Remove from scene
  86767. var index = this._scene.effectLayers.indexOf(this, 0);
  86768. if (index > -1) {
  86769. this._scene.effectLayers.splice(index, 1);
  86770. }
  86771. // Callback
  86772. this.onDisposeObservable.notifyObservers(this);
  86773. this.onDisposeObservable.clear();
  86774. this.onBeforeRenderMainTextureObservable.clear();
  86775. this.onBeforeComposeObservable.clear();
  86776. this.onAfterComposeObservable.clear();
  86777. this.onSizeChangedObservable.clear();
  86778. };
  86779. return EffectLayer;
  86780. }());
  86781. BABYLON.EffectLayer = EffectLayer;
  86782. })(BABYLON || (BABYLON = {}));
  86783. //# sourceMappingURL=babylon.effectLayer.js.map
  86784. "use strict";
  86785. var BABYLON;
  86786. (function (BABYLON) {
  86787. /**
  86788. * Special Glow Blur post process only blurring the alpha channel
  86789. * It enforces keeping the most luminous color in the color channel.
  86790. */
  86791. var GlowBlurPostProcess = /** @class */ (function (_super) {
  86792. __extends(GlowBlurPostProcess, _super);
  86793. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  86794. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  86795. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  86796. _this.direction = direction;
  86797. _this.kernel = kernel;
  86798. _this.onApplyObservable.add(function (effect) {
  86799. effect.setFloat2("screenSize", _this.width, _this.height);
  86800. effect.setVector2("direction", _this.direction);
  86801. effect.setFloat("blurWidth", _this.kernel);
  86802. });
  86803. return _this;
  86804. }
  86805. return GlowBlurPostProcess;
  86806. }(BABYLON.PostProcess));
  86807. /**
  86808. * The highlight layer Helps adding a glow effect around a mesh.
  86809. *
  86810. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  86811. * glowy meshes to your scene.
  86812. *
  86813. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  86814. */
  86815. var HighlightLayer = /** @class */ (function (_super) {
  86816. __extends(HighlightLayer, _super);
  86817. /**
  86818. * Instantiates a new highlight Layer and references it to the scene..
  86819. * @param name The name of the layer
  86820. * @param scene The scene to use the layer in
  86821. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  86822. */
  86823. function HighlightLayer(name, scene, options) {
  86824. var _this = _super.call(this, name, scene) || this;
  86825. _this.name = name;
  86826. /**
  86827. * Specifies whether or not the inner glow is ACTIVE in the layer.
  86828. */
  86829. _this.innerGlow = true;
  86830. /**
  86831. * Specifies whether or not the outer glow is ACTIVE in the layer.
  86832. */
  86833. _this.outerGlow = true;
  86834. /**
  86835. * An event triggered when the highlight layer is being blurred.
  86836. */
  86837. _this.onBeforeBlurObservable = new BABYLON.Observable();
  86838. /**
  86839. * An event triggered when the highlight layer has been blurred.
  86840. */
  86841. _this.onAfterBlurObservable = new BABYLON.Observable();
  86842. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  86843. _this._meshes = {};
  86844. _this._excludedMeshes = {};
  86845. _this.neutralColor = HighlightLayer.NeutralColor;
  86846. // Warn on stencil
  86847. if (!_this._engine.isStencilEnable) {
  86848. 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 }");
  86849. }
  86850. // Adapt options
  86851. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  86852. // Initialize the layer
  86853. _this._init({
  86854. alphaBlendingMode: _this._options.alphaBlendingMode,
  86855. camera: _this._options.camera,
  86856. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  86857. mainTextureRatio: _this._options.mainTextureRatio
  86858. });
  86859. // Do not render as long as no meshes have been added
  86860. _this._shouldRender = false;
  86861. return _this;
  86862. }
  86863. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  86864. /**
  86865. * Gets the horizontal size of the blur.
  86866. */
  86867. get: function () {
  86868. return this._horizontalBlurPostprocess.kernel;
  86869. },
  86870. /**
  86871. * Specifies the horizontal size of the blur.
  86872. */
  86873. set: function (value) {
  86874. this._horizontalBlurPostprocess.kernel = value;
  86875. },
  86876. enumerable: true,
  86877. configurable: true
  86878. });
  86879. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  86880. /**
  86881. * Gets the vertical size of the blur.
  86882. */
  86883. get: function () {
  86884. return this._verticalBlurPostprocess.kernel;
  86885. },
  86886. /**
  86887. * Specifies the vertical size of the blur.
  86888. */
  86889. set: function (value) {
  86890. this._verticalBlurPostprocess.kernel = value;
  86891. },
  86892. enumerable: true,
  86893. configurable: true
  86894. });
  86895. /**
  86896. * Get the effect name of the layer.
  86897. * @return The effect name
  86898. */
  86899. HighlightLayer.prototype.getEffectName = function () {
  86900. return HighlightLayer.EffectName;
  86901. };
  86902. /**
  86903. * Create the merge effect. This is the shader use to blit the information back
  86904. * to the main canvas at the end of the scene rendering.
  86905. */
  86906. HighlightLayer.prototype._createMergeEffect = function () {
  86907. // Effect
  86908. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  86909. };
  86910. /**
  86911. * Creates the render target textures and post processes used in the highlight layer.
  86912. */
  86913. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  86914. var _this = this;
  86915. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  86916. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  86917. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  86918. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  86919. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  86920. width: blurTextureWidth,
  86921. height: blurTextureHeight
  86922. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86923. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86924. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86925. this._blurTexture.anisotropicFilteringLevel = 16;
  86926. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  86927. this._blurTexture.renderParticles = false;
  86928. this._blurTexture.ignoreCameraViewport = true;
  86929. this._textures = [this._blurTexture];
  86930. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  86931. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  86932. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  86933. effect.setTexture("textureSampler", _this._mainTexture);
  86934. });
  86935. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  86936. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  86937. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  86938. });
  86939. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  86940. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  86941. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  86942. });
  86943. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  86944. }
  86945. else {
  86946. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  86947. width: blurTextureWidth,
  86948. height: blurTextureHeight
  86949. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86950. this._horizontalBlurPostprocess.width = blurTextureWidth;
  86951. this._horizontalBlurPostprocess.height = blurTextureHeight;
  86952. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  86953. effect.setTexture("textureSampler", _this._mainTexture);
  86954. });
  86955. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  86956. width: blurTextureWidth,
  86957. height: blurTextureHeight
  86958. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86959. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  86960. }
  86961. this._mainTexture.onAfterUnbindObservable.add(function () {
  86962. _this.onBeforeBlurObservable.notifyObservers(_this);
  86963. var internalTexture = _this._blurTexture.getInternalTexture();
  86964. if (internalTexture) {
  86965. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  86966. }
  86967. _this.onAfterBlurObservable.notifyObservers(_this);
  86968. });
  86969. // Prevent autoClear.
  86970. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  86971. };
  86972. /**
  86973. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  86974. */
  86975. HighlightLayer.prototype.needStencil = function () {
  86976. return true;
  86977. };
  86978. /**
  86979. * Checks for the readiness of the element composing the layer.
  86980. * @param subMesh the mesh to check for
  86981. * @param useInstances specify wether or not to use instances to render the mesh
  86982. * @param emissiveTexture the associated emissive texture used to generate the glow
  86983. * @return true if ready otherwise, false
  86984. */
  86985. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  86986. var material = subMesh.getMaterial();
  86987. var mesh = subMesh.getRenderingMesh();
  86988. if (!material || !mesh || !this._meshes) {
  86989. return false;
  86990. }
  86991. var emissiveTexture = null;
  86992. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  86993. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  86994. emissiveTexture = material.emissiveTexture;
  86995. }
  86996. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  86997. };
  86998. /**
  86999. * Implementation specific of rendering the generating effect on the main canvas.
  87000. * @param effect The effect used to render through
  87001. */
  87002. HighlightLayer.prototype._internalRender = function (effect) {
  87003. // Texture
  87004. effect.setTexture("textureSampler", this._blurTexture);
  87005. // Cache
  87006. var engine = this._engine;
  87007. var previousStencilBuffer = engine.getStencilBuffer();
  87008. var previousStencilFunction = engine.getStencilFunction();
  87009. var previousStencilMask = engine.getStencilMask();
  87010. var previousStencilOperationPass = engine.getStencilOperationPass();
  87011. var previousStencilOperationFail = engine.getStencilOperationFail();
  87012. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  87013. var previousStencilReference = engine.getStencilFunctionReference();
  87014. // Stencil operations
  87015. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  87016. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  87017. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  87018. // Draw order
  87019. engine.setStencilMask(0x00);
  87020. engine.setStencilBuffer(true);
  87021. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  87022. // 2 passes inner outer
  87023. if (this.outerGlow) {
  87024. effect.setFloat("offset", 0);
  87025. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  87026. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  87027. }
  87028. if (this.innerGlow) {
  87029. effect.setFloat("offset", 1);
  87030. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  87031. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  87032. }
  87033. // Restore Cache
  87034. engine.setStencilFunction(previousStencilFunction);
  87035. engine.setStencilMask(previousStencilMask);
  87036. engine.setStencilBuffer(previousStencilBuffer);
  87037. engine.setStencilOperationPass(previousStencilOperationPass);
  87038. engine.setStencilOperationFail(previousStencilOperationFail);
  87039. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  87040. engine.setStencilFunctionReference(previousStencilReference);
  87041. };
  87042. /**
  87043. * Returns true if the layer contains information to display, otherwise false.
  87044. */
  87045. HighlightLayer.prototype.shouldRender = function () {
  87046. if (_super.prototype.shouldRender.call(this)) {
  87047. return this._meshes ? true : false;
  87048. }
  87049. return false;
  87050. };
  87051. /**
  87052. * Returns true if the mesh should render, otherwise false.
  87053. * @param mesh The mesh to render
  87054. * @returns true if it should render otherwise false
  87055. */
  87056. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  87057. // Excluded Mesh
  87058. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  87059. return false;
  87060. }
  87061. ;
  87062. return true;
  87063. };
  87064. /**
  87065. * Sets the required values for both the emissive texture and and the main color.
  87066. */
  87067. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  87068. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  87069. if (highlightLayerMesh) {
  87070. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  87071. }
  87072. else {
  87073. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  87074. }
  87075. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  87076. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  87077. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  87078. }
  87079. else {
  87080. this._emissiveTextureAndColor.texture = null;
  87081. }
  87082. };
  87083. /**
  87084. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  87085. * @param mesh The mesh to exclude from the highlight layer
  87086. */
  87087. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  87088. if (!this._excludedMeshes) {
  87089. return;
  87090. }
  87091. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  87092. if (!meshExcluded) {
  87093. this._excludedMeshes[mesh.uniqueId] = {
  87094. mesh: mesh,
  87095. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  87096. mesh.getEngine().setStencilBuffer(false);
  87097. }),
  87098. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  87099. mesh.getEngine().setStencilBuffer(true);
  87100. }),
  87101. };
  87102. }
  87103. };
  87104. /**
  87105. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  87106. * @param mesh The mesh to highlight
  87107. */
  87108. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  87109. if (!this._excludedMeshes) {
  87110. return;
  87111. }
  87112. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  87113. if (meshExcluded) {
  87114. if (meshExcluded.beforeRender) {
  87115. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  87116. }
  87117. if (meshExcluded.afterRender) {
  87118. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  87119. }
  87120. }
  87121. this._excludedMeshes[mesh.uniqueId] = null;
  87122. };
  87123. /**
  87124. * Determine if a given mesh will be highlighted by the current HighlightLayer
  87125. * @param mesh mesh to test
  87126. * @returns true if the mesh will be highlighted by the current HighlightLayer
  87127. */
  87128. HighlightLayer.prototype.hasMesh = function (mesh) {
  87129. if (!this._meshes) {
  87130. return false;
  87131. }
  87132. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  87133. };
  87134. /**
  87135. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  87136. * @param mesh The mesh to highlight
  87137. * @param color The color of the highlight
  87138. * @param glowEmissiveOnly Extract the glow from the emissive texture
  87139. */
  87140. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  87141. var _this = this;
  87142. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  87143. if (!this._meshes) {
  87144. return;
  87145. }
  87146. var meshHighlight = this._meshes[mesh.uniqueId];
  87147. if (meshHighlight) {
  87148. meshHighlight.color = color;
  87149. }
  87150. else {
  87151. this._meshes[mesh.uniqueId] = {
  87152. mesh: mesh,
  87153. color: color,
  87154. // Lambda required for capture due to Observable this context
  87155. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  87156. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  87157. _this._defaultStencilReference(mesh);
  87158. }
  87159. else {
  87160. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  87161. }
  87162. }),
  87163. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  87164. glowEmissiveOnly: glowEmissiveOnly
  87165. };
  87166. }
  87167. this._shouldRender = true;
  87168. };
  87169. /**
  87170. * Remove a mesh from the highlight layer in order to make it stop glowing.
  87171. * @param mesh The mesh to highlight
  87172. */
  87173. HighlightLayer.prototype.removeMesh = function (mesh) {
  87174. if (!this._meshes) {
  87175. return;
  87176. }
  87177. var meshHighlight = this._meshes[mesh.uniqueId];
  87178. if (meshHighlight) {
  87179. if (meshHighlight.observerHighlight) {
  87180. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  87181. }
  87182. if (meshHighlight.observerDefault) {
  87183. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  87184. }
  87185. delete this._meshes[mesh.uniqueId];
  87186. }
  87187. this._shouldRender = false;
  87188. for (var meshHighlightToCheck in this._meshes) {
  87189. if (this._meshes[meshHighlightToCheck]) {
  87190. this._shouldRender = true;
  87191. break;
  87192. }
  87193. }
  87194. };
  87195. /**
  87196. * Force the stencil to the normal expected value for none glowing parts
  87197. */
  87198. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  87199. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  87200. };
  87201. /**
  87202. * Free any resources and references associated to a mesh.
  87203. * Internal use
  87204. * @param mesh The mesh to free.
  87205. */
  87206. HighlightLayer.prototype._disposeMesh = function (mesh) {
  87207. this.removeMesh(mesh);
  87208. this.removeExcludedMesh(mesh);
  87209. };
  87210. /**
  87211. * Dispose the highlight layer and free resources.
  87212. */
  87213. HighlightLayer.prototype.dispose = function () {
  87214. if (this._meshes) {
  87215. // Clean mesh references
  87216. for (var id in this._meshes) {
  87217. var meshHighlight = this._meshes[id];
  87218. if (meshHighlight && meshHighlight.mesh) {
  87219. if (meshHighlight.observerHighlight) {
  87220. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  87221. }
  87222. if (meshHighlight.observerDefault) {
  87223. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  87224. }
  87225. }
  87226. }
  87227. this._meshes = null;
  87228. }
  87229. if (this._excludedMeshes) {
  87230. for (var id in this._excludedMeshes) {
  87231. var meshHighlight = this._excludedMeshes[id];
  87232. if (meshHighlight) {
  87233. if (meshHighlight.beforeRender) {
  87234. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  87235. }
  87236. if (meshHighlight.afterRender) {
  87237. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  87238. }
  87239. }
  87240. }
  87241. this._excludedMeshes = null;
  87242. }
  87243. _super.prototype.dispose.call(this);
  87244. };
  87245. /**
  87246. * Effect Name of the highlight layer.
  87247. */
  87248. HighlightLayer.EffectName = "HighlightLayer";
  87249. /**
  87250. * The neutral color used during the preparation of the glow effect.
  87251. * This is black by default as the blend operation is a blend operation.
  87252. */
  87253. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  87254. /**
  87255. * Stencil value used for glowing meshes.
  87256. */
  87257. HighlightLayer.GlowingMeshStencilReference = 0x02;
  87258. /**
  87259. * Stencil value used for the other meshes in the scene.
  87260. */
  87261. HighlightLayer.NormalMeshStencilReference = 0x01;
  87262. return HighlightLayer;
  87263. }(BABYLON.EffectLayer));
  87264. BABYLON.HighlightLayer = HighlightLayer;
  87265. })(BABYLON || (BABYLON = {}));
  87266. //# sourceMappingURL=babylon.highlightLayer.js.map
  87267. "use strict";
  87268. var BABYLON;
  87269. (function (BABYLON) {
  87270. /**
  87271. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  87272. *
  87273. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  87274. * glowy meshes to your scene.
  87275. *
  87276. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  87277. */
  87278. var GlowLayer = /** @class */ (function (_super) {
  87279. __extends(GlowLayer, _super);
  87280. /**
  87281. * Instantiates a new glow Layer and references it to the scene.
  87282. * @param name The name of the layer
  87283. * @param scene The scene to use the layer in
  87284. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  87285. */
  87286. function GlowLayer(name, scene, options) {
  87287. var _this = _super.call(this, name, scene) || this;
  87288. _this.name = name;
  87289. _this._intensity = 1.0;
  87290. _this._includedOnlyMeshes = [];
  87291. _this._excludedMeshes = [];
  87292. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  87293. // Adapt options
  87294. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  87295. // Initialize the layer
  87296. _this._init({
  87297. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  87298. camera: _this._options.camera,
  87299. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  87300. mainTextureRatio: _this._options.mainTextureRatio
  87301. });
  87302. return _this;
  87303. }
  87304. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  87305. /**
  87306. * Gets the kernel size of the blur.
  87307. */
  87308. get: function () {
  87309. return this._horizontalBlurPostprocess1.kernel;
  87310. },
  87311. /**
  87312. * Sets the kernel size of the blur.
  87313. */
  87314. set: function (value) {
  87315. this._horizontalBlurPostprocess1.kernel = value;
  87316. this._verticalBlurPostprocess1.kernel = value;
  87317. this._horizontalBlurPostprocess2.kernel = value;
  87318. this._verticalBlurPostprocess2.kernel = value;
  87319. },
  87320. enumerable: true,
  87321. configurable: true
  87322. });
  87323. Object.defineProperty(GlowLayer.prototype, "intensity", {
  87324. /**
  87325. * Gets the glow intensity.
  87326. */
  87327. get: function () {
  87328. return this._intensity;
  87329. },
  87330. /**
  87331. * Sets the glow intensity.
  87332. */
  87333. set: function (value) {
  87334. this._intensity = value;
  87335. },
  87336. enumerable: true,
  87337. configurable: true
  87338. });
  87339. /**
  87340. * Get the effect name of the layer.
  87341. * @return The effect name
  87342. */
  87343. GlowLayer.prototype.getEffectName = function () {
  87344. return GlowLayer.EffectName;
  87345. };
  87346. /**
  87347. * Create the merge effect. This is the shader use to blit the information back
  87348. * to the main canvas at the end of the scene rendering.
  87349. */
  87350. GlowLayer.prototype._createMergeEffect = function () {
  87351. // Effect
  87352. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  87353. };
  87354. /**
  87355. * Creates the render target textures and post processes used in the glow layer.
  87356. */
  87357. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  87358. var _this = this;
  87359. var blurTextureWidth = this._mainTextureDesiredSize.width;
  87360. var blurTextureHeight = this._mainTextureDesiredSize.height;
  87361. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  87362. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  87363. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  87364. width: blurTextureWidth,
  87365. height: blurTextureHeight
  87366. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  87367. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87368. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87369. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  87370. this._blurTexture1.renderParticles = false;
  87371. this._blurTexture1.ignoreCameraViewport = true;
  87372. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  87373. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  87374. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  87375. width: blurTextureWidth2,
  87376. height: blurTextureHeight2
  87377. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  87378. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87379. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87380. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  87381. this._blurTexture2.renderParticles = false;
  87382. this._blurTexture2.ignoreCameraViewport = true;
  87383. this._textures = [this._blurTexture1, this._blurTexture2];
  87384. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  87385. width: blurTextureWidth,
  87386. height: blurTextureHeight
  87387. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  87388. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  87389. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  87390. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  87391. effect.setTexture("textureSampler", _this._mainTexture);
  87392. });
  87393. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  87394. width: blurTextureWidth,
  87395. height: blurTextureHeight
  87396. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  87397. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  87398. width: blurTextureWidth2,
  87399. height: blurTextureHeight2
  87400. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  87401. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  87402. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  87403. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  87404. effect.setTexture("textureSampler", _this._blurTexture1);
  87405. });
  87406. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  87407. width: blurTextureWidth2,
  87408. height: blurTextureHeight2
  87409. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  87410. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  87411. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  87412. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  87413. this._mainTexture.samples = this._options.mainTextureSamples;
  87414. this._mainTexture.onAfterUnbindObservable.add(function () {
  87415. var internalTexture = _this._blurTexture1.getInternalTexture();
  87416. if (internalTexture) {
  87417. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  87418. internalTexture = _this._blurTexture2.getInternalTexture();
  87419. if (internalTexture) {
  87420. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  87421. }
  87422. }
  87423. });
  87424. // Prevent autoClear.
  87425. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  87426. };
  87427. /**
  87428. * Checks for the readiness of the element composing the layer.
  87429. * @param subMesh the mesh to check for
  87430. * @param useInstances specify wether or not to use instances to render the mesh
  87431. * @param emissiveTexture the associated emissive texture used to generate the glow
  87432. * @return true if ready otherwise, false
  87433. */
  87434. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  87435. var material = subMesh.getMaterial();
  87436. var mesh = subMesh.getRenderingMesh();
  87437. if (!material || !mesh) {
  87438. return false;
  87439. }
  87440. var emissiveTexture = material.emissiveTexture;
  87441. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  87442. };
  87443. /**
  87444. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  87445. */
  87446. GlowLayer.prototype.needStencil = function () {
  87447. return false;
  87448. };
  87449. /**
  87450. * Implementation specific of rendering the generating effect on the main canvas.
  87451. * @param effect The effect used to render through
  87452. */
  87453. GlowLayer.prototype._internalRender = function (effect) {
  87454. // Texture
  87455. effect.setTexture("textureSampler", this._blurTexture1);
  87456. effect.setTexture("textureSampler2", this._blurTexture2);
  87457. effect.setFloat("offset", this._intensity);
  87458. // Cache
  87459. var engine = this._engine;
  87460. var previousStencilBuffer = engine.getStencilBuffer();
  87461. // Draw order
  87462. engine.setStencilBuffer(false);
  87463. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  87464. // Draw order
  87465. engine.setStencilBuffer(previousStencilBuffer);
  87466. };
  87467. /**
  87468. * Sets the required values for both the emissive texture and and the main color.
  87469. */
  87470. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  87471. var textureLevel = 1.0;
  87472. if (this.customEmissiveTextureSelector) {
  87473. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  87474. }
  87475. else {
  87476. if (material) {
  87477. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  87478. if (this._emissiveTextureAndColor.texture) {
  87479. textureLevel = this._emissiveTextureAndColor.texture.level;
  87480. }
  87481. }
  87482. else {
  87483. this._emissiveTextureAndColor.texture = null;
  87484. }
  87485. }
  87486. if (this.customEmissiveColorSelector) {
  87487. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  87488. }
  87489. else {
  87490. if (material.emissiveColor) {
  87491. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  87492. }
  87493. else {
  87494. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  87495. }
  87496. }
  87497. };
  87498. /**
  87499. * Returns true if the mesh should render, otherwise false.
  87500. * @param mesh The mesh to render
  87501. * @returns true if it should render otherwise false
  87502. */
  87503. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  87504. return this.hasMesh(mesh);
  87505. };
  87506. /**
  87507. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  87508. * @param mesh The mesh to exclude from the glow layer
  87509. */
  87510. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  87511. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  87512. this._excludedMeshes.push(mesh.uniqueId);
  87513. }
  87514. };
  87515. /**
  87516. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  87517. * @param mesh The mesh to remove
  87518. */
  87519. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  87520. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  87521. if (index !== -1) {
  87522. this._excludedMeshes.splice(index, 1);
  87523. }
  87524. };
  87525. /**
  87526. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  87527. * @param mesh The mesh to include in the glow layer
  87528. */
  87529. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  87530. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  87531. this._includedOnlyMeshes.push(mesh.uniqueId);
  87532. }
  87533. };
  87534. /**
  87535. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  87536. * @param mesh The mesh to remove
  87537. */
  87538. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  87539. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  87540. if (index !== -1) {
  87541. this._includedOnlyMeshes.splice(index, 1);
  87542. }
  87543. };
  87544. /**
  87545. * Determine if a given mesh will be used in the glow layer
  87546. * @param mesh The mesh to test
  87547. * @returns true if the mesh will be highlighted by the current glow layer
  87548. */
  87549. GlowLayer.prototype.hasMesh = function (mesh) {
  87550. // Included Mesh
  87551. if (this._includedOnlyMeshes.length) {
  87552. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  87553. }
  87554. ;
  87555. // Excluded Mesh
  87556. if (this._excludedMeshes.length) {
  87557. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  87558. }
  87559. ;
  87560. return true;
  87561. };
  87562. /**
  87563. * Free any resources and references associated to a mesh.
  87564. * Internal use
  87565. * @param mesh The mesh to free.
  87566. */
  87567. GlowLayer.prototype._disposeMesh = function (mesh) {
  87568. this.removeIncludedOnlyMesh(mesh);
  87569. this.removeExcludedMesh(mesh);
  87570. };
  87571. /**
  87572. * Effect Name of the layer.
  87573. */
  87574. GlowLayer.EffectName = "GlowLayer";
  87575. /**
  87576. * The default blur kernel size used for the glow.
  87577. */
  87578. GlowLayer.DefaultBlurKernelSize = 32;
  87579. /**
  87580. * The default texture size ratio used for the glow.
  87581. */
  87582. GlowLayer.DefaultTextureRatio = 0.5;
  87583. return GlowLayer;
  87584. }(BABYLON.EffectLayer));
  87585. BABYLON.GlowLayer = GlowLayer;
  87586. })(BABYLON || (BABYLON = {}));
  87587. //# sourceMappingURL=babylon.glowLayer.js.map
  87588. "use strict";
  87589. var BABYLON;
  87590. (function (BABYLON) {
  87591. /**
  87592. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  87593. */
  87594. var AssetTaskState;
  87595. (function (AssetTaskState) {
  87596. /**
  87597. * Initialization
  87598. */
  87599. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  87600. /**
  87601. * Running
  87602. */
  87603. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  87604. /**
  87605. * Done
  87606. */
  87607. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  87608. /**
  87609. * Error
  87610. */
  87611. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  87612. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  87613. /**
  87614. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  87615. */
  87616. var AbstractAssetTask = /** @class */ (function () {
  87617. /**
  87618. * Creates a new {BABYLON.AssetsManager}
  87619. * @param name defines the name of the task
  87620. */
  87621. function AbstractAssetTask(
  87622. /**
  87623. * Task name
  87624. */ name) {
  87625. this.name = name;
  87626. this._isCompleted = false;
  87627. this._taskState = AssetTaskState.INIT;
  87628. }
  87629. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  87630. /**
  87631. * Get if the task is completed
  87632. */
  87633. get: function () {
  87634. return this._isCompleted;
  87635. },
  87636. enumerable: true,
  87637. configurable: true
  87638. });
  87639. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  87640. /**
  87641. * Gets the current state of the task
  87642. */
  87643. get: function () {
  87644. return this._taskState;
  87645. },
  87646. enumerable: true,
  87647. configurable: true
  87648. });
  87649. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  87650. /**
  87651. * Gets the current error object (if task is in error)
  87652. */
  87653. get: function () {
  87654. return this._errorObject;
  87655. },
  87656. enumerable: true,
  87657. configurable: true
  87658. });
  87659. /**
  87660. * Internal only
  87661. * @ignore
  87662. */
  87663. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  87664. if (this._errorObject) {
  87665. return;
  87666. }
  87667. this._errorObject = {
  87668. message: message,
  87669. exception: exception
  87670. };
  87671. };
  87672. /**
  87673. * Execute the current task
  87674. * @param scene defines the scene where you want your assets to be loaded
  87675. * @param onSuccess is a callback called when the task is successfully executed
  87676. * @param onError is a callback called if an error occurs
  87677. */
  87678. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  87679. var _this = this;
  87680. this._taskState = AssetTaskState.RUNNING;
  87681. this.runTask(scene, function () {
  87682. _this.onDoneCallback(onSuccess, onError);
  87683. }, function (msg, exception) {
  87684. _this.onErrorCallback(onError, msg, exception);
  87685. });
  87686. };
  87687. /**
  87688. * Execute the current task
  87689. * @param scene defines the scene where you want your assets to be loaded
  87690. * @param onSuccess is a callback called when the task is successfully executed
  87691. * @param onError is a callback called if an error occurs
  87692. */
  87693. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  87694. throw new Error("runTask is not implemented");
  87695. };
  87696. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  87697. this._taskState = AssetTaskState.ERROR;
  87698. this._errorObject = {
  87699. message: message,
  87700. exception: exception
  87701. };
  87702. if (this.onError) {
  87703. this.onError(this, message, exception);
  87704. }
  87705. onError();
  87706. };
  87707. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  87708. try {
  87709. this._taskState = AssetTaskState.DONE;
  87710. this._isCompleted = true;
  87711. if (this.onSuccess) {
  87712. this.onSuccess(this);
  87713. }
  87714. onSuccess();
  87715. }
  87716. catch (e) {
  87717. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  87718. }
  87719. };
  87720. return AbstractAssetTask;
  87721. }());
  87722. BABYLON.AbstractAssetTask = AbstractAssetTask;
  87723. /**
  87724. * Class used to share progress information about assets loading
  87725. */
  87726. var AssetsProgressEvent = /** @class */ (function () {
  87727. /**
  87728. * Creates a {BABYLON.AssetsProgressEvent}
  87729. * @param remainingCount defines the number of remaining tasks to process
  87730. * @param totalCount defines the total number of tasks
  87731. * @param task defines the task that was just processed
  87732. */
  87733. function AssetsProgressEvent(remainingCount, totalCount, task) {
  87734. this.remainingCount = remainingCount;
  87735. this.totalCount = totalCount;
  87736. this.task = task;
  87737. }
  87738. return AssetsProgressEvent;
  87739. }());
  87740. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  87741. /**
  87742. * Define a task used by {BABYLON.AssetsManager} to load meshes
  87743. */
  87744. var MeshAssetTask = /** @class */ (function (_super) {
  87745. __extends(MeshAssetTask, _super);
  87746. /**
  87747. * Creates a new {BABYLON.MeshAssetTask}
  87748. * @param name defines the name of the task
  87749. * @param meshesNames defines the list of mesh's names you want to load
  87750. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  87751. * @param sceneFilename defines the filename of the scene to load from
  87752. */
  87753. function MeshAssetTask(
  87754. /**
  87755. * Defines the name of the task
  87756. */
  87757. name,
  87758. /**
  87759. * Defines the list of mesh's names you want to load
  87760. */
  87761. meshesNames,
  87762. /**
  87763. * Defines the root url to use as a base to load your meshes and associated resources
  87764. */
  87765. rootUrl,
  87766. /**
  87767. * Defines the filename of the scene to load from
  87768. */
  87769. sceneFilename) {
  87770. var _this = _super.call(this, name) || this;
  87771. _this.name = name;
  87772. _this.meshesNames = meshesNames;
  87773. _this.rootUrl = rootUrl;
  87774. _this.sceneFilename = sceneFilename;
  87775. return _this;
  87776. }
  87777. /**
  87778. * Execute the current task
  87779. * @param scene defines the scene where you want your assets to be loaded
  87780. * @param onSuccess is a callback called when the task is successfully executed
  87781. * @param onError is a callback called if an error occurs
  87782. */
  87783. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  87784. var _this = this;
  87785. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  87786. _this.loadedMeshes = meshes;
  87787. _this.loadedParticleSystems = particleSystems;
  87788. _this.loadedSkeletons = skeletons;
  87789. onSuccess();
  87790. }, null, function (scene, message, exception) {
  87791. onError(message, exception);
  87792. });
  87793. };
  87794. return MeshAssetTask;
  87795. }(AbstractAssetTask));
  87796. BABYLON.MeshAssetTask = MeshAssetTask;
  87797. /**
  87798. * Define a task used by {BABYLON.AssetsManager} to load text content
  87799. */
  87800. var TextFileAssetTask = /** @class */ (function (_super) {
  87801. __extends(TextFileAssetTask, _super);
  87802. /**
  87803. * Creates a new TextFileAssetTask object
  87804. * @param name defines the name of the task
  87805. * @param url defines the location of the file to load
  87806. */
  87807. function TextFileAssetTask(
  87808. /**
  87809. * Defines the name of the task
  87810. */
  87811. name,
  87812. /**
  87813. * Defines the location of the file to load
  87814. */
  87815. url) {
  87816. var _this = _super.call(this, name) || this;
  87817. _this.name = name;
  87818. _this.url = url;
  87819. return _this;
  87820. }
  87821. /**
  87822. * Execute the current task
  87823. * @param scene defines the scene where you want your assets to be loaded
  87824. * @param onSuccess is a callback called when the task is successfully executed
  87825. * @param onError is a callback called if an error occurs
  87826. */
  87827. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  87828. var _this = this;
  87829. scene._loadFile(this.url, function (data) {
  87830. _this.text = data;
  87831. onSuccess();
  87832. }, undefined, false, false, function (request, exception) {
  87833. if (request) {
  87834. onError(request.status + " " + request.statusText, exception);
  87835. }
  87836. });
  87837. };
  87838. return TextFileAssetTask;
  87839. }(AbstractAssetTask));
  87840. BABYLON.TextFileAssetTask = TextFileAssetTask;
  87841. /**
  87842. * Define a task used by {BABYLON.AssetsManager} to load binary data
  87843. */
  87844. var BinaryFileAssetTask = /** @class */ (function (_super) {
  87845. __extends(BinaryFileAssetTask, _super);
  87846. /**
  87847. * Creates a new BinaryFileAssetTask object
  87848. * @param name defines the name of the new task
  87849. * @param url defines the location of the file to load
  87850. */
  87851. function BinaryFileAssetTask(
  87852. /**
  87853. * Defines the name of the task
  87854. */
  87855. name,
  87856. /**
  87857. * Defines the location of the file to load
  87858. */
  87859. url) {
  87860. var _this = _super.call(this, name) || this;
  87861. _this.name = name;
  87862. _this.url = url;
  87863. return _this;
  87864. }
  87865. /**
  87866. * Execute the current task
  87867. * @param scene defines the scene where you want your assets to be loaded
  87868. * @param onSuccess is a callback called when the task is successfully executed
  87869. * @param onError is a callback called if an error occurs
  87870. */
  87871. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  87872. var _this = this;
  87873. scene._loadFile(this.url, function (data) {
  87874. _this.data = data;
  87875. onSuccess();
  87876. }, undefined, true, true, function (request, exception) {
  87877. if (request) {
  87878. onError(request.status + " " + request.statusText, exception);
  87879. }
  87880. });
  87881. };
  87882. return BinaryFileAssetTask;
  87883. }(AbstractAssetTask));
  87884. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  87885. /**
  87886. * Define a task used by {BABYLON.AssetsManager} to load images
  87887. */
  87888. var ImageAssetTask = /** @class */ (function (_super) {
  87889. __extends(ImageAssetTask, _super);
  87890. /**
  87891. * Creates a new ImageAssetTask
  87892. * @param name defines the name of the task
  87893. * @param url defines the location of the image to load
  87894. */
  87895. function ImageAssetTask(
  87896. /**
  87897. * Defines the name of the task
  87898. */
  87899. name,
  87900. /**
  87901. * Defines the location of the image to load
  87902. */
  87903. url) {
  87904. var _this = _super.call(this, name) || this;
  87905. _this.name = name;
  87906. _this.url = url;
  87907. return _this;
  87908. }
  87909. /**
  87910. * Execute the current task
  87911. * @param scene defines the scene where you want your assets to be loaded
  87912. * @param onSuccess is a callback called when the task is successfully executed
  87913. * @param onError is a callback called if an error occurs
  87914. */
  87915. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  87916. var _this = this;
  87917. var img = new Image();
  87918. BABYLON.Tools.SetCorsBehavior(this.url, img);
  87919. img.onload = function () {
  87920. _this.image = img;
  87921. onSuccess();
  87922. };
  87923. img.onerror = function (err) {
  87924. onError("Error loading image", err);
  87925. };
  87926. img.src = this.url;
  87927. };
  87928. return ImageAssetTask;
  87929. }(AbstractAssetTask));
  87930. BABYLON.ImageAssetTask = ImageAssetTask;
  87931. /**
  87932. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  87933. */
  87934. var TextureAssetTask = /** @class */ (function (_super) {
  87935. __extends(TextureAssetTask, _super);
  87936. /**
  87937. * Creates a new TextureAssetTask object
  87938. * @param name defines the name of the task
  87939. * @param url defines the location of the file to load
  87940. * @param noMipmap defines if mipmap should not be generated (default is false)
  87941. * @param invertY defines if texture must be inverted on Y axis (default is false)
  87942. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  87943. */
  87944. function TextureAssetTask(
  87945. /**
  87946. * Defines the name of the task
  87947. */
  87948. name,
  87949. /**
  87950. * Defines the location of the file to load
  87951. */
  87952. url,
  87953. /**
  87954. * Defines if mipmap should not be generated (default is false)
  87955. */
  87956. noMipmap,
  87957. /**
  87958. * Defines if texture must be inverted on Y axis (default is false)
  87959. */
  87960. invertY,
  87961. /**
  87962. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  87963. */
  87964. samplingMode) {
  87965. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  87966. var _this = _super.call(this, name) || this;
  87967. _this.name = name;
  87968. _this.url = url;
  87969. _this.noMipmap = noMipmap;
  87970. _this.invertY = invertY;
  87971. _this.samplingMode = samplingMode;
  87972. return _this;
  87973. }
  87974. /**
  87975. * Execute the current task
  87976. * @param scene defines the scene where you want your assets to be loaded
  87977. * @param onSuccess is a callback called when the task is successfully executed
  87978. * @param onError is a callback called if an error occurs
  87979. */
  87980. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  87981. var onload = function () {
  87982. onSuccess();
  87983. };
  87984. var onerror = function (message, exception) {
  87985. onError(message, exception);
  87986. };
  87987. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  87988. };
  87989. return TextureAssetTask;
  87990. }(AbstractAssetTask));
  87991. BABYLON.TextureAssetTask = TextureAssetTask;
  87992. /**
  87993. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  87994. */
  87995. var CubeTextureAssetTask = /** @class */ (function (_super) {
  87996. __extends(CubeTextureAssetTask, _super);
  87997. /**
  87998. * Creates a new CubeTextureAssetTask
  87999. * @param name defines the name of the task
  88000. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  88001. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  88002. * @param noMipmap defines if mipmaps should not be generated (default is false)
  88003. * @param files defines the explicit list of files (undefined by default)
  88004. */
  88005. function CubeTextureAssetTask(
  88006. /**
  88007. * Defines the name of the task
  88008. */
  88009. name,
  88010. /**
  88011. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  88012. */
  88013. url,
  88014. /**
  88015. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  88016. */
  88017. extensions,
  88018. /**
  88019. * Defines if mipmaps should not be generated (default is false)
  88020. */
  88021. noMipmap,
  88022. /**
  88023. * Defines the explicit list of files (undefined by default)
  88024. */
  88025. files) {
  88026. var _this = _super.call(this, name) || this;
  88027. _this.name = name;
  88028. _this.url = url;
  88029. _this.extensions = extensions;
  88030. _this.noMipmap = noMipmap;
  88031. _this.files = files;
  88032. return _this;
  88033. }
  88034. /**
  88035. * Execute the current task
  88036. * @param scene defines the scene where you want your assets to be loaded
  88037. * @param onSuccess is a callback called when the task is successfully executed
  88038. * @param onError is a callback called if an error occurs
  88039. */
  88040. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  88041. var onload = function () {
  88042. onSuccess();
  88043. };
  88044. var onerror = function (message, exception) {
  88045. onError(message, exception);
  88046. };
  88047. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  88048. };
  88049. return CubeTextureAssetTask;
  88050. }(AbstractAssetTask));
  88051. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  88052. /**
  88053. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  88054. */
  88055. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  88056. __extends(HDRCubeTextureAssetTask, _super);
  88057. /**
  88058. * Creates a new HDRCubeTextureAssetTask object
  88059. * @param name defines the name of the task
  88060. * @param url defines the location of the file to load
  88061. * @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.
  88062. * @param noMipmap defines if mipmaps should not be generated (default is false)
  88063. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  88064. * @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)
  88065. * @param usePMREMGenerator specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  88066. */
  88067. function HDRCubeTextureAssetTask(
  88068. /**
  88069. * Defines the name of the task
  88070. */
  88071. name,
  88072. /**
  88073. * Defines the location of the file to load
  88074. */
  88075. url,
  88076. /**
  88077. * 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.
  88078. */
  88079. size,
  88080. /**
  88081. * Defines if mipmaps should not be generated (default is false)
  88082. */
  88083. noMipmap,
  88084. /**
  88085. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  88086. */
  88087. generateHarmonics,
  88088. /**
  88089. * 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)
  88090. */
  88091. useInGammaSpace,
  88092. /**
  88093. * Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  88094. */
  88095. usePMREMGenerator) {
  88096. if (noMipmap === void 0) { noMipmap = false; }
  88097. if (generateHarmonics === void 0) { generateHarmonics = true; }
  88098. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  88099. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  88100. var _this = _super.call(this, name) || this;
  88101. _this.name = name;
  88102. _this.url = url;
  88103. _this.size = size;
  88104. _this.noMipmap = noMipmap;
  88105. _this.generateHarmonics = generateHarmonics;
  88106. _this.useInGammaSpace = useInGammaSpace;
  88107. _this.usePMREMGenerator = usePMREMGenerator;
  88108. return _this;
  88109. }
  88110. /**
  88111. * Execute the current task
  88112. * @param scene defines the scene where you want your assets to be loaded
  88113. * @param onSuccess is a callback called when the task is successfully executed
  88114. * @param onError is a callback called if an error occurs
  88115. */
  88116. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  88117. var onload = function () {
  88118. onSuccess();
  88119. };
  88120. var onerror = function (message, exception) {
  88121. onError(message, exception);
  88122. };
  88123. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  88124. };
  88125. return HDRCubeTextureAssetTask;
  88126. }(AbstractAssetTask));
  88127. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  88128. /**
  88129. * This class can be used to easily import assets into a scene
  88130. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  88131. */
  88132. var AssetsManager = /** @class */ (function () {
  88133. /**
  88134. * Creates a new AssetsManager
  88135. * @param scene defines the scene to work on
  88136. */
  88137. function AssetsManager(scene) {
  88138. this._isLoading = false;
  88139. this._tasks = new Array();
  88140. this._waitingTasksCount = 0;
  88141. this._totalTasksCount = 0;
  88142. /**
  88143. * Observable called when all tasks are processed
  88144. */
  88145. this.onTaskSuccessObservable = new BABYLON.Observable();
  88146. /**
  88147. * Observable called when a task had an error
  88148. */
  88149. this.onTaskErrorObservable = new BABYLON.Observable();
  88150. /**
  88151. * Observable called when a task is successful
  88152. */
  88153. this.onTasksDoneObservable = new BABYLON.Observable();
  88154. /**
  88155. * Observable called when a task is done (whatever the result is)
  88156. */
  88157. this.onProgressObservable = new BABYLON.Observable();
  88158. /**
  88159. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  88160. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  88161. */
  88162. this.useDefaultLoadingScreen = true;
  88163. this._scene = scene;
  88164. }
  88165. /**
  88166. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  88167. * @param taskName defines the name of the new task
  88168. * @param meshesNames defines the name of meshes to load
  88169. * @param rootUrl defines the root url to use to locate files
  88170. * @param sceneFilename defines the filename of the scene file
  88171. * @returns a new {BABYLON.MeshAssetTask} object
  88172. */
  88173. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  88174. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  88175. this._tasks.push(task);
  88176. return task;
  88177. };
  88178. /**
  88179. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  88180. * @param taskName defines the name of the new task
  88181. * @param url defines the url of the file to load
  88182. * @returns a new {BABYLON.TextFileAssetTask} object
  88183. */
  88184. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  88185. var task = new TextFileAssetTask(taskName, url);
  88186. this._tasks.push(task);
  88187. return task;
  88188. };
  88189. /**
  88190. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  88191. * @param taskName defines the name of the new task
  88192. * @param url defines the url of the file to load
  88193. * @returns a new {BABYLON.BinaryFileAssetTask} object
  88194. */
  88195. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  88196. var task = new BinaryFileAssetTask(taskName, url);
  88197. this._tasks.push(task);
  88198. return task;
  88199. };
  88200. /**
  88201. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  88202. * @param taskName defines the name of the new task
  88203. * @param url defines the url of the file to load
  88204. * @returns a new {BABYLON.ImageAssetTask} object
  88205. */
  88206. AssetsManager.prototype.addImageTask = function (taskName, url) {
  88207. var task = new ImageAssetTask(taskName, url);
  88208. this._tasks.push(task);
  88209. return task;
  88210. };
  88211. /**
  88212. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  88213. * @param taskName defines the name of the new task
  88214. * @param url defines the url of the file to load
  88215. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  88216. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  88217. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  88218. * @returns a new {BABYLON.TextureAssetTask} object
  88219. */
  88220. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  88221. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  88222. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  88223. this._tasks.push(task);
  88224. return task;
  88225. };
  88226. /**
  88227. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  88228. * @param taskName defines the name of the new task
  88229. * @param url defines the url of the file to load
  88230. * @param extensions defines the extension to use to load the cube map (can be null)
  88231. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  88232. * @param files defines the list of files to load (can be null)
  88233. * @returns a new {BABYLON.CubeTextureAssetTask} object
  88234. */
  88235. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  88236. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  88237. this._tasks.push(task);
  88238. return task;
  88239. };
  88240. /**
  88241. *
  88242. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  88243. * @param taskName defines the name of the new task
  88244. * @param url defines the url of the file to load
  88245. * @param size defines the size you want for the cubemap (can be null)
  88246. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  88247. * @param generateHarmonics defines if you want to automatically generate (true by default)
  88248. * @param useInGammaSpace defines if the texture must be considered in gamma space (false by default)
  88249. * @param usePMREMGenerator is a reserved parameter and must be set to false or ignored
  88250. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  88251. */
  88252. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  88253. if (noMipmap === void 0) { noMipmap = false; }
  88254. if (generateHarmonics === void 0) { generateHarmonics = true; }
  88255. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  88256. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  88257. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  88258. this._tasks.push(task);
  88259. return task;
  88260. };
  88261. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  88262. var _this = this;
  88263. this._waitingTasksCount--;
  88264. try {
  88265. if (task.taskState === AssetTaskState.DONE) {
  88266. // Let's remove successfull tasks
  88267. BABYLON.Tools.SetImmediate(function () {
  88268. var index = _this._tasks.indexOf(task);
  88269. if (index > -1) {
  88270. _this._tasks.splice(index, 1);
  88271. }
  88272. });
  88273. }
  88274. if (this.onProgress) {
  88275. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  88276. }
  88277. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  88278. }
  88279. catch (e) {
  88280. BABYLON.Tools.Error("Error running progress callbacks.");
  88281. console.log(e);
  88282. }
  88283. if (this._waitingTasksCount === 0) {
  88284. try {
  88285. if (this.onFinish) {
  88286. this.onFinish(this._tasks);
  88287. }
  88288. this.onTasksDoneObservable.notifyObservers(this._tasks);
  88289. }
  88290. catch (e) {
  88291. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  88292. console.log(e);
  88293. }
  88294. this._isLoading = false;
  88295. this._scene.getEngine().hideLoadingUI();
  88296. }
  88297. };
  88298. AssetsManager.prototype._runTask = function (task) {
  88299. var _this = this;
  88300. var done = function () {
  88301. try {
  88302. if (_this.onTaskSuccess) {
  88303. _this.onTaskSuccess(task);
  88304. }
  88305. _this.onTaskSuccessObservable.notifyObservers(task);
  88306. _this._decreaseWaitingTasksCount(task);
  88307. }
  88308. catch (e) {
  88309. error("Error executing task success callbacks", e);
  88310. }
  88311. };
  88312. var error = function (message, exception) {
  88313. task._setErrorObject(message, exception);
  88314. if (_this.onTaskError) {
  88315. _this.onTaskError(task);
  88316. }
  88317. _this.onTaskErrorObservable.notifyObservers(task);
  88318. _this._decreaseWaitingTasksCount(task);
  88319. };
  88320. task.run(this._scene, done, error);
  88321. };
  88322. /**
  88323. * Reset the {BABYLON.AssetsManager} and remove all tasks
  88324. * @return the current instance of the {BABYLON.AssetsManager}
  88325. */
  88326. AssetsManager.prototype.reset = function () {
  88327. this._isLoading = false;
  88328. this._tasks = new Array();
  88329. return this;
  88330. };
  88331. /**
  88332. * Start the loading process
  88333. * @return the current instance of the {BABYLON.AssetsManager}
  88334. */
  88335. AssetsManager.prototype.load = function () {
  88336. if (this._isLoading) {
  88337. return this;
  88338. }
  88339. this._isLoading = true;
  88340. this._waitingTasksCount = this._tasks.length;
  88341. this._totalTasksCount = this._tasks.length;
  88342. if (this._waitingTasksCount === 0) {
  88343. this._isLoading = false;
  88344. if (this.onFinish) {
  88345. this.onFinish(this._tasks);
  88346. }
  88347. this.onTasksDoneObservable.notifyObservers(this._tasks);
  88348. return this;
  88349. }
  88350. if (this.useDefaultLoadingScreen) {
  88351. this._scene.getEngine().displayLoadingUI();
  88352. }
  88353. for (var index = 0; index < this._tasks.length; index++) {
  88354. var task = this._tasks[index];
  88355. this._runTask(task);
  88356. }
  88357. return this;
  88358. };
  88359. return AssetsManager;
  88360. }());
  88361. BABYLON.AssetsManager = AssetsManager;
  88362. })(BABYLON || (BABYLON = {}));
  88363. //# sourceMappingURL=babylon.assetsManager.js.map
  88364. "use strict";
  88365. var BABYLON;
  88366. (function (BABYLON) {
  88367. var serializedGeometries = [];
  88368. var serializeGeometry = function (geometry, serializationGeometries) {
  88369. if (serializedGeometries[geometry.id]) {
  88370. return;
  88371. }
  88372. if (geometry.doNotSerialize) {
  88373. return;
  88374. }
  88375. if (geometry instanceof BABYLON.BoxGeometry) {
  88376. serializationGeometries.boxes.push(geometry.serialize());
  88377. }
  88378. else if (geometry instanceof BABYLON.SphereGeometry) {
  88379. serializationGeometries.spheres.push(geometry.serialize());
  88380. }
  88381. else if (geometry instanceof BABYLON.CylinderGeometry) {
  88382. serializationGeometries.cylinders.push(geometry.serialize());
  88383. }
  88384. else if (geometry instanceof BABYLON.TorusGeometry) {
  88385. serializationGeometries.toruses.push(geometry.serialize());
  88386. }
  88387. else if (geometry instanceof BABYLON.GroundGeometry) {
  88388. serializationGeometries.grounds.push(geometry.serialize());
  88389. }
  88390. else if (geometry instanceof BABYLON.Plane) {
  88391. serializationGeometries.planes.push(geometry.serialize());
  88392. }
  88393. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  88394. serializationGeometries.torusKnots.push(geometry.serialize());
  88395. }
  88396. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  88397. throw new Error("Unknown primitive type");
  88398. }
  88399. else {
  88400. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  88401. }
  88402. serializedGeometries[geometry.id] = true;
  88403. };
  88404. var serializeMesh = function (mesh, serializationScene) {
  88405. var serializationObject = {};
  88406. // Geometry
  88407. var geometry = mesh._geometry;
  88408. if (geometry) {
  88409. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  88410. // 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
  88411. serializeGeometry(geometry, serializationScene.geometries);
  88412. }
  88413. }
  88414. // Custom
  88415. if (mesh.serialize) {
  88416. mesh.serialize(serializationObject);
  88417. }
  88418. return serializationObject;
  88419. };
  88420. var finalizeSingleMesh = function (mesh, serializationObject) {
  88421. //only works if the mesh is already loaded
  88422. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  88423. //serialize material
  88424. if (mesh.material) {
  88425. if (mesh.material instanceof BABYLON.StandardMaterial) {
  88426. serializationObject.materials = serializationObject.materials || [];
  88427. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  88428. serializationObject.materials.push(mesh.material.serialize());
  88429. }
  88430. }
  88431. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  88432. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  88433. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  88434. serializationObject.multiMaterials.push(mesh.material.serialize());
  88435. }
  88436. }
  88437. }
  88438. //serialize geometry
  88439. var geometry = mesh._geometry;
  88440. if (geometry) {
  88441. if (!serializationObject.geometries) {
  88442. serializationObject.geometries = {};
  88443. serializationObject.geometries.boxes = [];
  88444. serializationObject.geometries.spheres = [];
  88445. serializationObject.geometries.cylinders = [];
  88446. serializationObject.geometries.toruses = [];
  88447. serializationObject.geometries.grounds = [];
  88448. serializationObject.geometries.planes = [];
  88449. serializationObject.geometries.torusKnots = [];
  88450. serializationObject.geometries.vertexData = [];
  88451. }
  88452. serializeGeometry(geometry, serializationObject.geometries);
  88453. }
  88454. // Skeletons
  88455. if (mesh.skeleton) {
  88456. serializationObject.skeletons = serializationObject.skeletons || [];
  88457. serializationObject.skeletons.push(mesh.skeleton.serialize());
  88458. }
  88459. //serialize the actual mesh
  88460. serializationObject.meshes = serializationObject.meshes || [];
  88461. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  88462. }
  88463. };
  88464. var SceneSerializer = /** @class */ (function () {
  88465. function SceneSerializer() {
  88466. }
  88467. SceneSerializer.ClearCache = function () {
  88468. serializedGeometries = [];
  88469. };
  88470. SceneSerializer.Serialize = function (scene) {
  88471. var serializationObject = {};
  88472. SceneSerializer.ClearCache();
  88473. // Scene
  88474. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  88475. serializationObject.autoClear = scene.autoClear;
  88476. serializationObject.clearColor = scene.clearColor.asArray();
  88477. serializationObject.ambientColor = scene.ambientColor.asArray();
  88478. serializationObject.gravity = scene.gravity.asArray();
  88479. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  88480. serializationObject.workerCollisions = scene.workerCollisions;
  88481. // Fog
  88482. if (scene.fogMode && scene.fogMode !== 0) {
  88483. serializationObject.fogMode = scene.fogMode;
  88484. serializationObject.fogColor = scene.fogColor.asArray();
  88485. serializationObject.fogStart = scene.fogStart;
  88486. serializationObject.fogEnd = scene.fogEnd;
  88487. serializationObject.fogDensity = scene.fogDensity;
  88488. }
  88489. //Physics
  88490. if (scene.isPhysicsEnabled()) {
  88491. var physicEngine = scene.getPhysicsEngine();
  88492. if (physicEngine) {
  88493. serializationObject.physicsEnabled = true;
  88494. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  88495. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  88496. }
  88497. }
  88498. // Metadata
  88499. if (scene.metadata) {
  88500. serializationObject.metadata = scene.metadata;
  88501. }
  88502. // Morph targets
  88503. serializationObject.morphTargetManagers = [];
  88504. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  88505. var abstractMesh = _a[_i];
  88506. var manager = abstractMesh.morphTargetManager;
  88507. if (manager) {
  88508. serializationObject.morphTargetManagers.push(manager.serialize());
  88509. }
  88510. }
  88511. // Lights
  88512. serializationObject.lights = [];
  88513. var index;
  88514. var light;
  88515. for (index = 0; index < scene.lights.length; index++) {
  88516. light = scene.lights[index];
  88517. if (!light.doNotSerialize) {
  88518. serializationObject.lights.push(light.serialize());
  88519. }
  88520. }
  88521. // Cameras
  88522. serializationObject.cameras = [];
  88523. for (index = 0; index < scene.cameras.length; index++) {
  88524. var camera = scene.cameras[index];
  88525. if (!camera.doNotSerialize) {
  88526. serializationObject.cameras.push(camera.serialize());
  88527. }
  88528. }
  88529. if (scene.activeCamera) {
  88530. serializationObject.activeCameraID = scene.activeCamera.id;
  88531. }
  88532. // Animations
  88533. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  88534. // Materials
  88535. serializationObject.materials = [];
  88536. serializationObject.multiMaterials = [];
  88537. var material;
  88538. for (index = 0; index < scene.materials.length; index++) {
  88539. material = scene.materials[index];
  88540. if (!material.doNotSerialize) {
  88541. serializationObject.materials.push(material.serialize());
  88542. }
  88543. }
  88544. // MultiMaterials
  88545. serializationObject.multiMaterials = [];
  88546. for (index = 0; index < scene.multiMaterials.length; index++) {
  88547. var multiMaterial = scene.multiMaterials[index];
  88548. serializationObject.multiMaterials.push(multiMaterial.serialize());
  88549. }
  88550. // Environment texture
  88551. if (scene.environmentTexture) {
  88552. serializationObject.environmentTexture = scene.environmentTexture.name;
  88553. }
  88554. // Skeletons
  88555. serializationObject.skeletons = [];
  88556. for (index = 0; index < scene.skeletons.length; index++) {
  88557. var skeleton = scene.skeletons[index];
  88558. if (!skeleton.doNotSerialize) {
  88559. serializationObject.skeletons.push(skeleton.serialize());
  88560. }
  88561. }
  88562. // Transform nodes
  88563. serializationObject.transformNodes = [];
  88564. for (index = 0; index < scene.transformNodes.length; index++) {
  88565. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  88566. }
  88567. // Geometries
  88568. serializationObject.geometries = {};
  88569. serializationObject.geometries.boxes = [];
  88570. serializationObject.geometries.spheres = [];
  88571. serializationObject.geometries.cylinders = [];
  88572. serializationObject.geometries.toruses = [];
  88573. serializationObject.geometries.grounds = [];
  88574. serializationObject.geometries.planes = [];
  88575. serializationObject.geometries.torusKnots = [];
  88576. serializationObject.geometries.vertexData = [];
  88577. serializedGeometries = [];
  88578. var geometries = scene.getGeometries();
  88579. for (index = 0; index < geometries.length; index++) {
  88580. var geometry = geometries[index];
  88581. if (geometry.isReady()) {
  88582. serializeGeometry(geometry, serializationObject.geometries);
  88583. }
  88584. }
  88585. // Meshes
  88586. serializationObject.meshes = [];
  88587. for (index = 0; index < scene.meshes.length; index++) {
  88588. var abstractMesh = scene.meshes[index];
  88589. if (abstractMesh instanceof BABYLON.Mesh) {
  88590. var mesh = abstractMesh;
  88591. if (!mesh.doNotSerialize) {
  88592. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  88593. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  88594. }
  88595. }
  88596. }
  88597. }
  88598. // Particles Systems
  88599. serializationObject.particleSystems = [];
  88600. for (index = 0; index < scene.particleSystems.length; index++) {
  88601. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  88602. }
  88603. // Lens flares
  88604. serializationObject.lensFlareSystems = [];
  88605. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  88606. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  88607. }
  88608. // Shadows
  88609. serializationObject.shadowGenerators = [];
  88610. for (index = 0; index < scene.lights.length; index++) {
  88611. light = scene.lights[index];
  88612. var shadowGenerator = light.getShadowGenerator();
  88613. if (shadowGenerator) {
  88614. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  88615. }
  88616. }
  88617. // Action Manager
  88618. if (scene.actionManager) {
  88619. serializationObject.actions = scene.actionManager.serialize("scene");
  88620. }
  88621. // Audio
  88622. serializationObject.sounds = [];
  88623. for (index = 0; index < scene.soundTracks.length; index++) {
  88624. var soundtrack = scene.soundTracks[index];
  88625. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  88626. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  88627. }
  88628. }
  88629. return serializationObject;
  88630. };
  88631. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  88632. if (withParents === void 0) { withParents = false; }
  88633. if (withChildren === void 0) { withChildren = false; }
  88634. var serializationObject = {};
  88635. SceneSerializer.ClearCache();
  88636. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  88637. if (withParents || withChildren) {
  88638. //deliberate for loop! not for each, appended should be processed as well.
  88639. for (var i = 0; i < toSerialize.length; ++i) {
  88640. if (withChildren) {
  88641. toSerialize[i].getDescendants().forEach(function (node) {
  88642. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  88643. toSerialize.push(node);
  88644. }
  88645. });
  88646. }
  88647. //make sure the array doesn't contain the object already
  88648. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  88649. toSerialize.push(toSerialize[i].parent);
  88650. }
  88651. }
  88652. }
  88653. toSerialize.forEach(function (mesh) {
  88654. finalizeSingleMesh(mesh, serializationObject);
  88655. });
  88656. return serializationObject;
  88657. };
  88658. return SceneSerializer;
  88659. }());
  88660. BABYLON.SceneSerializer = SceneSerializer;
  88661. })(BABYLON || (BABYLON = {}));
  88662. //# sourceMappingURL=babylon.sceneSerializer.js.map
  88663. "use strict";
  88664. var BABYLON;
  88665. (function (BABYLON) {
  88666. var ReflectionProbe = /** @class */ (function () {
  88667. function ReflectionProbe(name, size, scene, generateMipMaps) {
  88668. if (generateMipMaps === void 0) { generateMipMaps = true; }
  88669. var _this = this;
  88670. this.name = name;
  88671. this._viewMatrix = BABYLON.Matrix.Identity();
  88672. this._target = BABYLON.Vector3.Zero();
  88673. this._add = BABYLON.Vector3.Zero();
  88674. this._invertYAxis = false;
  88675. this.position = BABYLON.Vector3.Zero();
  88676. this._scene = scene;
  88677. this._scene.reflectionProbes.push(this);
  88678. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  88679. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  88680. switch (faceIndex) {
  88681. case 0:
  88682. _this._add.copyFromFloats(1, 0, 0);
  88683. break;
  88684. case 1:
  88685. _this._add.copyFromFloats(-1, 0, 0);
  88686. break;
  88687. case 2:
  88688. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  88689. break;
  88690. case 3:
  88691. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  88692. break;
  88693. case 4:
  88694. _this._add.copyFromFloats(0, 0, 1);
  88695. break;
  88696. case 5:
  88697. _this._add.copyFromFloats(0, 0, -1);
  88698. break;
  88699. }
  88700. if (_this._attachedMesh) {
  88701. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  88702. }
  88703. _this.position.addToRef(_this._add, _this._target);
  88704. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  88705. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  88706. scene._forcedViewPosition = _this.position;
  88707. });
  88708. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  88709. scene._forcedViewPosition = null;
  88710. scene.updateTransformMatrix(true);
  88711. });
  88712. if (scene.activeCamera) {
  88713. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  88714. }
  88715. }
  88716. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  88717. get: function () {
  88718. return this._renderTargetTexture.samples;
  88719. },
  88720. set: function (value) {
  88721. this._renderTargetTexture.samples = value;
  88722. },
  88723. enumerable: true,
  88724. configurable: true
  88725. });
  88726. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  88727. get: function () {
  88728. return this._renderTargetTexture.refreshRate;
  88729. },
  88730. set: function (value) {
  88731. this._renderTargetTexture.refreshRate = value;
  88732. },
  88733. enumerable: true,
  88734. configurable: true
  88735. });
  88736. ReflectionProbe.prototype.getScene = function () {
  88737. return this._scene;
  88738. };
  88739. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  88740. get: function () {
  88741. return this._renderTargetTexture;
  88742. },
  88743. enumerable: true,
  88744. configurable: true
  88745. });
  88746. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  88747. get: function () {
  88748. return this._renderTargetTexture.renderList;
  88749. },
  88750. enumerable: true,
  88751. configurable: true
  88752. });
  88753. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  88754. this._attachedMesh = mesh;
  88755. };
  88756. /**
  88757. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  88758. *
  88759. * @param renderingGroupId The rendering group id corresponding to its index
  88760. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  88761. */
  88762. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  88763. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  88764. };
  88765. ReflectionProbe.prototype.dispose = function () {
  88766. var index = this._scene.reflectionProbes.indexOf(this);
  88767. if (index !== -1) {
  88768. // Remove from the scene if found
  88769. this._scene.reflectionProbes.splice(index, 1);
  88770. }
  88771. if (this._renderTargetTexture) {
  88772. this._renderTargetTexture.dispose();
  88773. this._renderTargetTexture = null;
  88774. }
  88775. };
  88776. return ReflectionProbe;
  88777. }());
  88778. BABYLON.ReflectionProbe = ReflectionProbe;
  88779. })(BABYLON || (BABYLON = {}));
  88780. //# sourceMappingURL=babylon.reflectionProbe.js.map
  88781. "use strict";
  88782. var BABYLON;
  88783. (function (BABYLON) {
  88784. var Layer = /** @class */ (function () {
  88785. function Layer(name, imgUrl, scene, isBackground, color) {
  88786. this.name = name;
  88787. this.scale = new BABYLON.Vector2(1, 1);
  88788. this.offset = new BABYLON.Vector2(0, 0);
  88789. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  88790. this.layerMask = 0x0FFFFFFF;
  88791. this._vertexBuffers = {};
  88792. // Events
  88793. /**
  88794. * An event triggered when the layer is disposed.
  88795. * @type {BABYLON.Observable}
  88796. */
  88797. this.onDisposeObservable = new BABYLON.Observable();
  88798. /**
  88799. * An event triggered before rendering the scene
  88800. * @type {BABYLON.Observable}
  88801. */
  88802. this.onBeforeRenderObservable = new BABYLON.Observable();
  88803. /**
  88804. * An event triggered after rendering the scene
  88805. * @type {BABYLON.Observable}
  88806. */
  88807. this.onAfterRenderObservable = new BABYLON.Observable();
  88808. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  88809. this.isBackground = isBackground === undefined ? true : isBackground;
  88810. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  88811. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  88812. this._scene.layers.push(this);
  88813. var engine = this._scene.getEngine();
  88814. // VBO
  88815. var vertices = [];
  88816. vertices.push(1, 1);
  88817. vertices.push(-1, 1);
  88818. vertices.push(-1, -1);
  88819. vertices.push(1, -1);
  88820. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  88821. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  88822. this._createIndexBuffer();
  88823. // Effects
  88824. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  88825. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  88826. }
  88827. Object.defineProperty(Layer.prototype, "onDispose", {
  88828. set: function (callback) {
  88829. if (this._onDisposeObserver) {
  88830. this.onDisposeObservable.remove(this._onDisposeObserver);
  88831. }
  88832. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  88833. },
  88834. enumerable: true,
  88835. configurable: true
  88836. });
  88837. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  88838. set: function (callback) {
  88839. if (this._onBeforeRenderObserver) {
  88840. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  88841. }
  88842. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  88843. },
  88844. enumerable: true,
  88845. configurable: true
  88846. });
  88847. Object.defineProperty(Layer.prototype, "onAfterRender", {
  88848. set: function (callback) {
  88849. if (this._onAfterRenderObserver) {
  88850. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  88851. }
  88852. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  88853. },
  88854. enumerable: true,
  88855. configurable: true
  88856. });
  88857. Layer.prototype._createIndexBuffer = function () {
  88858. var engine = this._scene.getEngine();
  88859. // Indices
  88860. var indices = [];
  88861. indices.push(0);
  88862. indices.push(1);
  88863. indices.push(2);
  88864. indices.push(0);
  88865. indices.push(2);
  88866. indices.push(3);
  88867. this._indexBuffer = engine.createIndexBuffer(indices);
  88868. };
  88869. Layer.prototype._rebuild = function () {
  88870. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  88871. if (vb) {
  88872. vb._rebuild();
  88873. }
  88874. this._createIndexBuffer();
  88875. };
  88876. Layer.prototype.render = function () {
  88877. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  88878. // Check
  88879. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  88880. return;
  88881. var engine = this._scene.getEngine();
  88882. this.onBeforeRenderObservable.notifyObservers(this);
  88883. // Render
  88884. engine.enableEffect(currentEffect);
  88885. engine.setState(false);
  88886. // Texture
  88887. currentEffect.setTexture("textureSampler", this.texture);
  88888. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  88889. // Color
  88890. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  88891. // Scale / offset
  88892. currentEffect.setVector2("offset", this.offset);
  88893. currentEffect.setVector2("scale", this.scale);
  88894. // VBOs
  88895. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  88896. // Draw order
  88897. if (!this.alphaTest) {
  88898. engine.setAlphaMode(this.alphaBlendingMode);
  88899. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  88900. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  88901. }
  88902. else {
  88903. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  88904. }
  88905. this.onAfterRenderObservable.notifyObservers(this);
  88906. };
  88907. Layer.prototype.dispose = function () {
  88908. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  88909. if (vertexBuffer) {
  88910. vertexBuffer.dispose();
  88911. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  88912. }
  88913. if (this._indexBuffer) {
  88914. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  88915. this._indexBuffer = null;
  88916. }
  88917. if (this.texture) {
  88918. this.texture.dispose();
  88919. this.texture = null;
  88920. }
  88921. // Remove from scene
  88922. var index = this._scene.layers.indexOf(this);
  88923. this._scene.layers.splice(index, 1);
  88924. // Callback
  88925. this.onDisposeObservable.notifyObservers(this);
  88926. this.onDisposeObservable.clear();
  88927. this.onAfterRenderObservable.clear();
  88928. this.onBeforeRenderObservable.clear();
  88929. };
  88930. return Layer;
  88931. }());
  88932. BABYLON.Layer = Layer;
  88933. })(BABYLON || (BABYLON = {}));
  88934. //# sourceMappingURL=babylon.layer.js.map
  88935. "use strict";
  88936. var BABYLON;
  88937. (function (BABYLON) {
  88938. var TextureTools = /** @class */ (function () {
  88939. function TextureTools() {
  88940. }
  88941. /**
  88942. * Uses the GPU to create a copy texture rescaled at a given size
  88943. * @param texture Texture to copy from
  88944. * @param width Desired width
  88945. * @param height Desired height
  88946. * @return Generated texture
  88947. */
  88948. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  88949. if (useBilinearMode === void 0) { useBilinearMode = true; }
  88950. var scene = texture.getScene();
  88951. var engine = scene.getEngine();
  88952. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  88953. rtt.wrapU = texture.wrapU;
  88954. rtt.wrapV = texture.wrapV;
  88955. rtt.uOffset = texture.uOffset;
  88956. rtt.vOffset = texture.vOffset;
  88957. rtt.uScale = texture.uScale;
  88958. rtt.vScale = texture.vScale;
  88959. rtt.uAng = texture.uAng;
  88960. rtt.vAng = texture.vAng;
  88961. rtt.wAng = texture.wAng;
  88962. rtt.coordinatesIndex = texture.coordinatesIndex;
  88963. rtt.level = texture.level;
  88964. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  88965. rtt._texture.isReady = false;
  88966. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  88967. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  88968. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  88969. passPostProcess.getEffect().executeWhenCompiled(function () {
  88970. passPostProcess.onApply = function (effect) {
  88971. effect.setTexture("textureSampler", texture);
  88972. };
  88973. var internalTexture = rtt.getInternalTexture();
  88974. if (internalTexture) {
  88975. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  88976. engine.unBindFramebuffer(internalTexture);
  88977. rtt.disposeFramebufferObjects();
  88978. passPostProcess.dispose();
  88979. internalTexture.isReady = true;
  88980. }
  88981. });
  88982. return rtt;
  88983. };
  88984. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  88985. if (!scene._environmentBRDFTexture) {
  88986. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  88987. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  88988. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  88989. scene._environmentBRDFTexture = texture;
  88990. }
  88991. return scene._environmentBRDFTexture;
  88992. };
  88993. 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=";
  88994. return TextureTools;
  88995. }());
  88996. BABYLON.TextureTools = TextureTools;
  88997. })(BABYLON || (BABYLON = {}));
  88998. //# sourceMappingURL=babylon.textureTools.js.map
  88999. "use strict";
  89000. var BABYLON;
  89001. (function (BABYLON) {
  89002. var FramingBehavior = /** @class */ (function () {
  89003. function FramingBehavior() {
  89004. this._mode = FramingBehavior.FitFrustumSidesMode;
  89005. this._radiusScale = 1.0;
  89006. this._positionScale = 0.5;
  89007. this._defaultElevation = 0.3;
  89008. this._elevationReturnTime = 1500;
  89009. this._elevationReturnWaitTime = 1000;
  89010. this._zoomStopsAnimation = false;
  89011. this._framingTime = 1500;
  89012. this._isPointerDown = false;
  89013. this._lastInteractionTime = -Infinity;
  89014. // Framing control
  89015. this._animatables = new Array();
  89016. this._betaIsAnimating = false;
  89017. }
  89018. Object.defineProperty(FramingBehavior.prototype, "name", {
  89019. get: function () {
  89020. return "Framing";
  89021. },
  89022. enumerable: true,
  89023. configurable: true
  89024. });
  89025. Object.defineProperty(FramingBehavior.prototype, "mode", {
  89026. /**
  89027. * Gets current mode used by the behavior.
  89028. */
  89029. get: function () {
  89030. return this._mode;
  89031. },
  89032. /**
  89033. * Sets the current mode used by the behavior
  89034. */
  89035. set: function (mode) {
  89036. this._mode = mode;
  89037. },
  89038. enumerable: true,
  89039. configurable: true
  89040. });
  89041. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  89042. /**
  89043. * Gets the scale applied to the radius
  89044. */
  89045. get: function () {
  89046. return this._radiusScale;
  89047. },
  89048. /**
  89049. * Sets the scale applied to the radius (1 by default)
  89050. */
  89051. set: function (radius) {
  89052. this._radiusScale = radius;
  89053. },
  89054. enumerable: true,
  89055. configurable: true
  89056. });
  89057. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  89058. /**
  89059. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  89060. */
  89061. get: function () {
  89062. return this._positionScale;
  89063. },
  89064. /**
  89065. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  89066. */
  89067. set: function (scale) {
  89068. this._positionScale = scale;
  89069. },
  89070. enumerable: true,
  89071. configurable: true
  89072. });
  89073. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  89074. /**
  89075. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  89076. * behaviour is triggered, in radians.
  89077. */
  89078. get: function () {
  89079. return this._defaultElevation;
  89080. },
  89081. /**
  89082. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  89083. * behaviour is triggered, in radians.
  89084. */
  89085. set: function (elevation) {
  89086. this._defaultElevation = elevation;
  89087. },
  89088. enumerable: true,
  89089. configurable: true
  89090. });
  89091. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  89092. /**
  89093. * Gets the time (in milliseconds) taken to return to the default beta position.
  89094. * Negative value indicates camera should not return to default.
  89095. */
  89096. get: function () {
  89097. return this._elevationReturnTime;
  89098. },
  89099. /**
  89100. * Sets the time (in milliseconds) taken to return to the default beta position.
  89101. * Negative value indicates camera should not return to default.
  89102. */
  89103. set: function (speed) {
  89104. this._elevationReturnTime = speed;
  89105. },
  89106. enumerable: true,
  89107. configurable: true
  89108. });
  89109. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  89110. /**
  89111. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  89112. */
  89113. get: function () {
  89114. return this._elevationReturnWaitTime;
  89115. },
  89116. /**
  89117. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  89118. */
  89119. set: function (time) {
  89120. this._elevationReturnWaitTime = time;
  89121. },
  89122. enumerable: true,
  89123. configurable: true
  89124. });
  89125. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  89126. /**
  89127. * Gets the flag that indicates if user zooming should stop animation.
  89128. */
  89129. get: function () {
  89130. return this._zoomStopsAnimation;
  89131. },
  89132. /**
  89133. * Sets the flag that indicates if user zooming should stop animation.
  89134. */
  89135. set: function (flag) {
  89136. this._zoomStopsAnimation = flag;
  89137. },
  89138. enumerable: true,
  89139. configurable: true
  89140. });
  89141. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  89142. /**
  89143. * Gets the transition time when framing the mesh, in milliseconds
  89144. */
  89145. get: function () {
  89146. return this._framingTime;
  89147. },
  89148. /**
  89149. * Sets the transition time when framing the mesh, in milliseconds
  89150. */
  89151. set: function (time) {
  89152. this._framingTime = time;
  89153. },
  89154. enumerable: true,
  89155. configurable: true
  89156. });
  89157. FramingBehavior.prototype.init = function () {
  89158. // Do notihng
  89159. };
  89160. FramingBehavior.prototype.attach = function (camera) {
  89161. var _this = this;
  89162. this._attachedCamera = camera;
  89163. var scene = this._attachedCamera.getScene();
  89164. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  89165. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  89166. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  89167. _this._isPointerDown = true;
  89168. return;
  89169. }
  89170. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  89171. _this._isPointerDown = false;
  89172. }
  89173. });
  89174. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  89175. if (mesh) {
  89176. _this.zoomOnMesh(mesh);
  89177. }
  89178. });
  89179. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  89180. // Stop the animation if there is user interaction and the animation should stop for this interaction
  89181. _this._applyUserInteraction();
  89182. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  89183. // back to the default position after a given timeout
  89184. _this._maintainCameraAboveGround();
  89185. });
  89186. };
  89187. FramingBehavior.prototype.detach = function () {
  89188. if (!this._attachedCamera) {
  89189. return;
  89190. }
  89191. var scene = this._attachedCamera.getScene();
  89192. if (this._onPrePointerObservableObserver) {
  89193. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  89194. }
  89195. if (this._onAfterCheckInputsObserver) {
  89196. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  89197. }
  89198. if (this._onMeshTargetChangedObserver) {
  89199. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  89200. }
  89201. this._attachedCamera = null;
  89202. };
  89203. /**
  89204. * Targets the given mesh and updates zoom level accordingly.
  89205. * @param mesh The mesh to target.
  89206. * @param radius Optional. If a cached radius position already exists, overrides default.
  89207. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  89208. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  89209. * @param onAnimationEnd Callback triggered at the end of the framing animation
  89210. */
  89211. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  89212. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  89213. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  89214. mesh.computeWorldMatrix(true);
  89215. var boundingBox = mesh.getBoundingInfo().boundingBox;
  89216. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  89217. };
  89218. /**
  89219. * Targets the given mesh with its children and updates zoom level accordingly.
  89220. * @param mesh The mesh to target.
  89221. * @param radius Optional. If a cached radius position already exists, overrides default.
  89222. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  89223. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  89224. * @param onAnimationEnd Callback triggered at the end of the framing animation
  89225. */
  89226. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  89227. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  89228. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  89229. mesh.computeWorldMatrix(true);
  89230. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  89231. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  89232. };
  89233. /**
  89234. * Targets the given meshes with their children and updates zoom level accordingly.
  89235. * @param meshes The mesh to target.
  89236. * @param radius Optional. If a cached radius position already exists, overrides default.
  89237. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  89238. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  89239. * @param onAnimationEnd Callback triggered at the end of the framing animation
  89240. */
  89241. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  89242. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  89243. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  89244. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  89245. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  89246. for (var i = 0; i < meshes.length; i++) {
  89247. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  89248. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  89249. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  89250. }
  89251. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  89252. };
  89253. /**
  89254. * Targets the given mesh and updates zoom level accordingly.
  89255. * @param mesh The mesh to target.
  89256. * @param radius Optional. If a cached radius position already exists, overrides default.
  89257. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  89258. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  89259. * @param onAnimationEnd Callback triggered at the end of the framing animation
  89260. */
  89261. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  89262. var _this = this;
  89263. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  89264. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  89265. var zoomTarget;
  89266. if (!this._attachedCamera) {
  89267. return;
  89268. }
  89269. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  89270. var bottom = minimumWorld.y;
  89271. var top = maximumWorld.y;
  89272. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  89273. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  89274. if (focusOnOriginXZ) {
  89275. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  89276. }
  89277. else {
  89278. var centerWorld = minimumWorld.add(radiusWorld);
  89279. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  89280. }
  89281. if (!this._vectorTransition) {
  89282. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  89283. }
  89284. this._betaIsAnimating = true;
  89285. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  89286. if (animatable) {
  89287. this._animatables.push(animatable);
  89288. }
  89289. // sets the radius and lower radius bounds
  89290. // Small delta ensures camera is not always at lower zoom limit.
  89291. var radius = 0;
  89292. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  89293. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  89294. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  89295. radius = position;
  89296. }
  89297. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  89298. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  89299. if (this._attachedCamera.lowerRadiusLimit === null) {
  89300. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  89301. }
  89302. }
  89303. // Set sensibilities
  89304. var extend = maximumWorld.subtract(minimumWorld).length();
  89305. this._attachedCamera.panningSensibility = 5000 / extend;
  89306. this._attachedCamera.wheelPrecision = 100 / radius;
  89307. // transition to new radius
  89308. if (!this._radiusTransition) {
  89309. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  89310. }
  89311. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  89312. _this.stopAllAnimations();
  89313. if (onAnimationEnd) {
  89314. onAnimationEnd();
  89315. }
  89316. if (_this._attachedCamera) {
  89317. _this._attachedCamera.storeState();
  89318. }
  89319. });
  89320. if (animatable) {
  89321. this._animatables.push(animatable);
  89322. }
  89323. };
  89324. /**
  89325. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  89326. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  89327. * frustum width.
  89328. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  89329. * to fully enclose the mesh in the viewing frustum.
  89330. */
  89331. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  89332. var size = maximumWorld.subtract(minimumWorld);
  89333. var boxVectorGlobalDiagonal = size.length();
  89334. var frustumSlope = this._getFrustumSlope();
  89335. // Formula for setting distance
  89336. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  89337. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  89338. // Horizon distance
  89339. var radius = radiusWithoutFraming * this._radiusScale;
  89340. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  89341. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  89342. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  89343. var camera = this._attachedCamera;
  89344. if (!camera) {
  89345. return 0;
  89346. }
  89347. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  89348. // Don't exceed the requested limit
  89349. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  89350. }
  89351. // Don't exceed the upper radius limit
  89352. if (camera.upperRadiusLimit) {
  89353. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  89354. }
  89355. return distance;
  89356. };
  89357. /**
  89358. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  89359. * is automatically returned to its default position (expected to be above ground plane).
  89360. */
  89361. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  89362. var _this = this;
  89363. if (this._elevationReturnTime < 0) {
  89364. return;
  89365. }
  89366. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  89367. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  89368. var limitBeta = Math.PI * 0.5;
  89369. // Bring the camera back up if below the ground plane
  89370. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  89371. this._betaIsAnimating = true;
  89372. //Transition to new position
  89373. this.stopAllAnimations();
  89374. if (!this._betaTransition) {
  89375. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  89376. }
  89377. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  89378. _this._clearAnimationLocks();
  89379. _this.stopAllAnimations();
  89380. });
  89381. if (animatabe) {
  89382. this._animatables.push(animatabe);
  89383. }
  89384. }
  89385. };
  89386. /**
  89387. * Returns the frustum slope based on the canvas ratio and camera FOV
  89388. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  89389. */
  89390. FramingBehavior.prototype._getFrustumSlope = function () {
  89391. // Calculate the viewport ratio
  89392. // Aspect Ratio is Height/Width.
  89393. var camera = this._attachedCamera;
  89394. if (!camera) {
  89395. return BABYLON.Vector2.Zero();
  89396. }
  89397. var engine = camera.getScene().getEngine();
  89398. var aspectRatio = engine.getAspectRatio(camera);
  89399. // Camera FOV is the vertical field of view (top-bottom) in radians.
  89400. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  89401. var frustumSlopeY = Math.tan(camera.fov / 2);
  89402. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  89403. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  89404. // along the forward vector.
  89405. var frustumSlopeX = frustumSlopeY * aspectRatio;
  89406. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  89407. };
  89408. /**
  89409. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  89410. */
  89411. FramingBehavior.prototype._clearAnimationLocks = function () {
  89412. this._betaIsAnimating = false;
  89413. };
  89414. /**
  89415. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  89416. */
  89417. FramingBehavior.prototype._applyUserInteraction = function () {
  89418. if (this.isUserIsMoving) {
  89419. this._lastInteractionTime = BABYLON.Tools.Now;
  89420. this.stopAllAnimations();
  89421. this._clearAnimationLocks();
  89422. }
  89423. };
  89424. /**
  89425. * Stops and removes all animations that have been applied to the camera
  89426. */
  89427. FramingBehavior.prototype.stopAllAnimations = function () {
  89428. if (this._attachedCamera) {
  89429. this._attachedCamera.animations = [];
  89430. }
  89431. while (this._animatables.length) {
  89432. if (this._animatables[0]) {
  89433. this._animatables[0].onAnimationEnd = null;
  89434. this._animatables[0].stop();
  89435. }
  89436. this._animatables.shift();
  89437. }
  89438. };
  89439. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  89440. /**
  89441. * Gets a value indicating if the user is moving the camera
  89442. */
  89443. get: function () {
  89444. if (!this._attachedCamera) {
  89445. return false;
  89446. }
  89447. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  89448. this._attachedCamera.inertialBetaOffset !== 0 ||
  89449. this._attachedCamera.inertialRadiusOffset !== 0 ||
  89450. this._attachedCamera.inertialPanningX !== 0 ||
  89451. this._attachedCamera.inertialPanningY !== 0 ||
  89452. this._isPointerDown;
  89453. },
  89454. enumerable: true,
  89455. configurable: true
  89456. });
  89457. /**
  89458. * The easing function used by animations
  89459. */
  89460. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  89461. /**
  89462. * The easing mode used by animations
  89463. */
  89464. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  89465. // Statics
  89466. /**
  89467. * The camera can move all the way towards the mesh.
  89468. */
  89469. FramingBehavior.IgnoreBoundsSizeMode = 0;
  89470. /**
  89471. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  89472. */
  89473. FramingBehavior.FitFrustumSidesMode = 1;
  89474. return FramingBehavior;
  89475. }());
  89476. BABYLON.FramingBehavior = FramingBehavior;
  89477. })(BABYLON || (BABYLON = {}));
  89478. //# sourceMappingURL=babylon.framingBehavior.js.map
  89479. "use strict";
  89480. var BABYLON;
  89481. (function (BABYLON) {
  89482. /**
  89483. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  89484. */
  89485. var BouncingBehavior = /** @class */ (function () {
  89486. function BouncingBehavior() {
  89487. /**
  89488. * The duration of the animation, in milliseconds
  89489. */
  89490. this.transitionDuration = 450;
  89491. /**
  89492. * Length of the distance animated by the transition when lower radius is reached
  89493. */
  89494. this.lowerRadiusTransitionRange = 2;
  89495. /**
  89496. * Length of the distance animated by the transition when upper radius is reached
  89497. */
  89498. this.upperRadiusTransitionRange = -2;
  89499. this._autoTransitionRange = false;
  89500. // Animations
  89501. this._radiusIsAnimating = false;
  89502. this._radiusBounceTransition = null;
  89503. this._animatables = new Array();
  89504. }
  89505. Object.defineProperty(BouncingBehavior.prototype, "name", {
  89506. get: function () {
  89507. return "Bouncing";
  89508. },
  89509. enumerable: true,
  89510. configurable: true
  89511. });
  89512. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  89513. /**
  89514. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  89515. */
  89516. get: function () {
  89517. return this._autoTransitionRange;
  89518. },
  89519. /**
  89520. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  89521. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  89522. */
  89523. set: function (value) {
  89524. var _this = this;
  89525. if (this._autoTransitionRange === value) {
  89526. return;
  89527. }
  89528. this._autoTransitionRange = value;
  89529. var camera = this._attachedCamera;
  89530. if (!camera) {
  89531. return;
  89532. }
  89533. if (value) {
  89534. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  89535. if (!mesh) {
  89536. return;
  89537. }
  89538. mesh.computeWorldMatrix(true);
  89539. var diagonal = mesh.getBoundingInfo().diagonalLength;
  89540. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  89541. _this.upperRadiusTransitionRange = diagonal * 0.05;
  89542. });
  89543. }
  89544. else if (this._onMeshTargetChangedObserver) {
  89545. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  89546. }
  89547. },
  89548. enumerable: true,
  89549. configurable: true
  89550. });
  89551. BouncingBehavior.prototype.init = function () {
  89552. // Do notihng
  89553. };
  89554. BouncingBehavior.prototype.attach = function (camera) {
  89555. var _this = this;
  89556. this._attachedCamera = camera;
  89557. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  89558. if (!_this._attachedCamera) {
  89559. return;
  89560. }
  89561. // Add the bounce animation to the lower radius limit
  89562. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  89563. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  89564. }
  89565. // Add the bounce animation to the upper radius limit
  89566. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  89567. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  89568. }
  89569. });
  89570. };
  89571. BouncingBehavior.prototype.detach = function () {
  89572. if (!this._attachedCamera) {
  89573. return;
  89574. }
  89575. if (this._onAfterCheckInputsObserver) {
  89576. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  89577. }
  89578. if (this._onMeshTargetChangedObserver) {
  89579. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  89580. }
  89581. this._attachedCamera = null;
  89582. };
  89583. /**
  89584. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  89585. * @param radiusLimit The limit to check against.
  89586. * @return Bool to indicate if at limit.
  89587. */
  89588. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  89589. if (!this._attachedCamera) {
  89590. return false;
  89591. }
  89592. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  89593. return true;
  89594. }
  89595. return false;
  89596. };
  89597. /**
  89598. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  89599. * @param radiusDelta The delta by which to animate to. Can be negative.
  89600. */
  89601. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  89602. var _this = this;
  89603. if (!this._attachedCamera) {
  89604. return;
  89605. }
  89606. if (!this._radiusBounceTransition) {
  89607. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  89608. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  89609. }
  89610. // Prevent zoom until bounce has completed
  89611. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  89612. this._attachedCamera.wheelPrecision = Infinity;
  89613. this._attachedCamera.inertialRadiusOffset = 0;
  89614. // Animate to the radius limit
  89615. this.stopAllAnimations();
  89616. this._radiusIsAnimating = true;
  89617. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  89618. if (animatable) {
  89619. this._animatables.push(animatable);
  89620. }
  89621. };
  89622. /**
  89623. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  89624. */
  89625. BouncingBehavior.prototype._clearAnimationLocks = function () {
  89626. this._radiusIsAnimating = false;
  89627. if (this._attachedCamera) {
  89628. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  89629. }
  89630. };
  89631. /**
  89632. * Stops and removes all animations that have been applied to the camera
  89633. */
  89634. BouncingBehavior.prototype.stopAllAnimations = function () {
  89635. if (this._attachedCamera) {
  89636. this._attachedCamera.animations = [];
  89637. }
  89638. while (this._animatables.length) {
  89639. this._animatables[0].onAnimationEnd = null;
  89640. this._animatables[0].stop();
  89641. this._animatables.shift();
  89642. }
  89643. };
  89644. /**
  89645. * The easing function used by animations
  89646. */
  89647. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  89648. /**
  89649. * The easing mode used by animations
  89650. */
  89651. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  89652. return BouncingBehavior;
  89653. }());
  89654. BABYLON.BouncingBehavior = BouncingBehavior;
  89655. })(BABYLON || (BABYLON = {}));
  89656. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  89657. "use strict";
  89658. var BABYLON;
  89659. (function (BABYLON) {
  89660. var AutoRotationBehavior = /** @class */ (function () {
  89661. function AutoRotationBehavior() {
  89662. this._zoomStopsAnimation = false;
  89663. this._idleRotationSpeed = 0.05;
  89664. this._idleRotationWaitTime = 2000;
  89665. this._idleRotationSpinupTime = 2000;
  89666. this._isPointerDown = false;
  89667. this._lastFrameTime = null;
  89668. this._lastInteractionTime = -Infinity;
  89669. this._cameraRotationSpeed = 0;
  89670. this._lastFrameRadius = 0;
  89671. }
  89672. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  89673. get: function () {
  89674. return "AutoRotation";
  89675. },
  89676. enumerable: true,
  89677. configurable: true
  89678. });
  89679. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  89680. /**
  89681. * Gets the flag that indicates if user zooming should stop animation.
  89682. */
  89683. get: function () {
  89684. return this._zoomStopsAnimation;
  89685. },
  89686. /**
  89687. * Sets the flag that indicates if user zooming should stop animation.
  89688. */
  89689. set: function (flag) {
  89690. this._zoomStopsAnimation = flag;
  89691. },
  89692. enumerable: true,
  89693. configurable: true
  89694. });
  89695. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  89696. /**
  89697. * Gets the default speed at which the camera rotates around the model.
  89698. */
  89699. get: function () {
  89700. return this._idleRotationSpeed;
  89701. },
  89702. /**
  89703. * Sets the default speed at which the camera rotates around the model.
  89704. */
  89705. set: function (speed) {
  89706. this._idleRotationSpeed = speed;
  89707. },
  89708. enumerable: true,
  89709. configurable: true
  89710. });
  89711. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  89712. /**
  89713. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  89714. */
  89715. get: function () {
  89716. return this._idleRotationWaitTime;
  89717. },
  89718. /**
  89719. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  89720. */
  89721. set: function (time) {
  89722. this._idleRotationWaitTime = time;
  89723. },
  89724. enumerable: true,
  89725. configurable: true
  89726. });
  89727. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  89728. /**
  89729. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  89730. */
  89731. get: function () {
  89732. return this._idleRotationSpinupTime;
  89733. },
  89734. /**
  89735. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  89736. */
  89737. set: function (time) {
  89738. this._idleRotationSpinupTime = time;
  89739. },
  89740. enumerable: true,
  89741. configurable: true
  89742. });
  89743. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  89744. /**
  89745. * Gets a value indicating if the camera is currently rotating because of this behavior
  89746. */
  89747. get: function () {
  89748. return Math.abs(this._cameraRotationSpeed) > 0;
  89749. },
  89750. enumerable: true,
  89751. configurable: true
  89752. });
  89753. AutoRotationBehavior.prototype.init = function () {
  89754. // Do notihng
  89755. };
  89756. AutoRotationBehavior.prototype.attach = function (camera) {
  89757. var _this = this;
  89758. this._attachedCamera = camera;
  89759. var scene = this._attachedCamera.getScene();
  89760. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  89761. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  89762. _this._isPointerDown = true;
  89763. return;
  89764. }
  89765. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  89766. _this._isPointerDown = false;
  89767. }
  89768. });
  89769. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  89770. var now = BABYLON.Tools.Now;
  89771. var dt = 0;
  89772. if (_this._lastFrameTime != null) {
  89773. dt = now - _this._lastFrameTime;
  89774. }
  89775. _this._lastFrameTime = now;
  89776. // Stop the animation if there is user interaction and the animation should stop for this interaction
  89777. _this._applyUserInteraction();
  89778. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  89779. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  89780. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  89781. // Step camera rotation by rotation speed
  89782. if (_this._attachedCamera) {
  89783. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  89784. }
  89785. });
  89786. };
  89787. AutoRotationBehavior.prototype.detach = function () {
  89788. if (!this._attachedCamera) {
  89789. return;
  89790. }
  89791. var scene = this._attachedCamera.getScene();
  89792. if (this._onPrePointerObservableObserver) {
  89793. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  89794. }
  89795. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  89796. this._attachedCamera = null;
  89797. };
  89798. /**
  89799. * Returns true if user is scrolling.
  89800. * @return true if user is scrolling.
  89801. */
  89802. AutoRotationBehavior.prototype._userIsZooming = function () {
  89803. if (!this._attachedCamera) {
  89804. return false;
  89805. }
  89806. return this._attachedCamera.inertialRadiusOffset !== 0;
  89807. };
  89808. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  89809. if (!this._attachedCamera) {
  89810. return false;
  89811. }
  89812. var zoomHasHitLimit = false;
  89813. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  89814. zoomHasHitLimit = true;
  89815. }
  89816. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  89817. this._lastFrameRadius = this._attachedCamera.radius;
  89818. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  89819. };
  89820. /**
  89821. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  89822. */
  89823. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  89824. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  89825. this._lastInteractionTime = BABYLON.Tools.Now;
  89826. }
  89827. };
  89828. // Tools
  89829. AutoRotationBehavior.prototype._userIsMoving = function () {
  89830. if (!this._attachedCamera) {
  89831. return false;
  89832. }
  89833. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  89834. this._attachedCamera.inertialBetaOffset !== 0 ||
  89835. this._attachedCamera.inertialRadiusOffset !== 0 ||
  89836. this._attachedCamera.inertialPanningX !== 0 ||
  89837. this._attachedCamera.inertialPanningY !== 0 ||
  89838. this._isPointerDown;
  89839. };
  89840. return AutoRotationBehavior;
  89841. }());
  89842. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  89843. })(BABYLON || (BABYLON = {}));
  89844. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  89845. "use strict";
  89846. var BABYLON;
  89847. (function (BABYLON) {
  89848. var NullEngineOptions = /** @class */ (function () {
  89849. function NullEngineOptions() {
  89850. this.renderWidth = 512;
  89851. this.renderHeight = 256;
  89852. this.textureSize = 512;
  89853. this.deterministicLockstep = false;
  89854. this.lockstepMaxSteps = 4;
  89855. }
  89856. return NullEngineOptions;
  89857. }());
  89858. BABYLON.NullEngineOptions = NullEngineOptions;
  89859. /**
  89860. * The null engine class provides support for headless version of babylon.js.
  89861. * This can be used in server side scenario or for testing purposes
  89862. */
  89863. var NullEngine = /** @class */ (function (_super) {
  89864. __extends(NullEngine, _super);
  89865. function NullEngine(options) {
  89866. if (options === void 0) { options = new NullEngineOptions(); }
  89867. var _this = _super.call(this, null) || this;
  89868. if (options.deterministicLockstep === undefined) {
  89869. options.deterministicLockstep = false;
  89870. }
  89871. if (options.lockstepMaxSteps === undefined) {
  89872. options.lockstepMaxSteps = 4;
  89873. }
  89874. _this._options = options;
  89875. // Init caps
  89876. // We consider we are on a webgl1 capable device
  89877. _this._caps = new BABYLON.EngineCapabilities();
  89878. _this._caps.maxTexturesImageUnits = 16;
  89879. _this._caps.maxVertexTextureImageUnits = 16;
  89880. _this._caps.maxTextureSize = 512;
  89881. _this._caps.maxCubemapTextureSize = 512;
  89882. _this._caps.maxRenderTextureSize = 512;
  89883. _this._caps.maxVertexAttribs = 16;
  89884. _this._caps.maxVaryingVectors = 16;
  89885. _this._caps.maxFragmentUniformVectors = 16;
  89886. _this._caps.maxVertexUniformVectors = 16;
  89887. // Extensions
  89888. _this._caps.standardDerivatives = false;
  89889. _this._caps.astc = null;
  89890. _this._caps.s3tc = null;
  89891. _this._caps.pvrtc = null;
  89892. _this._caps.etc1 = null;
  89893. _this._caps.etc2 = null;
  89894. _this._caps.textureAnisotropicFilterExtension = null;
  89895. _this._caps.maxAnisotropy = 0;
  89896. _this._caps.uintIndices = false;
  89897. _this._caps.fragmentDepthSupported = false;
  89898. _this._caps.highPrecisionShaderSupported = true;
  89899. _this._caps.colorBufferFloat = false;
  89900. _this._caps.textureFloat = false;
  89901. _this._caps.textureFloatLinearFiltering = false;
  89902. _this._caps.textureFloatRender = false;
  89903. _this._caps.textureHalfFloat = false;
  89904. _this._caps.textureHalfFloatLinearFiltering = false;
  89905. _this._caps.textureHalfFloatRender = false;
  89906. _this._caps.textureLOD = false;
  89907. _this._caps.drawBuffersExtension = false;
  89908. _this._caps.depthTextureExtension = false;
  89909. _this._caps.vertexArrayObject = false;
  89910. _this._caps.instancedArrays = false;
  89911. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  89912. // Wrappers
  89913. if (typeof URL === "undefined") {
  89914. URL = {
  89915. createObjectURL: function () { },
  89916. revokeObjectURL: function () { }
  89917. };
  89918. }
  89919. if (typeof Blob === "undefined") {
  89920. Blob = function () { };
  89921. }
  89922. return _this;
  89923. }
  89924. NullEngine.prototype.isDeterministicLockStep = function () {
  89925. return this._options.deterministicLockstep;
  89926. };
  89927. NullEngine.prototype.getLockstepMaxSteps = function () {
  89928. return this._options.lockstepMaxSteps;
  89929. };
  89930. NullEngine.prototype.getHardwareScalingLevel = function () {
  89931. return 1.0;
  89932. };
  89933. NullEngine.prototype.createVertexBuffer = function (vertices) {
  89934. return {
  89935. capacity: 0,
  89936. references: 1,
  89937. is32Bits: false
  89938. };
  89939. };
  89940. NullEngine.prototype.createIndexBuffer = function (indices) {
  89941. return {
  89942. capacity: 0,
  89943. references: 1,
  89944. is32Bits: false
  89945. };
  89946. };
  89947. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  89948. if (stencil === void 0) { stencil = false; }
  89949. };
  89950. NullEngine.prototype.getRenderWidth = function (useScreen) {
  89951. if (useScreen === void 0) { useScreen = false; }
  89952. if (!useScreen && this._currentRenderTarget) {
  89953. return this._currentRenderTarget.width;
  89954. }
  89955. return this._options.renderWidth;
  89956. };
  89957. NullEngine.prototype.getRenderHeight = function (useScreen) {
  89958. if (useScreen === void 0) { useScreen = false; }
  89959. if (!useScreen && this._currentRenderTarget) {
  89960. return this._currentRenderTarget.height;
  89961. }
  89962. return this._options.renderHeight;
  89963. };
  89964. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  89965. this._cachedViewport = viewport;
  89966. };
  89967. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  89968. return {
  89969. transformFeedback: null,
  89970. __SPECTOR_rebuildProgram: null
  89971. };
  89972. };
  89973. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  89974. return [];
  89975. };
  89976. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  89977. return [];
  89978. };
  89979. NullEngine.prototype.bindSamplers = function (effect) {
  89980. this._currentEffect = null;
  89981. };
  89982. NullEngine.prototype.enableEffect = function (effect) {
  89983. this._currentEffect = effect;
  89984. if (effect.onBind) {
  89985. effect.onBind(effect);
  89986. }
  89987. effect.onBindObservable.notifyObservers(effect);
  89988. };
  89989. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  89990. if (zOffset === void 0) { zOffset = 0; }
  89991. if (reverseSide === void 0) { reverseSide = false; }
  89992. };
  89993. NullEngine.prototype.setIntArray = function (uniform, array) {
  89994. };
  89995. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  89996. };
  89997. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  89998. };
  89999. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  90000. };
  90001. NullEngine.prototype.setFloatArray = function (uniform, array) {
  90002. };
  90003. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  90004. };
  90005. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  90006. };
  90007. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  90008. };
  90009. NullEngine.prototype.setArray = function (uniform, array) {
  90010. };
  90011. NullEngine.prototype.setArray2 = function (uniform, array) {
  90012. };
  90013. NullEngine.prototype.setArray3 = function (uniform, array) {
  90014. };
  90015. NullEngine.prototype.setArray4 = function (uniform, array) {
  90016. };
  90017. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  90018. };
  90019. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  90020. };
  90021. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  90022. };
  90023. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  90024. };
  90025. NullEngine.prototype.setFloat = function (uniform, value) {
  90026. };
  90027. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  90028. };
  90029. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  90030. };
  90031. NullEngine.prototype.setBool = function (uniform, bool) {
  90032. };
  90033. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  90034. };
  90035. NullEngine.prototype.setColor3 = function (uniform, color3) {
  90036. };
  90037. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  90038. };
  90039. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  90040. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  90041. if (this._alphaMode === mode) {
  90042. return;
  90043. }
  90044. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  90045. if (!noDepthWriteChange) {
  90046. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  90047. }
  90048. this._alphaMode = mode;
  90049. };
  90050. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  90051. };
  90052. NullEngine.prototype.wipeCaches = function (bruteForce) {
  90053. if (this.preventCacheWipeBetweenFrames) {
  90054. return;
  90055. }
  90056. this.resetTextureCache();
  90057. this._currentEffect = null;
  90058. if (bruteForce) {
  90059. this._currentProgram = null;
  90060. this._stencilState.reset();
  90061. this._depthCullingState.reset();
  90062. this._alphaState.reset();
  90063. }
  90064. this._cachedVertexBuffers = null;
  90065. this._cachedIndexBuffer = null;
  90066. this._cachedEffectForVertexBuffers = null;
  90067. };
  90068. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  90069. };
  90070. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  90071. };
  90072. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  90073. };
  90074. NullEngine.prototype._createTexture = function () {
  90075. return {};
  90076. };
  90077. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  90078. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  90079. if (onLoad === void 0) { onLoad = null; }
  90080. if (onError === void 0) { onError = null; }
  90081. if (buffer === void 0) { buffer = null; }
  90082. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  90083. var url = String(urlArg);
  90084. texture.url = url;
  90085. texture.generateMipMaps = !noMipmap;
  90086. texture.samplingMode = samplingMode;
  90087. texture.invertY = invertY;
  90088. texture.baseWidth = this._options.textureSize;
  90089. texture.baseHeight = this._options.textureSize;
  90090. texture.width = this._options.textureSize;
  90091. texture.height = this._options.textureSize;
  90092. if (format) {
  90093. texture.format = format;
  90094. }
  90095. texture.isReady = true;
  90096. if (onLoad) {
  90097. onLoad();
  90098. }
  90099. return texture;
  90100. };
  90101. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  90102. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  90103. if (options !== undefined && typeof options === "object") {
  90104. fullOptions.generateMipMaps = options.generateMipMaps;
  90105. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  90106. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  90107. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  90108. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  90109. }
  90110. else {
  90111. fullOptions.generateMipMaps = options;
  90112. fullOptions.generateDepthBuffer = true;
  90113. fullOptions.generateStencilBuffer = false;
  90114. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  90115. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  90116. }
  90117. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  90118. var width = size.width || size;
  90119. var height = size.height || size;
  90120. texture._depthStencilBuffer = {};
  90121. texture._framebuffer = {};
  90122. texture.baseWidth = width;
  90123. texture.baseHeight = height;
  90124. texture.width = width;
  90125. texture.height = height;
  90126. texture.isReady = true;
  90127. texture.samples = 1;
  90128. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  90129. texture.samplingMode = fullOptions.samplingMode;
  90130. texture.type = fullOptions.type;
  90131. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  90132. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  90133. return texture;
  90134. };
  90135. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  90136. texture.samplingMode = samplingMode;
  90137. };
  90138. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  90139. if (this._currentRenderTarget) {
  90140. this.unBindFramebuffer(this._currentRenderTarget);
  90141. }
  90142. this._currentRenderTarget = texture;
  90143. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  90144. if (this._cachedViewport && !forceFullscreenViewport) {
  90145. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  90146. }
  90147. };
  90148. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  90149. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  90150. this._currentRenderTarget = null;
  90151. if (onBeforeUnbind) {
  90152. if (texture._MSAAFramebuffer) {
  90153. this._currentFramebuffer = texture._framebuffer;
  90154. }
  90155. onBeforeUnbind();
  90156. }
  90157. this._currentFramebuffer = null;
  90158. };
  90159. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  90160. var vbo = {
  90161. capacity: 1,
  90162. references: 1,
  90163. is32Bits: false
  90164. };
  90165. return vbo;
  90166. };
  90167. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  90168. if (offset === void 0) { offset = 0; }
  90169. };
  90170. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  90171. };
  90172. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  90173. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  90174. this._boundTexturesCache[this._activeChannel] = texture;
  90175. }
  90176. };
  90177. NullEngine.prototype._bindTexture = function (channel, texture) {
  90178. if (channel < 0) {
  90179. return;
  90180. }
  90181. this._bindTextureDirectly(0, texture);
  90182. };
  90183. NullEngine.prototype._releaseBuffer = function (buffer) {
  90184. buffer.references--;
  90185. if (buffer.references === 0) {
  90186. return true;
  90187. }
  90188. return false;
  90189. };
  90190. return NullEngine;
  90191. }(BABYLON.Engine));
  90192. BABYLON.NullEngine = NullEngine;
  90193. })(BABYLON || (BABYLON = {}));
  90194. //# sourceMappingURL=babylon.nullEngine.js.map
  90195. "use strict";
  90196. var BABYLON;
  90197. (function (BABYLON) {
  90198. /**
  90199. * This class can be used to get instrumentation data from a Babylon engine
  90200. */
  90201. var EngineInstrumentation = /** @class */ (function () {
  90202. function EngineInstrumentation(engine) {
  90203. this.engine = engine;
  90204. this._captureGPUFrameTime = false;
  90205. this._gpuFrameTime = new BABYLON.PerfCounter();
  90206. this._captureShaderCompilationTime = false;
  90207. this._shaderCompilationTime = new BABYLON.PerfCounter();
  90208. // Observers
  90209. this._onBeginFrameObserver = null;
  90210. this._onEndFrameObserver = null;
  90211. this._onBeforeShaderCompilationObserver = null;
  90212. this._onAfterShaderCompilationObserver = null;
  90213. }
  90214. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  90215. // Properties
  90216. /**
  90217. * Gets the perf counter used for GPU frame time
  90218. */
  90219. get: function () {
  90220. return this._gpuFrameTime;
  90221. },
  90222. enumerable: true,
  90223. configurable: true
  90224. });
  90225. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  90226. /**
  90227. * Gets the GPU frame time capture status
  90228. */
  90229. get: function () {
  90230. return this._captureGPUFrameTime;
  90231. },
  90232. /**
  90233. * Enable or disable the GPU frame time capture
  90234. */
  90235. set: function (value) {
  90236. var _this = this;
  90237. if (value === this._captureGPUFrameTime) {
  90238. return;
  90239. }
  90240. this._captureGPUFrameTime = value;
  90241. if (value) {
  90242. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  90243. if (!_this._gpuFrameTimeToken) {
  90244. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  90245. }
  90246. });
  90247. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  90248. if (!_this._gpuFrameTimeToken) {
  90249. return;
  90250. }
  90251. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  90252. if (time > -1) {
  90253. _this._gpuFrameTimeToken = null;
  90254. _this._gpuFrameTime.fetchNewFrame();
  90255. _this._gpuFrameTime.addCount(time, true);
  90256. }
  90257. });
  90258. }
  90259. else {
  90260. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  90261. this._onBeginFrameObserver = null;
  90262. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  90263. this._onEndFrameObserver = null;
  90264. }
  90265. },
  90266. enumerable: true,
  90267. configurable: true
  90268. });
  90269. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  90270. /**
  90271. * Gets the perf counter used for shader compilation time
  90272. */
  90273. get: function () {
  90274. return this._shaderCompilationTime;
  90275. },
  90276. enumerable: true,
  90277. configurable: true
  90278. });
  90279. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  90280. /**
  90281. * Gets the shader compilation time capture status
  90282. */
  90283. get: function () {
  90284. return this._captureShaderCompilationTime;
  90285. },
  90286. /**
  90287. * Enable or disable the shader compilation time capture
  90288. */
  90289. set: function (value) {
  90290. var _this = this;
  90291. if (value === this._captureShaderCompilationTime) {
  90292. return;
  90293. }
  90294. this._captureShaderCompilationTime = value;
  90295. if (value) {
  90296. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  90297. _this._shaderCompilationTime.fetchNewFrame();
  90298. _this._shaderCompilationTime.beginMonitoring();
  90299. });
  90300. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  90301. _this._shaderCompilationTime.endMonitoring();
  90302. });
  90303. }
  90304. else {
  90305. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  90306. this._onBeforeShaderCompilationObserver = null;
  90307. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  90308. this._onAfterShaderCompilationObserver = null;
  90309. }
  90310. },
  90311. enumerable: true,
  90312. configurable: true
  90313. });
  90314. EngineInstrumentation.prototype.dispose = function () {
  90315. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  90316. this._onBeginFrameObserver = null;
  90317. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  90318. this._onEndFrameObserver = null;
  90319. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  90320. this._onBeforeShaderCompilationObserver = null;
  90321. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  90322. this._onAfterShaderCompilationObserver = null;
  90323. this.engine = null;
  90324. };
  90325. return EngineInstrumentation;
  90326. }());
  90327. BABYLON.EngineInstrumentation = EngineInstrumentation;
  90328. })(BABYLON || (BABYLON = {}));
  90329. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  90330. "use strict";
  90331. var BABYLON;
  90332. (function (BABYLON) {
  90333. /**
  90334. * This class can be used to get instrumentation data from a Babylon engine
  90335. */
  90336. var SceneInstrumentation = /** @class */ (function () {
  90337. function SceneInstrumentation(scene) {
  90338. var _this = this;
  90339. this.scene = scene;
  90340. this._captureActiveMeshesEvaluationTime = false;
  90341. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  90342. this._captureRenderTargetsRenderTime = false;
  90343. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  90344. this._captureFrameTime = false;
  90345. this._frameTime = new BABYLON.PerfCounter();
  90346. this._captureRenderTime = false;
  90347. this._renderTime = new BABYLON.PerfCounter();
  90348. this._captureInterFrameTime = false;
  90349. this._interFrameTime = new BABYLON.PerfCounter();
  90350. this._captureParticlesRenderTime = false;
  90351. this._particlesRenderTime = new BABYLON.PerfCounter();
  90352. this._captureSpritesRenderTime = false;
  90353. this._spritesRenderTime = new BABYLON.PerfCounter();
  90354. this._capturePhysicsTime = false;
  90355. this._physicsTime = new BABYLON.PerfCounter();
  90356. this._captureAnimationsTime = false;
  90357. this._animationsTime = new BABYLON.PerfCounter();
  90358. // Observers
  90359. this._onBeforeActiveMeshesEvaluationObserver = null;
  90360. this._onAfterActiveMeshesEvaluationObserver = null;
  90361. this._onBeforeRenderTargetsRenderObserver = null;
  90362. this._onAfterRenderTargetsRenderObserver = null;
  90363. this._onAfterRenderObserver = null;
  90364. this._onBeforeDrawPhaseObserver = null;
  90365. this._onAfterDrawPhaseObserver = null;
  90366. this._onBeforeAnimationsObserver = null;
  90367. this._onBeforeParticlesRenderingObserver = null;
  90368. this._onAfterParticlesRenderingObserver = null;
  90369. this._onBeforeSpritesRenderingObserver = null;
  90370. this._onAfterSpritesRenderingObserver = null;
  90371. this._onBeforePhysicsObserver = null;
  90372. this._onAfterPhysicsObserver = null;
  90373. this._onAfterAnimationsObserver = null;
  90374. // Before render
  90375. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  90376. if (_this._captureActiveMeshesEvaluationTime) {
  90377. _this._activeMeshesEvaluationTime.fetchNewFrame();
  90378. }
  90379. if (_this._captureRenderTargetsRenderTime) {
  90380. _this._renderTargetsRenderTime.fetchNewFrame();
  90381. }
  90382. if (_this._captureFrameTime) {
  90383. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  90384. _this._frameTime.beginMonitoring();
  90385. }
  90386. if (_this._captureInterFrameTime) {
  90387. _this._interFrameTime.endMonitoring();
  90388. }
  90389. if (_this._captureParticlesRenderTime) {
  90390. _this._particlesRenderTime.fetchNewFrame();
  90391. }
  90392. if (_this._captureSpritesRenderTime) {
  90393. _this._spritesRenderTime.fetchNewFrame();
  90394. }
  90395. if (_this._captureAnimationsTime) {
  90396. _this._animationsTime.beginMonitoring();
  90397. }
  90398. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  90399. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  90400. });
  90401. // After render
  90402. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  90403. if (_this._captureFrameTime) {
  90404. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  90405. _this._frameTime.endMonitoring();
  90406. }
  90407. if (_this._captureRenderTime) {
  90408. _this._renderTime.endMonitoring(false);
  90409. }
  90410. if (_this._captureInterFrameTime) {
  90411. _this._interFrameTime.beginMonitoring();
  90412. }
  90413. });
  90414. }
  90415. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  90416. // Properties
  90417. /**
  90418. * Gets the perf counter used for active meshes evaluation time
  90419. */
  90420. get: function () {
  90421. return this._activeMeshesEvaluationTime;
  90422. },
  90423. enumerable: true,
  90424. configurable: true
  90425. });
  90426. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  90427. /**
  90428. * Gets the active meshes evaluation time capture status
  90429. */
  90430. get: function () {
  90431. return this._captureActiveMeshesEvaluationTime;
  90432. },
  90433. /**
  90434. * Enable or disable the active meshes evaluation time capture
  90435. */
  90436. set: function (value) {
  90437. var _this = this;
  90438. if (value === this._captureActiveMeshesEvaluationTime) {
  90439. return;
  90440. }
  90441. this._captureActiveMeshesEvaluationTime = value;
  90442. if (value) {
  90443. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  90444. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  90445. _this._activeMeshesEvaluationTime.beginMonitoring();
  90446. });
  90447. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  90448. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  90449. _this._activeMeshesEvaluationTime.endMonitoring();
  90450. });
  90451. }
  90452. else {
  90453. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  90454. this._onBeforeActiveMeshesEvaluationObserver = null;
  90455. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  90456. this._onAfterActiveMeshesEvaluationObserver = null;
  90457. }
  90458. },
  90459. enumerable: true,
  90460. configurable: true
  90461. });
  90462. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  90463. /**
  90464. * Gets the perf counter used for render targets render time
  90465. */
  90466. get: function () {
  90467. return this._renderTargetsRenderTime;
  90468. },
  90469. enumerable: true,
  90470. configurable: true
  90471. });
  90472. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  90473. /**
  90474. * Gets the render targets render time capture status
  90475. */
  90476. get: function () {
  90477. return this._captureRenderTargetsRenderTime;
  90478. },
  90479. /**
  90480. * Enable or disable the render targets render time capture
  90481. */
  90482. set: function (value) {
  90483. var _this = this;
  90484. if (value === this._captureRenderTargetsRenderTime) {
  90485. return;
  90486. }
  90487. this._captureRenderTargetsRenderTime = value;
  90488. if (value) {
  90489. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  90490. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  90491. _this._renderTargetsRenderTime.beginMonitoring();
  90492. });
  90493. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  90494. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  90495. _this._renderTargetsRenderTime.endMonitoring(false);
  90496. });
  90497. }
  90498. else {
  90499. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  90500. this._onBeforeRenderTargetsRenderObserver = null;
  90501. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  90502. this._onAfterRenderTargetsRenderObserver = null;
  90503. }
  90504. },
  90505. enumerable: true,
  90506. configurable: true
  90507. });
  90508. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  90509. /**
  90510. * Gets the perf counter used for particles render time
  90511. */
  90512. get: function () {
  90513. return this._particlesRenderTime;
  90514. },
  90515. enumerable: true,
  90516. configurable: true
  90517. });
  90518. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  90519. /**
  90520. * Gets the particles render time capture status
  90521. */
  90522. get: function () {
  90523. return this._captureParticlesRenderTime;
  90524. },
  90525. /**
  90526. * Enable or disable the particles render time capture
  90527. */
  90528. set: function (value) {
  90529. var _this = this;
  90530. if (value === this._captureParticlesRenderTime) {
  90531. return;
  90532. }
  90533. this._captureParticlesRenderTime = value;
  90534. if (value) {
  90535. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  90536. BABYLON.Tools.StartPerformanceCounter("Particles");
  90537. _this._particlesRenderTime.beginMonitoring();
  90538. });
  90539. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  90540. BABYLON.Tools.EndPerformanceCounter("Particles");
  90541. _this._particlesRenderTime.endMonitoring(false);
  90542. });
  90543. }
  90544. else {
  90545. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  90546. this._onBeforeParticlesRenderingObserver = null;
  90547. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  90548. this._onAfterParticlesRenderingObserver = null;
  90549. }
  90550. },
  90551. enumerable: true,
  90552. configurable: true
  90553. });
  90554. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  90555. /**
  90556. * Gets the perf counter used for sprites render time
  90557. */
  90558. get: function () {
  90559. return this._spritesRenderTime;
  90560. },
  90561. enumerable: true,
  90562. configurable: true
  90563. });
  90564. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  90565. /**
  90566. * Gets the sprites render time capture status
  90567. */
  90568. get: function () {
  90569. return this._captureSpritesRenderTime;
  90570. },
  90571. /**
  90572. * Enable or disable the sprites render time capture
  90573. */
  90574. set: function (value) {
  90575. var _this = this;
  90576. if (value === this._captureSpritesRenderTime) {
  90577. return;
  90578. }
  90579. this._captureSpritesRenderTime = value;
  90580. if (value) {
  90581. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  90582. BABYLON.Tools.StartPerformanceCounter("Sprites");
  90583. _this._spritesRenderTime.beginMonitoring();
  90584. });
  90585. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  90586. BABYLON.Tools.EndPerformanceCounter("Sprites");
  90587. _this._spritesRenderTime.endMonitoring(false);
  90588. });
  90589. }
  90590. else {
  90591. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  90592. this._onBeforeSpritesRenderingObserver = null;
  90593. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  90594. this._onAfterSpritesRenderingObserver = null;
  90595. }
  90596. },
  90597. enumerable: true,
  90598. configurable: true
  90599. });
  90600. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  90601. /**
  90602. * Gets the perf counter used for physics time
  90603. */
  90604. get: function () {
  90605. return this._physicsTime;
  90606. },
  90607. enumerable: true,
  90608. configurable: true
  90609. });
  90610. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  90611. /**
  90612. * Gets the physics time capture status
  90613. */
  90614. get: function () {
  90615. return this._capturePhysicsTime;
  90616. },
  90617. /**
  90618. * Enable or disable the physics time capture
  90619. */
  90620. set: function (value) {
  90621. var _this = this;
  90622. if (value === this._capturePhysicsTime) {
  90623. return;
  90624. }
  90625. this._capturePhysicsTime = value;
  90626. if (value) {
  90627. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  90628. BABYLON.Tools.StartPerformanceCounter("Physics");
  90629. _this._physicsTime.beginMonitoring();
  90630. });
  90631. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  90632. BABYLON.Tools.EndPerformanceCounter("Physics");
  90633. _this._physicsTime.endMonitoring();
  90634. });
  90635. }
  90636. else {
  90637. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  90638. this._onBeforePhysicsObserver = null;
  90639. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  90640. this._onAfterPhysicsObserver = null;
  90641. }
  90642. },
  90643. enumerable: true,
  90644. configurable: true
  90645. });
  90646. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  90647. /**
  90648. * Gets the perf counter used for animations time
  90649. */
  90650. get: function () {
  90651. return this._animationsTime;
  90652. },
  90653. enumerable: true,
  90654. configurable: true
  90655. });
  90656. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  90657. /**
  90658. * Gets the animations time capture status
  90659. */
  90660. get: function () {
  90661. return this._captureAnimationsTime;
  90662. },
  90663. /**
  90664. * Enable or disable the animations time capture
  90665. */
  90666. set: function (value) {
  90667. var _this = this;
  90668. if (value === this._captureAnimationsTime) {
  90669. return;
  90670. }
  90671. this._captureAnimationsTime = value;
  90672. if (value) {
  90673. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  90674. _this._animationsTime.endMonitoring();
  90675. });
  90676. }
  90677. else {
  90678. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  90679. this._onAfterAnimationsObserver = null;
  90680. }
  90681. },
  90682. enumerable: true,
  90683. configurable: true
  90684. });
  90685. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  90686. /**
  90687. * Gets the perf counter used for frame time capture
  90688. */
  90689. get: function () {
  90690. return this._frameTime;
  90691. },
  90692. enumerable: true,
  90693. configurable: true
  90694. });
  90695. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  90696. /**
  90697. * Gets the frame time capture status
  90698. */
  90699. get: function () {
  90700. return this._captureFrameTime;
  90701. },
  90702. /**
  90703. * Enable or disable the frame time capture
  90704. */
  90705. set: function (value) {
  90706. this._captureFrameTime = value;
  90707. },
  90708. enumerable: true,
  90709. configurable: true
  90710. });
  90711. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  90712. /**
  90713. * Gets the perf counter used for inter-frames time capture
  90714. */
  90715. get: function () {
  90716. return this._interFrameTime;
  90717. },
  90718. enumerable: true,
  90719. configurable: true
  90720. });
  90721. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  90722. /**
  90723. * Gets the inter-frames time capture status
  90724. */
  90725. get: function () {
  90726. return this._captureInterFrameTime;
  90727. },
  90728. /**
  90729. * Enable or disable the inter-frames time capture
  90730. */
  90731. set: function (value) {
  90732. this._captureInterFrameTime = value;
  90733. },
  90734. enumerable: true,
  90735. configurable: true
  90736. });
  90737. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  90738. /**
  90739. * Gets the perf counter used for render time capture
  90740. */
  90741. get: function () {
  90742. return this._renderTime;
  90743. },
  90744. enumerable: true,
  90745. configurable: true
  90746. });
  90747. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  90748. /**
  90749. * Gets the render time capture status
  90750. */
  90751. get: function () {
  90752. return this._captureRenderTime;
  90753. },
  90754. /**
  90755. * Enable or disable the render time capture
  90756. */
  90757. set: function (value) {
  90758. var _this = this;
  90759. if (value === this._captureRenderTime) {
  90760. return;
  90761. }
  90762. this._captureRenderTime = value;
  90763. if (value) {
  90764. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  90765. _this._renderTime.beginMonitoring();
  90766. BABYLON.Tools.StartPerformanceCounter("Main render");
  90767. });
  90768. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  90769. _this._renderTime.endMonitoring(false);
  90770. BABYLON.Tools.EndPerformanceCounter("Main render");
  90771. });
  90772. }
  90773. else {
  90774. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  90775. this._onBeforeDrawPhaseObserver = null;
  90776. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  90777. this._onAfterDrawPhaseObserver = null;
  90778. }
  90779. },
  90780. enumerable: true,
  90781. configurable: true
  90782. });
  90783. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  90784. /**
  90785. * Gets the perf counter used for draw calls
  90786. */
  90787. get: function () {
  90788. return this.scene.getEngine()._drawCalls;
  90789. },
  90790. enumerable: true,
  90791. configurable: true
  90792. });
  90793. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  90794. /**
  90795. * Gets the perf counter used for texture collisions
  90796. */
  90797. get: function () {
  90798. return this.scene.getEngine()._textureCollisions;
  90799. },
  90800. enumerable: true,
  90801. configurable: true
  90802. });
  90803. SceneInstrumentation.prototype.dispose = function () {
  90804. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  90805. this._onAfterRenderObserver = null;
  90806. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  90807. this._onBeforeActiveMeshesEvaluationObserver = null;
  90808. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  90809. this._onAfterActiveMeshesEvaluationObserver = null;
  90810. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  90811. this._onBeforeRenderTargetsRenderObserver = null;
  90812. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  90813. this._onAfterRenderTargetsRenderObserver = null;
  90814. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  90815. this._onBeforeAnimationsObserver = null;
  90816. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  90817. this._onBeforeParticlesRenderingObserver = null;
  90818. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  90819. this._onAfterParticlesRenderingObserver = null;
  90820. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  90821. this._onBeforeSpritesRenderingObserver = null;
  90822. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  90823. this._onAfterSpritesRenderingObserver = null;
  90824. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  90825. this._onBeforeDrawPhaseObserver = null;
  90826. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  90827. this._onAfterDrawPhaseObserver = null;
  90828. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  90829. this._onBeforePhysicsObserver = null;
  90830. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  90831. this._onAfterPhysicsObserver = null;
  90832. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  90833. this._onAfterAnimationsObserver = null;
  90834. this.scene = null;
  90835. };
  90836. return SceneInstrumentation;
  90837. }());
  90838. BABYLON.SceneInstrumentation = SceneInstrumentation;
  90839. })(BABYLON || (BABYLON = {}));
  90840. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  90841. "use strict";
  90842. var BABYLON;
  90843. (function (BABYLON) {
  90844. var _TimeToken = /** @class */ (function () {
  90845. function _TimeToken() {
  90846. this._timeElapsedQueryEnded = false;
  90847. }
  90848. return _TimeToken;
  90849. }());
  90850. BABYLON._TimeToken = _TimeToken;
  90851. })(BABYLON || (BABYLON = {}));
  90852. //# sourceMappingURL=babylon.timeToken.js.map
  90853. "use strict";
  90854. var BABYLON;
  90855. (function (BABYLON) {
  90856. /**
  90857. * Background material defines definition.
  90858. * @ignore Mainly internal Use
  90859. */
  90860. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  90861. __extends(BackgroundMaterialDefines, _super);
  90862. /**
  90863. * Constructor of the defines.
  90864. */
  90865. function BackgroundMaterialDefines() {
  90866. var _this = _super.call(this) || this;
  90867. /**
  90868. * True if the diffuse texture is in use.
  90869. */
  90870. _this.DIFFUSE = false;
  90871. /**
  90872. * The direct UV channel to use.
  90873. */
  90874. _this.DIFFUSEDIRECTUV = 0;
  90875. /**
  90876. * True if the diffuse texture is in gamma space.
  90877. */
  90878. _this.GAMMADIFFUSE = false;
  90879. /**
  90880. * True if the diffuse texture has opacity in the alpha channel.
  90881. */
  90882. _this.DIFFUSEHASALPHA = false;
  90883. /**
  90884. * True if you want the material to fade to transparent at grazing angle.
  90885. */
  90886. _this.OPACITYFRESNEL = false;
  90887. /**
  90888. * True if an extra blur needs to be added in the reflection.
  90889. */
  90890. _this.REFLECTIONBLUR = false;
  90891. /**
  90892. * True if you want the material to fade to reflection at grazing angle.
  90893. */
  90894. _this.REFLECTIONFRESNEL = false;
  90895. /**
  90896. * True if you want the material to falloff as far as you move away from the scene center.
  90897. */
  90898. _this.REFLECTIONFALLOFF = false;
  90899. /**
  90900. * False if the current Webgl implementation does not support the texture lod extension.
  90901. */
  90902. _this.TEXTURELODSUPPORT = false;
  90903. /**
  90904. * True to ensure the data are premultiplied.
  90905. */
  90906. _this.PREMULTIPLYALPHA = false;
  90907. /**
  90908. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  90909. */
  90910. _this.USERGBCOLOR = false;
  90911. /**
  90912. * True to add noise in order to reduce the banding effect.
  90913. */
  90914. _this.NOISE = false;
  90915. /**
  90916. * is the reflection texture in BGR color scheme?
  90917. * Mainly used to solve a bug in ios10 video tag
  90918. */
  90919. _this.REFLECTIONBGR = false;
  90920. _this.IMAGEPROCESSING = false;
  90921. _this.VIGNETTE = false;
  90922. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  90923. _this.VIGNETTEBLENDMODEOPAQUE = false;
  90924. _this.TONEMAPPING = false;
  90925. _this.CONTRAST = false;
  90926. _this.COLORCURVES = false;
  90927. _this.COLORGRADING = false;
  90928. _this.COLORGRADING3D = false;
  90929. _this.SAMPLER3DGREENDEPTH = false;
  90930. _this.SAMPLER3DBGRMAP = false;
  90931. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  90932. _this.EXPOSURE = false;
  90933. _this.GRAIN = false;
  90934. // Reflection.
  90935. _this.REFLECTION = false;
  90936. _this.REFLECTIONMAP_3D = false;
  90937. _this.REFLECTIONMAP_SPHERICAL = false;
  90938. _this.REFLECTIONMAP_PLANAR = false;
  90939. _this.REFLECTIONMAP_CUBIC = false;
  90940. _this.REFLECTIONMAP_PROJECTION = false;
  90941. _this.REFLECTIONMAP_SKYBOX = false;
  90942. _this.REFLECTIONMAP_EXPLICIT = false;
  90943. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  90944. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  90945. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  90946. _this.INVERTCUBICMAP = false;
  90947. _this.REFLECTIONMAP_OPPOSITEZ = false;
  90948. _this.LODINREFLECTIONALPHA = false;
  90949. _this.GAMMAREFLECTION = false;
  90950. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  90951. // Default BJS.
  90952. _this.MAINUV1 = false;
  90953. _this.MAINUV2 = false;
  90954. _this.UV1 = false;
  90955. _this.UV2 = false;
  90956. _this.CLIPPLANE = false;
  90957. _this.POINTSIZE = false;
  90958. _this.FOG = false;
  90959. _this.NORMAL = false;
  90960. _this.NUM_BONE_INFLUENCERS = 0;
  90961. _this.BonesPerMesh = 0;
  90962. _this.INSTANCES = false;
  90963. _this.SHADOWFLOAT = false;
  90964. _this.rebuild();
  90965. return _this;
  90966. }
  90967. return BackgroundMaterialDefines;
  90968. }(BABYLON.MaterialDefines));
  90969. /**
  90970. * Background material used to create an efficient environement around your scene.
  90971. */
  90972. var BackgroundMaterial = /** @class */ (function (_super) {
  90973. __extends(BackgroundMaterial, _super);
  90974. /**
  90975. * Instantiates a Background Material in the given scene
  90976. * @param name The friendly name of the material
  90977. * @param scene The scene to add the material to
  90978. */
  90979. function BackgroundMaterial(name, scene) {
  90980. var _this = _super.call(this, name, scene) || this;
  90981. /**
  90982. * Key light Color (multiply against the R channel of the environement texture)
  90983. */
  90984. _this.primaryColor = BABYLON.Color3.White();
  90985. /**
  90986. * Key light Level (allowing HDR output of the background)
  90987. */
  90988. _this.primaryLevel = 1;
  90989. /**
  90990. * Secondary light Color (multiply against the G channel of the environement texture)
  90991. */
  90992. _this.secondaryColor = BABYLON.Color3.Gray();
  90993. /**
  90994. * Secondary light Level (allowing HDR output of the background)
  90995. */
  90996. _this.secondaryLevel = 1;
  90997. /**
  90998. * Tertiary light Color (multiply against the B channel of the environement texture)
  90999. */
  91000. _this.tertiaryColor = BABYLON.Color3.Black();
  91001. /**
  91002. * Tertiary light Level (allowing HDR output of the background)
  91003. */
  91004. _this.tertiaryLevel = 1;
  91005. /**
  91006. * Reflection Texture used in the material.
  91007. * Should be author in a specific way for the best result (refer to the documentation).
  91008. */
  91009. _this.reflectionTexture = null;
  91010. /**
  91011. * Reflection Texture level of blur.
  91012. *
  91013. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  91014. * texture twice.
  91015. */
  91016. _this.reflectionBlur = 0;
  91017. /**
  91018. * Diffuse Texture used in the material.
  91019. * Should be author in a specific way for the best result (refer to the documentation).
  91020. */
  91021. _this.diffuseTexture = null;
  91022. _this._shadowLights = null;
  91023. /**
  91024. * Specify the list of lights casting shadow on the material.
  91025. * All scene shadow lights will be included if null.
  91026. */
  91027. _this.shadowLights = null;
  91028. /**
  91029. * For the lights having a blurred shadow generator, this can add a second blur pass in order to reach
  91030. * soft lighting on the background.
  91031. */
  91032. _this.shadowBlurScale = 1;
  91033. /**
  91034. * Helps adjusting the shadow to a softer level if required.
  91035. * 0 means black shadows and 1 means no shadows.
  91036. */
  91037. _this.shadowLevel = 0;
  91038. /**
  91039. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  91040. * It is usually zero but might be interesting to modify according to your setup.
  91041. */
  91042. _this.sceneCenter = BABYLON.Vector3.Zero();
  91043. /**
  91044. * This helps specifying that the material is falling off to the sky box at grazing angle.
  91045. * This helps ensuring a nice transition when the camera goes under the ground.
  91046. */
  91047. _this.opacityFresnel = true;
  91048. /**
  91049. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  91050. * This helps adding a mirror texture on the ground.
  91051. */
  91052. _this.reflectionFresnel = false;
  91053. /**
  91054. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  91055. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  91056. */
  91057. _this.reflectionFalloffDistance = 0.0;
  91058. /**
  91059. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  91060. */
  91061. _this.reflectionAmount = 1.0;
  91062. /**
  91063. * This specifies the weight of the reflection at grazing angle.
  91064. */
  91065. _this.reflectionReflectance0 = 0.05;
  91066. /**
  91067. * This specifies the weight of the reflection at a perpendicular point of view.
  91068. */
  91069. _this.reflectionReflectance90 = 0.5;
  91070. /**
  91071. * Helps to directly use the maps channels instead of their level.
  91072. */
  91073. _this.useRGBColor = true;
  91074. /**
  91075. * This helps reducing the banding effect that could occur on the background.
  91076. */
  91077. _this.enableNoise = false;
  91078. _this._fovMultiplier = 1.0;
  91079. /**
  91080. * Enable the FOV adjustment feature controlled by fovMultiplier.
  91081. * @type {boolean}
  91082. */
  91083. _this.useEquirectangularFOV = false;
  91084. _this._maxSimultaneousLights = 4;
  91085. /**
  91086. * Number of Simultaneous lights allowed on the material.
  91087. */
  91088. _this.maxSimultaneousLights = 4;
  91089. /**
  91090. * Keep track of the image processing observer to allow dispose and replace.
  91091. */
  91092. _this._imageProcessingObserver = null;
  91093. /**
  91094. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  91095. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  91096. */
  91097. _this.switchToBGR = false;
  91098. // Temp values kept as cache in the material.
  91099. _this._renderTargets = new BABYLON.SmartArray(16);
  91100. _this._reflectionControls = BABYLON.Vector4.Zero();
  91101. // Setup the default processing configuration to the scene.
  91102. _this._attachImageProcessingConfiguration(null);
  91103. _this.getRenderTargetTextures = function () {
  91104. _this._renderTargets.reset();
  91105. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  91106. _this._renderTargets.push(_this._diffuseTexture);
  91107. }
  91108. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  91109. _this._renderTargets.push(_this._reflectionTexture);
  91110. }
  91111. return _this._renderTargets;
  91112. };
  91113. return _this;
  91114. }
  91115. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  91116. /**
  91117. * Sets the reflection reflectance fresnel values according to the default standard
  91118. * empirically know to work well :-)
  91119. */
  91120. set: function (value) {
  91121. var reflectionWeight = value;
  91122. if (reflectionWeight < 0.5) {
  91123. reflectionWeight = reflectionWeight * 2.0;
  91124. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  91125. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  91126. }
  91127. else {
  91128. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  91129. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  91130. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  91131. }
  91132. },
  91133. enumerable: true,
  91134. configurable: true
  91135. });
  91136. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  91137. /**
  91138. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  91139. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  91140. * Recommended to be keep at 1.0 except for special cases.
  91141. */
  91142. get: function () {
  91143. return this._fovMultiplier;
  91144. },
  91145. set: function (value) {
  91146. if (isNaN(value)) {
  91147. value = 1.0;
  91148. }
  91149. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  91150. },
  91151. enumerable: true,
  91152. configurable: true
  91153. });
  91154. /**
  91155. * Attaches a new image processing configuration to the PBR Material.
  91156. * @param configuration (if null the scene configuration will be use)
  91157. */
  91158. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  91159. var _this = this;
  91160. if (configuration === this._imageProcessingConfiguration) {
  91161. return;
  91162. }
  91163. // Detaches observer.
  91164. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  91165. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  91166. }
  91167. // Pick the scene configuration if needed.
  91168. if (!configuration) {
  91169. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  91170. }
  91171. else {
  91172. this._imageProcessingConfiguration = configuration;
  91173. }
  91174. // Attaches observer.
  91175. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  91176. _this._markAllSubMeshesAsImageProcessingDirty();
  91177. });
  91178. };
  91179. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  91180. /**
  91181. * Gets the image processing configuration used either in this material.
  91182. */
  91183. get: function () {
  91184. return this._imageProcessingConfiguration;
  91185. },
  91186. /**
  91187. * Sets the Default image processing configuration used either in the this material.
  91188. *
  91189. * If sets to null, the scene one is in use.
  91190. */
  91191. set: function (value) {
  91192. this._attachImageProcessingConfiguration(value);
  91193. // Ensure the effect will be rebuilt.
  91194. this._markAllSubMeshesAsTexturesDirty();
  91195. },
  91196. enumerable: true,
  91197. configurable: true
  91198. });
  91199. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  91200. /**
  91201. * Gets wether the color curves effect is enabled.
  91202. */
  91203. get: function () {
  91204. return this.imageProcessingConfiguration.colorCurvesEnabled;
  91205. },
  91206. /**
  91207. * Sets wether the color curves effect is enabled.
  91208. */
  91209. set: function (value) {
  91210. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  91211. },
  91212. enumerable: true,
  91213. configurable: true
  91214. });
  91215. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  91216. /**
  91217. * Gets wether the color grading effect is enabled.
  91218. */
  91219. get: function () {
  91220. return this.imageProcessingConfiguration.colorGradingEnabled;
  91221. },
  91222. /**
  91223. * Gets wether the color grading effect is enabled.
  91224. */
  91225. set: function (value) {
  91226. this.imageProcessingConfiguration.colorGradingEnabled = value;
  91227. },
  91228. enumerable: true,
  91229. configurable: true
  91230. });
  91231. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  91232. /**
  91233. * Gets wether tonemapping is enabled or not.
  91234. */
  91235. get: function () {
  91236. return this._imageProcessingConfiguration.toneMappingEnabled;
  91237. },
  91238. /**
  91239. * Sets wether tonemapping is enabled or not
  91240. */
  91241. set: function (value) {
  91242. this._imageProcessingConfiguration.toneMappingEnabled = value;
  91243. },
  91244. enumerable: true,
  91245. configurable: true
  91246. });
  91247. ;
  91248. ;
  91249. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  91250. /**
  91251. * The camera exposure used on this material.
  91252. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  91253. * This corresponds to a photographic exposure.
  91254. */
  91255. get: function () {
  91256. return this._imageProcessingConfiguration.exposure;
  91257. },
  91258. /**
  91259. * The camera exposure used on this material.
  91260. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  91261. * This corresponds to a photographic exposure.
  91262. */
  91263. set: function (value) {
  91264. this._imageProcessingConfiguration.exposure = value;
  91265. },
  91266. enumerable: true,
  91267. configurable: true
  91268. });
  91269. ;
  91270. ;
  91271. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  91272. /**
  91273. * Gets The camera contrast used on this material.
  91274. */
  91275. get: function () {
  91276. return this._imageProcessingConfiguration.contrast;
  91277. },
  91278. /**
  91279. * Sets The camera contrast used on this material.
  91280. */
  91281. set: function (value) {
  91282. this._imageProcessingConfiguration.contrast = value;
  91283. },
  91284. enumerable: true,
  91285. configurable: true
  91286. });
  91287. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  91288. /**
  91289. * Gets the Color Grading 2D Lookup Texture.
  91290. */
  91291. get: function () {
  91292. return this._imageProcessingConfiguration.colorGradingTexture;
  91293. },
  91294. /**
  91295. * Sets the Color Grading 2D Lookup Texture.
  91296. */
  91297. set: function (value) {
  91298. this.imageProcessingConfiguration.colorGradingTexture = value;
  91299. },
  91300. enumerable: true,
  91301. configurable: true
  91302. });
  91303. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  91304. /**
  91305. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  91306. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  91307. * 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;
  91308. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  91309. */
  91310. get: function () {
  91311. return this.imageProcessingConfiguration.colorCurves;
  91312. },
  91313. /**
  91314. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  91315. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  91316. * 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;
  91317. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  91318. */
  91319. set: function (value) {
  91320. this.imageProcessingConfiguration.colorCurves = value;
  91321. },
  91322. enumerable: true,
  91323. configurable: true
  91324. });
  91325. /**
  91326. * The entire material has been created in order to prevent overdraw.
  91327. * @returns false
  91328. */
  91329. BackgroundMaterial.prototype.needAlphaTesting = function () {
  91330. return true;
  91331. };
  91332. /**
  91333. * The entire material has been created in order to prevent overdraw.
  91334. * @returns true if blending is enable
  91335. */
  91336. BackgroundMaterial.prototype.needAlphaBlending = function () {
  91337. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  91338. };
  91339. /**
  91340. * Checks wether the material is ready to be rendered for a given mesh.
  91341. * @param mesh The mesh to render
  91342. * @param subMesh The submesh to check against
  91343. * @param useInstances Specify wether or not the material is used with instances
  91344. * @returns true if all the dependencies are ready (Textures, Effects...)
  91345. */
  91346. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  91347. var _this = this;
  91348. if (useInstances === void 0) { useInstances = false; }
  91349. if (subMesh.effect && this.isFrozen) {
  91350. if (this._wasPreviouslyReady) {
  91351. return true;
  91352. }
  91353. }
  91354. if (!subMesh._materialDefines) {
  91355. subMesh._materialDefines = new BackgroundMaterialDefines();
  91356. }
  91357. var scene = this.getScene();
  91358. var defines = subMesh._materialDefines;
  91359. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  91360. if (defines._renderId === scene.getRenderId()) {
  91361. return true;
  91362. }
  91363. }
  91364. var engine = scene.getEngine();
  91365. // Lights
  91366. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  91367. defines._needNormals = true;
  91368. // Textures
  91369. if (defines._areTexturesDirty) {
  91370. defines._needUVs = false;
  91371. if (scene.texturesEnabled) {
  91372. if (scene.getEngine().getCaps().textureLOD) {
  91373. defines.TEXTURELODSUPPORT = true;
  91374. }
  91375. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  91376. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  91377. return false;
  91378. }
  91379. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  91380. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  91381. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  91382. defines.OPACITYFRESNEL = this._opacityFresnel;
  91383. }
  91384. else {
  91385. defines.DIFFUSE = false;
  91386. defines.DIFFUSEHASALPHA = false;
  91387. defines.GAMMADIFFUSE = false;
  91388. defines.OPACITYFRESNEL = false;
  91389. }
  91390. var reflectionTexture = this._reflectionTexture;
  91391. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  91392. if (!reflectionTexture.isReadyOrNotBlocking()) {
  91393. return false;
  91394. }
  91395. defines.REFLECTION = true;
  91396. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  91397. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  91398. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  91399. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  91400. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  91401. defines.REFLECTIONBGR = this.switchToBGR;
  91402. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  91403. defines.INVERTCUBICMAP = true;
  91404. }
  91405. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  91406. switch (reflectionTexture.coordinatesMode) {
  91407. case BABYLON.Texture.CUBIC_MODE:
  91408. case BABYLON.Texture.INVCUBIC_MODE:
  91409. defines.REFLECTIONMAP_CUBIC = true;
  91410. break;
  91411. case BABYLON.Texture.EXPLICIT_MODE:
  91412. defines.REFLECTIONMAP_EXPLICIT = true;
  91413. break;
  91414. case BABYLON.Texture.PLANAR_MODE:
  91415. defines.REFLECTIONMAP_PLANAR = true;
  91416. break;
  91417. case BABYLON.Texture.PROJECTION_MODE:
  91418. defines.REFLECTIONMAP_PROJECTION = true;
  91419. break;
  91420. case BABYLON.Texture.SKYBOX_MODE:
  91421. defines.REFLECTIONMAP_SKYBOX = true;
  91422. break;
  91423. case BABYLON.Texture.SPHERICAL_MODE:
  91424. defines.REFLECTIONMAP_SPHERICAL = true;
  91425. break;
  91426. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  91427. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  91428. break;
  91429. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  91430. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  91431. break;
  91432. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  91433. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  91434. break;
  91435. }
  91436. if (this.reflectionFresnel) {
  91437. defines.REFLECTIONFRESNEL = true;
  91438. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  91439. this._reflectionControls.x = this.reflectionAmount;
  91440. this._reflectionControls.y = this.reflectionReflectance0;
  91441. this._reflectionControls.z = this.reflectionReflectance90;
  91442. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  91443. }
  91444. else {
  91445. defines.REFLECTIONFRESNEL = false;
  91446. defines.REFLECTIONFALLOFF = false;
  91447. }
  91448. }
  91449. else {
  91450. defines.REFLECTION = false;
  91451. defines.REFLECTIONFALLOFF = false;
  91452. defines.REFLECTIONBLUR = false;
  91453. defines.REFLECTIONMAP_3D = false;
  91454. defines.REFLECTIONMAP_SPHERICAL = false;
  91455. defines.REFLECTIONMAP_PLANAR = false;
  91456. defines.REFLECTIONMAP_CUBIC = false;
  91457. defines.REFLECTIONMAP_PROJECTION = false;
  91458. defines.REFLECTIONMAP_SKYBOX = false;
  91459. defines.REFLECTIONMAP_EXPLICIT = false;
  91460. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  91461. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  91462. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  91463. defines.INVERTCUBICMAP = false;
  91464. defines.REFLECTIONMAP_OPPOSITEZ = false;
  91465. defines.LODINREFLECTIONALPHA = false;
  91466. defines.GAMMAREFLECTION = false;
  91467. }
  91468. }
  91469. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  91470. defines.USERGBCOLOR = this._useRGBColor;
  91471. defines.NOISE = this._enableNoise;
  91472. }
  91473. if (defines._areImageProcessingDirty) {
  91474. if (!this._imageProcessingConfiguration.isReady()) {
  91475. return false;
  91476. }
  91477. this._imageProcessingConfiguration.prepareDefines(defines);
  91478. }
  91479. // Misc.
  91480. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  91481. // Values that need to be evaluated on every frame
  91482. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  91483. // Attribs
  91484. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  91485. if (mesh) {
  91486. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  91487. mesh.createNormals(true);
  91488. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  91489. }
  91490. }
  91491. }
  91492. // Get correct effect
  91493. if (defines.isDirty) {
  91494. defines.markAsProcessed();
  91495. scene.resetCachedMaterial();
  91496. // Fallbacks
  91497. var fallbacks = new BABYLON.EffectFallbacks();
  91498. if (defines.FOG) {
  91499. fallbacks.addFallback(0, "FOG");
  91500. }
  91501. if (defines.POINTSIZE) {
  91502. fallbacks.addFallback(1, "POINTSIZE");
  91503. }
  91504. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  91505. if (defines.NUM_BONE_INFLUENCERS > 0) {
  91506. fallbacks.addCPUSkinningFallback(0, mesh);
  91507. }
  91508. //Attributes
  91509. var attribs = [BABYLON.VertexBuffer.PositionKind];
  91510. if (defines.NORMAL) {
  91511. attribs.push(BABYLON.VertexBuffer.NormalKind);
  91512. }
  91513. if (defines.UV1) {
  91514. attribs.push(BABYLON.VertexBuffer.UVKind);
  91515. }
  91516. if (defines.UV2) {
  91517. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  91518. }
  91519. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  91520. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  91521. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  91522. "vFogInfos", "vFogColor", "pointSize",
  91523. "vClipPlane", "mBones",
  91524. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  91525. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  91526. "shadowLevel", "alpha",
  91527. "vBackgroundCenter", "vReflectionControl",
  91528. "vDiffuseInfos", "diffuseMatrix",
  91529. ];
  91530. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  91531. var uniformBuffers = ["Material", "Scene"];
  91532. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  91533. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  91534. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  91535. uniformsNames: uniforms,
  91536. uniformBuffersNames: uniformBuffers,
  91537. samplers: samplers,
  91538. defines: defines,
  91539. maxSimultaneousLights: this._maxSimultaneousLights
  91540. });
  91541. var onCompiled = function (effect) {
  91542. if (_this.onCompiled) {
  91543. _this.onCompiled(effect);
  91544. }
  91545. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  91546. };
  91547. var join = defines.toString();
  91548. subMesh.setEffect(scene.getEngine().createEffect("background", {
  91549. attributes: attribs,
  91550. uniformsNames: uniforms,
  91551. uniformBuffersNames: uniformBuffers,
  91552. samplers: samplers,
  91553. defines: join,
  91554. fallbacks: fallbacks,
  91555. onCompiled: onCompiled,
  91556. onError: this.onError,
  91557. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  91558. }, engine), defines);
  91559. this.buildUniformLayout();
  91560. }
  91561. if (!subMesh.effect || !subMesh.effect.isReady()) {
  91562. return false;
  91563. }
  91564. defines._renderId = scene.getRenderId();
  91565. this._wasPreviouslyReady = true;
  91566. return true;
  91567. };
  91568. /**
  91569. * Build the uniform buffer used in the material.
  91570. */
  91571. BackgroundMaterial.prototype.buildUniformLayout = function () {
  91572. // Order is important !
  91573. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  91574. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  91575. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  91576. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  91577. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  91578. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  91579. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  91580. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  91581. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  91582. this._uniformBuffer.addUniform("pointSize", 1);
  91583. this._uniformBuffer.addUniform("shadowLevel", 1);
  91584. this._uniformBuffer.addUniform("alpha", 1);
  91585. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  91586. this._uniformBuffer.addUniform("vReflectionControl", 4);
  91587. this._uniformBuffer.create();
  91588. };
  91589. /**
  91590. * Unbind the material.
  91591. */
  91592. BackgroundMaterial.prototype.unbind = function () {
  91593. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  91594. this._uniformBuffer.setTexture("diffuseSampler", null);
  91595. }
  91596. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  91597. this._uniformBuffer.setTexture("reflectionSampler", null);
  91598. }
  91599. _super.prototype.unbind.call(this);
  91600. };
  91601. /**
  91602. * Bind only the world matrix to the material.
  91603. * @param world The world matrix to bind.
  91604. */
  91605. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  91606. this._activeEffect.setMatrix("world", world);
  91607. };
  91608. /**
  91609. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  91610. * @param world The world matrix to bind.
  91611. * @param subMesh The submesh to bind for.
  91612. */
  91613. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  91614. var scene = this.getScene();
  91615. var defines = subMesh._materialDefines;
  91616. if (!defines) {
  91617. return;
  91618. }
  91619. var effect = subMesh.effect;
  91620. if (!effect) {
  91621. return;
  91622. }
  91623. this._activeEffect = effect;
  91624. // Matrices
  91625. this.bindOnlyWorldMatrix(world);
  91626. // Bones
  91627. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  91628. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  91629. if (mustRebind) {
  91630. this._uniformBuffer.bindToEffect(effect, "Material");
  91631. this.bindViewProjection(effect);
  91632. var reflectionTexture = this._reflectionTexture;
  91633. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  91634. // Texture uniforms
  91635. if (scene.texturesEnabled) {
  91636. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  91637. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  91638. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  91639. }
  91640. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  91641. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  91642. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  91643. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  91644. }
  91645. }
  91646. if (this.shadowLevel > 0) {
  91647. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  91648. }
  91649. this._uniformBuffer.updateFloat("alpha", this.alpha);
  91650. // Point size
  91651. if (this.pointsCloud) {
  91652. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  91653. }
  91654. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  91655. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  91656. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  91657. }
  91658. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  91659. // Textures
  91660. if (scene.texturesEnabled) {
  91661. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  91662. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  91663. }
  91664. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  91665. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  91666. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  91667. }
  91668. else if (!defines.REFLECTIONBLUR) {
  91669. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  91670. }
  91671. else {
  91672. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  91673. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  91674. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  91675. }
  91676. if (defines.REFLECTIONFRESNEL) {
  91677. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  91678. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  91679. }
  91680. }
  91681. }
  91682. // Clip plane
  91683. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  91684. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  91685. }
  91686. if (mustRebind || !this.isFrozen) {
  91687. if (scene.lightsEnabled) {
  91688. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  91689. }
  91690. // View
  91691. this.bindView(effect);
  91692. // Fog
  91693. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  91694. // image processing
  91695. this._imageProcessingConfiguration.bind(this._activeEffect);
  91696. }
  91697. this._uniformBuffer.update();
  91698. this._afterBind(mesh);
  91699. };
  91700. /**
  91701. * Dispose the material.
  91702. * @param forceDisposeEffect Force disposal of the associated effect.
  91703. * @param forceDisposeTextures Force disposal of the associated textures.
  91704. */
  91705. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  91706. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  91707. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  91708. if (forceDisposeTextures) {
  91709. if (this.diffuseTexture) {
  91710. this.diffuseTexture.dispose();
  91711. }
  91712. if (this.reflectionTexture) {
  91713. this.reflectionTexture.dispose();
  91714. }
  91715. }
  91716. this._renderTargets.dispose();
  91717. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  91718. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  91719. }
  91720. _super.prototype.dispose.call(this, forceDisposeEffect);
  91721. };
  91722. /**
  91723. * Clones the material.
  91724. * @param name The cloned name.
  91725. * @returns The cloned material.
  91726. */
  91727. BackgroundMaterial.prototype.clone = function (name) {
  91728. var _this = this;
  91729. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  91730. };
  91731. /**
  91732. * Serializes the current material to its JSON representation.
  91733. * @returns The JSON representation.
  91734. */
  91735. BackgroundMaterial.prototype.serialize = function () {
  91736. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  91737. serializationObject.customType = "BABYLON.BackgroundMaterial";
  91738. return serializationObject;
  91739. };
  91740. /**
  91741. * Gets the class name of the material
  91742. * @returns "BackgroundMaterial"
  91743. */
  91744. BackgroundMaterial.prototype.getClassName = function () {
  91745. return "BackgroundMaterial";
  91746. };
  91747. /**
  91748. * Parse a JSON input to create back a background material.
  91749. * @param source The JSON data to parse
  91750. * @param scene The scene to create the parsed material in
  91751. * @param rootUrl The root url of the assets the material depends upon
  91752. * @returns the instantiated BackgroundMaterial.
  91753. */
  91754. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  91755. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  91756. };
  91757. /**
  91758. * Standard reflectance value at parallel view angle.
  91759. */
  91760. BackgroundMaterial.StandardReflectance0 = 0.05;
  91761. /**
  91762. * Standard reflectance value at grazing angle.
  91763. */
  91764. BackgroundMaterial.StandardReflectance90 = 0.5;
  91765. __decorate([
  91766. BABYLON.serializeAsColor3()
  91767. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  91768. __decorate([
  91769. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  91770. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  91771. __decorate([
  91772. BABYLON.serialize()
  91773. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  91774. __decorate([
  91775. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  91776. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  91777. __decorate([
  91778. BABYLON.serializeAsColor3()
  91779. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  91780. __decorate([
  91781. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  91782. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  91783. __decorate([
  91784. BABYLON.serialize()
  91785. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  91786. __decorate([
  91787. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  91788. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  91789. __decorate([
  91790. BABYLON.serializeAsColor3()
  91791. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  91792. __decorate([
  91793. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  91794. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  91795. __decorate([
  91796. BABYLON.serialize()
  91797. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  91798. __decorate([
  91799. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  91800. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  91801. __decorate([
  91802. BABYLON.serializeAsTexture()
  91803. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  91804. __decorate([
  91805. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91806. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  91807. __decorate([
  91808. BABYLON.serialize()
  91809. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  91810. __decorate([
  91811. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91812. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  91813. __decorate([
  91814. BABYLON.serializeAsTexture()
  91815. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  91816. __decorate([
  91817. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91818. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  91819. __decorate([
  91820. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91821. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  91822. __decorate([
  91823. BABYLON.serialize()
  91824. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  91825. __decorate([
  91826. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91827. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  91828. __decorate([
  91829. BABYLON.serialize()
  91830. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  91831. __decorate([
  91832. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91833. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  91834. __decorate([
  91835. BABYLON.serializeAsVector3()
  91836. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  91837. __decorate([
  91838. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91839. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  91840. __decorate([
  91841. BABYLON.serialize()
  91842. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  91843. __decorate([
  91844. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91845. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  91846. __decorate([
  91847. BABYLON.serialize()
  91848. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  91849. __decorate([
  91850. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91851. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  91852. __decorate([
  91853. BABYLON.serialize()
  91854. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  91855. __decorate([
  91856. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91857. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  91858. __decorate([
  91859. BABYLON.serialize()
  91860. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  91861. __decorate([
  91862. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91863. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  91864. __decorate([
  91865. BABYLON.serialize()
  91866. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  91867. __decorate([
  91868. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91869. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  91870. __decorate([
  91871. BABYLON.serialize()
  91872. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  91873. __decorate([
  91874. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91875. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  91876. __decorate([
  91877. BABYLON.serialize()
  91878. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  91879. __decorate([
  91880. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91881. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  91882. __decorate([
  91883. BABYLON.serialize()
  91884. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  91885. __decorate([
  91886. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91887. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  91888. __decorate([
  91889. BABYLON.serialize()
  91890. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  91891. __decorate([
  91892. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91893. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  91894. __decorate([
  91895. BABYLON.serializeAsImageProcessingConfiguration()
  91896. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  91897. return BackgroundMaterial;
  91898. }(BABYLON.PushMaterial));
  91899. BABYLON.BackgroundMaterial = BackgroundMaterial;
  91900. })(BABYLON || (BABYLON = {}));
  91901. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  91902. "use strict";
  91903. var __assign = (this && this.__assign) || Object.assign || function(t) {
  91904. for (var s, i = 1, n = arguments.length; i < n; i++) {
  91905. s = arguments[i];
  91906. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  91907. t[p] = s[p];
  91908. }
  91909. return t;
  91910. };
  91911. var BABYLON;
  91912. (function (BABYLON) {
  91913. /**
  91914. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  91915. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  91916. * It also helps with the default setup of your imageProcessing configuration.
  91917. */
  91918. var EnvironmentHelper = /** @class */ (function () {
  91919. /**
  91920. * constructor
  91921. * @param options
  91922. * @param scene The scene to add the material to
  91923. */
  91924. function EnvironmentHelper(options, scene) {
  91925. var _this = this;
  91926. this._errorHandler = function (message, exception) {
  91927. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  91928. };
  91929. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  91930. this._scene = scene;
  91931. this.onErrorObservable = new BABYLON.Observable();
  91932. this._setupBackground();
  91933. this._setupImageProcessing();
  91934. }
  91935. /**
  91936. * Creates the default options for the helper.
  91937. */
  91938. EnvironmentHelper._getDefaultOptions = function () {
  91939. return {
  91940. createGround: true,
  91941. groundSize: 15,
  91942. groundTexture: this._groundTextureCDNUrl,
  91943. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  91944. groundOpacity: 0.9,
  91945. enableGroundShadow: true,
  91946. groundShadowLevel: 0.5,
  91947. enableGroundMirror: false,
  91948. groundMirrorSizeRatio: 0.3,
  91949. groundMirrorBlurKernel: 64,
  91950. groundMirrorAmount: 1,
  91951. groundMirrorFresnelWeight: 1,
  91952. groundMirrorFallOffDistance: 0,
  91953. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  91954. groundYBias: 0.00001,
  91955. createSkybox: true,
  91956. skyboxSize: 20,
  91957. skyboxTexture: this._skyboxTextureCDNUrl,
  91958. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  91959. backgroundYRotation: 0,
  91960. sizeAuto: true,
  91961. rootPosition: BABYLON.Vector3.Zero(),
  91962. setupImageProcessing: true,
  91963. environmentTexture: this._environmentTextureCDNUrl,
  91964. cameraExposure: 0.8,
  91965. cameraContrast: 1.2,
  91966. toneMappingEnabled: true,
  91967. };
  91968. };
  91969. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  91970. /**
  91971. * Gets the root mesh created by the helper.
  91972. */
  91973. get: function () {
  91974. return this._rootMesh;
  91975. },
  91976. enumerable: true,
  91977. configurable: true
  91978. });
  91979. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  91980. /**
  91981. * Gets the skybox created by the helper.
  91982. */
  91983. get: function () {
  91984. return this._skybox;
  91985. },
  91986. enumerable: true,
  91987. configurable: true
  91988. });
  91989. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  91990. /**
  91991. * Gets the skybox texture created by the helper.
  91992. */
  91993. get: function () {
  91994. return this._skyboxTexture;
  91995. },
  91996. enumerable: true,
  91997. configurable: true
  91998. });
  91999. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  92000. /**
  92001. * Gets the skybox material created by the helper.
  92002. */
  92003. get: function () {
  92004. return this._skyboxMaterial;
  92005. },
  92006. enumerable: true,
  92007. configurable: true
  92008. });
  92009. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  92010. /**
  92011. * Gets the ground mesh created by the helper.
  92012. */
  92013. get: function () {
  92014. return this._ground;
  92015. },
  92016. enumerable: true,
  92017. configurable: true
  92018. });
  92019. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  92020. /**
  92021. * Gets the ground texture created by the helper.
  92022. */
  92023. get: function () {
  92024. return this._groundTexture;
  92025. },
  92026. enumerable: true,
  92027. configurable: true
  92028. });
  92029. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  92030. /**
  92031. * Gets the ground mirror created by the helper.
  92032. */
  92033. get: function () {
  92034. return this._groundMirror;
  92035. },
  92036. enumerable: true,
  92037. configurable: true
  92038. });
  92039. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  92040. /**
  92041. * Gets the ground mirror render list to helps pushing the meshes
  92042. * you wish in the ground reflection.
  92043. */
  92044. get: function () {
  92045. if (this._groundMirror) {
  92046. return this._groundMirror.renderList;
  92047. }
  92048. return null;
  92049. },
  92050. enumerable: true,
  92051. configurable: true
  92052. });
  92053. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  92054. /**
  92055. * Gets the ground material created by the helper.
  92056. */
  92057. get: function () {
  92058. return this._groundMaterial;
  92059. },
  92060. enumerable: true,
  92061. configurable: true
  92062. });
  92063. /**
  92064. * Updates the background according to the new options
  92065. * @param options
  92066. */
  92067. EnvironmentHelper.prototype.updateOptions = function (options) {
  92068. var newOptions = __assign({}, this._options, options);
  92069. if (this._ground && !newOptions.createGround) {
  92070. this._ground.dispose();
  92071. this._ground = null;
  92072. }
  92073. if (this._groundMaterial && !newOptions.createGround) {
  92074. this._groundMaterial.dispose();
  92075. this._groundMaterial = null;
  92076. }
  92077. if (this._groundTexture) {
  92078. if (this._options.groundTexture != newOptions.groundTexture) {
  92079. this._groundTexture.dispose();
  92080. this._groundTexture = null;
  92081. }
  92082. }
  92083. if (this._skybox && !newOptions.createSkybox) {
  92084. this._skybox.dispose();
  92085. this._skybox = null;
  92086. }
  92087. if (this._skyboxMaterial && !newOptions.createSkybox) {
  92088. this._skyboxMaterial.dispose();
  92089. this._skyboxMaterial = null;
  92090. }
  92091. if (this._skyboxTexture) {
  92092. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  92093. this._skyboxTexture.dispose();
  92094. this._skyboxTexture = null;
  92095. }
  92096. }
  92097. if (this._groundMirror && !newOptions.enableGroundMirror) {
  92098. this._groundMirror.dispose();
  92099. this._groundMirror = null;
  92100. }
  92101. if (this._scene.environmentTexture) {
  92102. if (this._options.environmentTexture != newOptions.environmentTexture) {
  92103. this._scene.environmentTexture.dispose();
  92104. }
  92105. }
  92106. this._options = newOptions;
  92107. this._setupBackground();
  92108. this._setupImageProcessing();
  92109. };
  92110. /**
  92111. * Sets the primary color of all the available elements.
  92112. * @param color
  92113. */
  92114. EnvironmentHelper.prototype.setMainColor = function (color) {
  92115. if (this.groundMaterial) {
  92116. this.groundMaterial.primaryColor = color;
  92117. }
  92118. if (this.skyboxMaterial) {
  92119. this.skyboxMaterial.primaryColor = color;
  92120. }
  92121. if (this.groundMirror) {
  92122. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  92123. }
  92124. };
  92125. /**
  92126. * Setup the image processing according to the specified options.
  92127. */
  92128. EnvironmentHelper.prototype._setupImageProcessing = function () {
  92129. if (this._options.setupImageProcessing) {
  92130. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  92131. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  92132. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  92133. this._setupEnvironmentTexture();
  92134. }
  92135. };
  92136. /**
  92137. * Setup the environment texture according to the specified options.
  92138. */
  92139. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  92140. if (this._scene.environmentTexture) {
  92141. return;
  92142. }
  92143. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  92144. this._scene.environmentTexture = this._options.environmentTexture;
  92145. return;
  92146. }
  92147. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  92148. this._scene.environmentTexture = environmentTexture;
  92149. };
  92150. /**
  92151. * Setup the background according to the specified options.
  92152. */
  92153. EnvironmentHelper.prototype._setupBackground = function () {
  92154. if (!this._rootMesh) {
  92155. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  92156. }
  92157. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  92158. var sceneSize = this._getSceneSize();
  92159. if (this._options.createGround) {
  92160. this._setupGround(sceneSize);
  92161. this._setupGroundMaterial();
  92162. this._setupGroundDiffuseTexture();
  92163. if (this._options.enableGroundMirror) {
  92164. this._setupGroundMirrorTexture(sceneSize);
  92165. }
  92166. this._setupMirrorInGroundMaterial();
  92167. }
  92168. if (this._options.createSkybox) {
  92169. this._setupSkybox(sceneSize);
  92170. this._setupSkyboxMaterial();
  92171. this._setupSkyboxReflectionTexture();
  92172. }
  92173. this._rootMesh.position.x = sceneSize.rootPosition.x;
  92174. this._rootMesh.position.z = sceneSize.rootPosition.z;
  92175. this._rootMesh.position.y = sceneSize.rootPosition.y;
  92176. };
  92177. /**
  92178. * Get the scene sizes according to the setup.
  92179. */
  92180. EnvironmentHelper.prototype._getSceneSize = function () {
  92181. var _this = this;
  92182. var groundSize = this._options.groundSize;
  92183. var skyboxSize = this._options.skyboxSize;
  92184. var rootPosition = this._options.rootPosition;
  92185. if (!this._scene.meshes || this._scene.meshes.length === 1) {
  92186. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  92187. }
  92188. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  92189. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  92190. });
  92191. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  92192. if (this._options.sizeAuto) {
  92193. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  92194. this._scene.activeCamera.upperRadiusLimit) {
  92195. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  92196. skyboxSize = groundSize;
  92197. }
  92198. var sceneDiagonalLenght = sceneDiagonal.length();
  92199. if (sceneDiagonalLenght > groundSize) {
  92200. groundSize = sceneDiagonalLenght * 2;
  92201. skyboxSize = groundSize;
  92202. }
  92203. // 10 % bigger.
  92204. groundSize *= 1.1;
  92205. skyboxSize *= 1.5;
  92206. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  92207. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  92208. }
  92209. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  92210. };
  92211. /**
  92212. * Setup the ground according to the specified options.
  92213. */
  92214. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  92215. var _this = this;
  92216. if (!this._ground) {
  92217. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  92218. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  92219. this._ground.parent = this._rootMesh;
  92220. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  92221. }
  92222. this._ground.receiveShadows = this._options.enableGroundShadow;
  92223. };
  92224. /**
  92225. * Setup the ground material according to the specified options.
  92226. */
  92227. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  92228. if (!this._groundMaterial) {
  92229. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  92230. }
  92231. this._groundMaterial.alpha = this._options.groundOpacity;
  92232. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  92233. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  92234. this._groundMaterial.primaryLevel = 1;
  92235. this._groundMaterial.primaryColor = this._options.groundColor;
  92236. this._groundMaterial.secondaryLevel = 0;
  92237. this._groundMaterial.tertiaryLevel = 0;
  92238. this._groundMaterial.useRGBColor = false;
  92239. this._groundMaterial.enableNoise = true;
  92240. if (this._ground) {
  92241. this._ground.material = this._groundMaterial;
  92242. }
  92243. };
  92244. /**
  92245. * Setup the ground diffuse texture according to the specified options.
  92246. */
  92247. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  92248. if (!this._groundMaterial) {
  92249. return;
  92250. }
  92251. if (this._groundTexture) {
  92252. return;
  92253. }
  92254. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  92255. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  92256. return;
  92257. }
  92258. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  92259. diffuseTexture.gammaSpace = false;
  92260. diffuseTexture.hasAlpha = true;
  92261. this._groundMaterial.diffuseTexture = diffuseTexture;
  92262. };
  92263. /**
  92264. * Setup the ground mirror texture according to the specified options.
  92265. */
  92266. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  92267. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92268. if (!this._groundMirror) {
  92269. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  92270. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  92271. this._groundMirror.anisotropicFilteringLevel = 1;
  92272. this._groundMirror.wrapU = wrapping;
  92273. this._groundMirror.wrapV = wrapping;
  92274. this._groundMirror.gammaSpace = false;
  92275. if (this._groundMirror.renderList) {
  92276. for (var i = 0; i < this._scene.meshes.length; i++) {
  92277. var mesh = this._scene.meshes[i];
  92278. if (mesh !== this._ground &&
  92279. mesh !== this._skybox &&
  92280. mesh !== this._rootMesh) {
  92281. this._groundMirror.renderList.push(mesh);
  92282. }
  92283. }
  92284. }
  92285. }
  92286. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  92287. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  92288. };
  92289. /**
  92290. * Setup the ground to receive the mirror texture.
  92291. */
  92292. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  92293. if (this._groundMaterial) {
  92294. this._groundMaterial.reflectionTexture = this._groundMirror;
  92295. this._groundMaterial.reflectionFresnel = true;
  92296. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  92297. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  92298. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  92299. }
  92300. };
  92301. /**
  92302. * Setup the skybox according to the specified options.
  92303. */
  92304. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  92305. var _this = this;
  92306. if (!this._skybox) {
  92307. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  92308. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  92309. }
  92310. this._skybox.parent = this._rootMesh;
  92311. };
  92312. /**
  92313. * Setup the skybox material according to the specified options.
  92314. */
  92315. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  92316. if (!this._skybox) {
  92317. return;
  92318. }
  92319. if (!this._skyboxMaterial) {
  92320. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  92321. }
  92322. this._skyboxMaterial.useRGBColor = false;
  92323. this._skyboxMaterial.primaryLevel = 1;
  92324. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  92325. this._skyboxMaterial.secondaryLevel = 0;
  92326. this._skyboxMaterial.tertiaryLevel = 0;
  92327. this._skyboxMaterial.enableNoise = true;
  92328. this._skybox.material = this._skyboxMaterial;
  92329. };
  92330. /**
  92331. * Setup the skybox reflection texture according to the specified options.
  92332. */
  92333. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  92334. if (!this._skyboxMaterial) {
  92335. return;
  92336. }
  92337. if (this._skyboxTexture) {
  92338. return;
  92339. }
  92340. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  92341. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  92342. return;
  92343. }
  92344. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  92345. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  92346. this._skyboxTexture.gammaSpace = false;
  92347. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  92348. };
  92349. /**
  92350. * Dispose all the elements created by the Helper.
  92351. */
  92352. EnvironmentHelper.prototype.dispose = function () {
  92353. if (this._groundMaterial) {
  92354. this._groundMaterial.dispose(true, true);
  92355. }
  92356. if (this._skyboxMaterial) {
  92357. this._skyboxMaterial.dispose(true, true);
  92358. }
  92359. this._rootMesh.dispose(false);
  92360. };
  92361. /**
  92362. * Default ground texture URL.
  92363. */
  92364. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  92365. /**
  92366. * Default skybox texture URL.
  92367. */
  92368. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  92369. /**
  92370. * Default environment texture URL.
  92371. */
  92372. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  92373. return EnvironmentHelper;
  92374. }());
  92375. BABYLON.EnvironmentHelper = EnvironmentHelper;
  92376. })(BABYLON || (BABYLON = {}));
  92377. //# sourceMappingURL=babylon.environmentHelper.js.map
  92378. "use strict";
  92379. var BABYLON;
  92380. (function (BABYLON) {
  92381. /**
  92382. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  92383. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  92384. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  92385. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  92386. */
  92387. var VideoDome = /** @class */ (function (_super) {
  92388. __extends(VideoDome, _super);
  92389. /**
  92390. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  92391. * @param name Element's name, child elements will append suffixes for their own names.
  92392. * @param urlsOrVideo
  92393. * @param options An object containing optional or exposed sub element properties:
  92394. * @param options **resolution=12** Integer, lower resolutions have more artifacts at extreme fovs
  92395. * @param options **clickToPlay=false** Add a click to play listener to the video, does not prevent autoplay.
  92396. * @param options **autoPlay=true** Automatically attempt to being playing the video.
  92397. * @param options **loop=true** Automatically loop video on end.
  92398. * @param options **size=1000** Physical radius to create the dome at, defaults to approximately half the far clip plane.
  92399. */
  92400. function VideoDome(name, urlsOrVideo, options, scene) {
  92401. var _this = _super.call(this, name, scene) || this;
  92402. // set defaults and manage values
  92403. name = name || "videoDome";
  92404. options.resolution = (Math.abs(options.resolution) | 0) || 12;
  92405. options.clickToPlay = Boolean(options.clickToPlay);
  92406. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  92407. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  92408. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  92409. // create
  92410. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true };
  92411. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  92412. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  92413. _this._mesh = BABYLON.MeshBuilder.CreateIcoSphere(name + "_mesh", {
  92414. flat: false,
  92415. radius: options.size,
  92416. subdivisions: options.resolution,
  92417. sideOrientation: BABYLON.Mesh.BACKSIDE // needs to be inside out
  92418. }, scene);
  92419. // configure material
  92420. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  92421. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; // always clamp the up/down
  92422. material.reflectionTexture = _this._videoTexture;
  92423. material.useEquirectangularFOV = true;
  92424. material.fovMultiplier = 1.0;
  92425. // configure mesh
  92426. _this._mesh.material = material;
  92427. _this._mesh.parent = _this;
  92428. // optional configuration
  92429. if (options.clickToPlay) {
  92430. scene.onPointerUp = function () {
  92431. _this._videoTexture.video.play();
  92432. };
  92433. }
  92434. return _this;
  92435. }
  92436. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  92437. /**
  92438. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  92439. * Also see the options.resolution property.
  92440. */
  92441. get: function () {
  92442. return this._material.fovMultiplier;
  92443. },
  92444. set: function (value) {
  92445. this._material.fovMultiplier = value;
  92446. },
  92447. enumerable: true,
  92448. configurable: true
  92449. });
  92450. /**
  92451. * Releases resources associated with this node.
  92452. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  92453. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  92454. */
  92455. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  92456. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  92457. this._videoTexture.dispose();
  92458. this._mesh.dispose();
  92459. this._material.dispose();
  92460. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  92461. };
  92462. return VideoDome;
  92463. }(BABYLON.Node));
  92464. BABYLON.VideoDome = VideoDome;
  92465. })(BABYLON || (BABYLON = {}));
  92466. //# sourceMappingURL=babylon.videoDome.js.map
  92467. 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)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#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\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","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;\ngl_FragColor=original;\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}","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}\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{\n#ifdef DOF\nfloat sumOfWeights=0.0; \nfloat sampleDepth=0.0;\nfloat factor=0.0;\nfloat centerSampleDepth=sampleDistance(sampleCenter);\n#endif\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\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\n\nif(sumOfWeights == 0.0){\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor/=sumOfWeights;\n#endif\n}","depthOfFieldMergePixelShader":"\nuniform sampler2D textureSampler;\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\n\nvarying vec2 vUV;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\nvec4 original=texture2D(textureSampler,vUV);\n#if BLUR_LEVEL == 0\nvec4 blurred0=texture2D(blurStep0,vUV);\ngl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL == 1\nvec4 blurred0=texture2D(blurStep0,vUV); \nvec4 blurred1=texture2D(blurStep1,vUV);\nif(coc<0.5){\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\ngl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nvec4 blurred0=texture2D(blurStep0,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\nif(coc<0.33){\ngl_FragColor=mix(original,blurred2,coc/0.33);\n}else if(coc<0.66){\ngl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);\n}else{\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;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(depthSampler,offset).r; \nreturn (cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \n}\nvoid main(void)\n{\nfloat pixelDistance=sampleDistance(vUV);\nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,texture2D(depthSampler,vUV).r,coc,1.0);\n}\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\n#ifdef GRAIN\nvec2 seed=vUV*(grainAnimatedSeed);\nfloat grain=dither(seed,grainVarianceAmount);\n\nfloat lum=getLuminance(result.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\nresult.rgb+=grain*grainAmount;\nresult.rgb=max(result.rgb,0.0);\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#ifndef GRAIN \n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);\ncolor=max(color,0.0);\n#endif\n#endif\ngl_FragColor=color;\n}\n"};
  92468. 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\n#ifdef GRAIN\nuniform float grainVarianceAmount;\nuniform float grainAnimatedSeed;\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,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,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,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)\n{\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,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);\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,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);\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,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);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}","kernelBlurFragment":"#ifdef DOF\nsampleDepth=sampleDistance(sampleCoord{X});\nfactor=clamp(1.0-((centerSampleDepth-sampleDepth)/centerSampleDepth),0.0,1.0);\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\nsampleDepth=sampleDistance(sampleCoord{X});\nfactor=clamp(1.0-((centerSampleDepth-sampleDepth)/centerSampleDepth),0.0,1.0);\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};"};
  92469. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  92470. globalObject["BABYLON"] = BABYLON
  92471. return BABYLON;
  92472. });
  92473. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(18)))
  92474. /***/ }),
  92475. /* 1 */
  92476. /***/ (function(module, exports, __webpack_require__) {
  92477. "use strict";
  92478. Object.defineProperty(exports, "__esModule", { value: true });
  92479. var babylonjs_1 = __webpack_require__(0);
  92480. var helper_1 = __webpack_require__(3);
  92481. var HTMLMapper = (function () {
  92482. function HTMLMapper() {
  92483. }
  92484. HTMLMapper.prototype.map = function (element) {
  92485. var config = {};
  92486. var _loop_1 = function (attrIdx) {
  92487. var attr = element.attributes.item(attrIdx);
  92488. var split = attr.nodeName.split('.');
  92489. split.reduce(function (currentConfig, key, idx) {
  92490. var camelKey = helper_1.kebabToCamel(key);
  92491. if (idx === split.length - 1) {
  92492. var val = attr.nodeValue;
  92493. if (val === "true") {
  92494. val = true;
  92495. }
  92496. else if (val === "false") {
  92497. val = false;
  92498. }
  92499. else {
  92500. var isnum = /^\d+$/.test(val);
  92501. if (isnum) {
  92502. var number = parseFloat(val);
  92503. if (!isNaN(number)) {
  92504. val = number;
  92505. }
  92506. }
  92507. }
  92508. currentConfig[camelKey] = val;
  92509. }
  92510. else {
  92511. currentConfig[camelKey] = currentConfig[camelKey] || {};
  92512. }
  92513. return currentConfig[camelKey];
  92514. }, config);
  92515. };
  92516. for (var attrIdx = 0; attrIdx < element.attributes.length; ++attrIdx) {
  92517. _loop_1(attrIdx);
  92518. }
  92519. return config;
  92520. };
  92521. return HTMLMapper;
  92522. }());
  92523. var JSONMapper = (function () {
  92524. function JSONMapper() {
  92525. }
  92526. JSONMapper.prototype.map = function (rawSource) {
  92527. return JSON.parse(rawSource);
  92528. };
  92529. return JSONMapper;
  92530. }());
  92531. var DOMMapper = (function () {
  92532. function DOMMapper() {
  92533. }
  92534. DOMMapper.prototype.map = function (baseElement) {
  92535. var htmlMapper = new HTMLMapper();
  92536. var config = htmlMapper.map(baseElement);
  92537. var traverseChildren = function (element, partConfig) {
  92538. var children = element.children;
  92539. if (children.length) {
  92540. for (var i = 0; i < children.length; ++i) {
  92541. var item = children.item(i);
  92542. var configMapped = htmlMapper.map(item);
  92543. var key = helper_1.kebabToCamel(item.nodeName.toLowerCase());
  92544. if (item.attributes.getNamedItem('array') && item.attributes.getNamedItem('array').nodeValue === 'true') {
  92545. partConfig[key] = [];
  92546. }
  92547. else {
  92548. if (element.attributes.getNamedItem('array') && element.attributes.getNamedItem('array').nodeValue === 'true') {
  92549. partConfig.push(configMapped);
  92550. }
  92551. else if (partConfig[key]) {
  92552. element.setAttribute('array', 'true');
  92553. var oldItem = partConfig[key];
  92554. partConfig = [oldItem, configMapped];
  92555. }
  92556. else {
  92557. partConfig[key] = configMapped;
  92558. }
  92559. }
  92560. traverseChildren(item, partConfig[key] || configMapped);
  92561. }
  92562. }
  92563. return partConfig;
  92564. };
  92565. traverseChildren(baseElement, config);
  92566. return config;
  92567. };
  92568. return DOMMapper;
  92569. }());
  92570. var MapperManager = (function () {
  92571. function MapperManager() {
  92572. this.mappers = {
  92573. "html": new HTMLMapper(),
  92574. "json": new JSONMapper(),
  92575. "dom": new DOMMapper()
  92576. };
  92577. }
  92578. MapperManager.prototype.getMapper = function (type) {
  92579. if (!this.mappers[type]) {
  92580. babylonjs_1.Tools.Error("No mapper defined for " + type);
  92581. }
  92582. return this.mappers[type] || this.mappers[MapperManager.DefaultMapper];
  92583. };
  92584. MapperManager.prototype.registerMapper = function (type, mapper) {
  92585. this.mappers[type] = mapper;
  92586. };
  92587. MapperManager.prototype.dispose = function () {
  92588. this.mappers = {};
  92589. };
  92590. MapperManager.DefaultMapper = 'json';
  92591. return MapperManager;
  92592. }());
  92593. exports.MapperManager = MapperManager;
  92594. exports.mapperManager = new MapperManager();
  92595. /***/ }),
  92596. /* 2 */
  92597. /***/ (function(module, exports, __webpack_require__) {
  92598. (function (global, factory) {
  92599. true ? module.exports = factory() :
  92600. typeof define === 'function' && define.amd ? define(factory) :
  92601. (global.deepmerge = factory());
  92602. }(this, (function () { 'use strict';
  92603. var isMergeableObject = function isMergeableObject(value) {
  92604. return isNonNullObject(value)
  92605. && !isSpecial(value)
  92606. };
  92607. function isNonNullObject(value) {
  92608. return !!value && typeof value === 'object'
  92609. }
  92610. function isSpecial(value) {
  92611. var stringValue = Object.prototype.toString.call(value);
  92612. return stringValue === '[object RegExp]'
  92613. || stringValue === '[object Date]'
  92614. || isReactElement(value)
  92615. }
  92616. // see https://github.com/facebook/react/blob/b5ac963fb791d1298e7f396236383bc955f916c1/src/isomorphic/classic/element/ReactElement.js#L21-L25
  92617. var canUseSymbol = typeof Symbol === 'function' && Symbol.for;
  92618. var REACT_ELEMENT_TYPE = canUseSymbol ? Symbol.for('react.element') : 0xeac7;
  92619. function isReactElement(value) {
  92620. return value.$$typeof === REACT_ELEMENT_TYPE
  92621. }
  92622. function emptyTarget(val) {
  92623. return Array.isArray(val) ? [] : {}
  92624. }
  92625. function cloneUnlessOtherwiseSpecified(value, optionsArgument) {
  92626. var clone = !optionsArgument || optionsArgument.clone !== false;
  92627. return (clone && isMergeableObject(value))
  92628. ? deepmerge(emptyTarget(value), value, optionsArgument)
  92629. : value
  92630. }
  92631. function defaultArrayMerge(target, source, optionsArgument) {
  92632. return target.concat(source).map(function(element) {
  92633. return cloneUnlessOtherwiseSpecified(element, optionsArgument)
  92634. })
  92635. }
  92636. function mergeObject(target, source, optionsArgument) {
  92637. var destination = {};
  92638. if (isMergeableObject(target)) {
  92639. Object.keys(target).forEach(function(key) {
  92640. destination[key] = cloneUnlessOtherwiseSpecified(target[key], optionsArgument);
  92641. });
  92642. }
  92643. Object.keys(source).forEach(function(key) {
  92644. if (!isMergeableObject(source[key]) || !target[key]) {
  92645. destination[key] = cloneUnlessOtherwiseSpecified(source[key], optionsArgument);
  92646. } else {
  92647. destination[key] = deepmerge(target[key], source[key], optionsArgument);
  92648. }
  92649. });
  92650. return destination
  92651. }
  92652. function deepmerge(target, source, optionsArgument) {
  92653. var sourceIsArray = Array.isArray(source);
  92654. var targetIsArray = Array.isArray(target);
  92655. var options = optionsArgument || { arrayMerge: defaultArrayMerge };
  92656. var sourceAndTargetTypesMatch = sourceIsArray === targetIsArray;
  92657. if (!sourceAndTargetTypesMatch) {
  92658. return cloneUnlessOtherwiseSpecified(source, optionsArgument)
  92659. } else if (sourceIsArray) {
  92660. var arrayMerge = options.arrayMerge || defaultArrayMerge;
  92661. return arrayMerge(target, source, optionsArgument)
  92662. } else {
  92663. return mergeObject(target, source, optionsArgument)
  92664. }
  92665. }
  92666. deepmerge.all = function deepmergeAll(array, optionsArgument) {
  92667. if (!Array.isArray(array)) {
  92668. throw new Error('first argument should be an array')
  92669. }
  92670. return array.reduce(function(prev, next) {
  92671. return deepmerge(prev, next, optionsArgument)
  92672. }, {})
  92673. };
  92674. var deepmerge_1 = deepmerge;
  92675. return deepmerge_1;
  92676. })));
  92677. /***/ }),
  92678. /* 3 */
  92679. /***/ (function(module, exports, __webpack_require__) {
  92680. "use strict";
  92681. Object.defineProperty(exports, "__esModule", { value: true });
  92682. function isUrl(urlToCheck) {
  92683. if (urlToCheck.indexOf('http') === 0 || urlToCheck.indexOf('/') === 0 || urlToCheck.indexOf('./') === 0 || urlToCheck.indexOf('../') === 0) {
  92684. return true;
  92685. }
  92686. return false;
  92687. }
  92688. exports.isUrl = isUrl;
  92689. function kebabToCamel(s) {
  92690. return s.replace(/(\-\w)/g, function (m) { return m[1].toUpperCase(); });
  92691. }
  92692. exports.kebabToCamel = kebabToCamel;
  92693. function camelToKebab(str) {
  92694. return !str ? null : str.replace(/([A-Z])/g, function (g) { return '-' + g[0].toLowerCase(); });
  92695. }
  92696. exports.camelToKebab = camelToKebab;
  92697. /***/ }),
  92698. /* 4 */
  92699. /***/ (function(module, exports, __webpack_require__) {
  92700. "use strict";
  92701. Object.defineProperty(exports, "__esModule", { value: true });
  92702. var babylonjs_1 = __webpack_require__(0);
  92703. var ViewerManager = (function () {
  92704. function ViewerManager() {
  92705. this.viewers = {};
  92706. this.onViewerAddedObservable = new babylonjs_1.Observable();
  92707. this.onViewerRemovedObservable = new babylonjs_1.Observable();
  92708. }
  92709. ViewerManager.prototype.addViewer = function (viewer) {
  92710. this.viewers[viewer.getBaseId()] = viewer;
  92711. this._onViewerAdded(viewer);
  92712. };
  92713. ViewerManager.prototype.removeViewer = function (viewer) {
  92714. var id = viewer.getBaseId();
  92715. delete this.viewers[id];
  92716. this.onViewerRemovedObservable.notifyObservers(id);
  92717. };
  92718. ViewerManager.prototype.getViewerById = function (id) {
  92719. return this.viewers[id];
  92720. };
  92721. ViewerManager.prototype.getViewerByHTMLElement = function (element) {
  92722. for (var id in this.viewers) {
  92723. if (this.viewers[id].containerElement === element) {
  92724. return this.getViewerById(id);
  92725. }
  92726. }
  92727. };
  92728. ViewerManager.prototype.getViewerPromiseById = function (id) {
  92729. var _this = this;
  92730. return new Promise(function (resolve, reject) {
  92731. var localViewer = _this.getViewerById(id);
  92732. if (localViewer) {
  92733. return resolve(localViewer);
  92734. }
  92735. var viewerFunction = function (viewer) {
  92736. if (viewer.getBaseId() === id) {
  92737. resolve(viewer);
  92738. _this.onViewerAddedObservable.removeCallback(viewerFunction);
  92739. }
  92740. };
  92741. _this.onViewerAddedObservable.add(viewerFunction);
  92742. });
  92743. };
  92744. ViewerManager.prototype._onViewerAdded = function (viewer) {
  92745. this.onViewerAdded && this.onViewerAdded(viewer);
  92746. this.onViewerAddedObservable.notifyObservers(viewer);
  92747. };
  92748. ViewerManager.prototype.dispose = function () {
  92749. for (var id in this.viewers) {
  92750. this.viewers[id].dispose();
  92751. }
  92752. };
  92753. return ViewerManager;
  92754. }());
  92755. exports.ViewerManager = ViewerManager;
  92756. exports.viewerManager = new ViewerManager();
  92757. /***/ }),
  92758. /* 5 */
  92759. /***/ (function(module, exports, __webpack_require__) {
  92760. "use strict";
  92761. var __extends = (this && this.__extends) || (function () {
  92762. var extendStatics = Object.setPrototypeOf ||
  92763. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  92764. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  92765. return function (d, b) {
  92766. extendStatics(d, b);
  92767. function __() { this.constructor = d; }
  92768. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  92769. };
  92770. })();
  92771. Object.defineProperty(exports, "__esModule", { value: true });
  92772. var viewer_1 = __webpack_require__(6);
  92773. var babylonjs_1 = __webpack_require__(0);
  92774. var DefaultViewer = (function (_super) {
  92775. __extends(DefaultViewer, _super);
  92776. function DefaultViewer(containerElement, initialConfiguration) {
  92777. if (initialConfiguration === void 0) { initialConfiguration = { extends: 'default' }; }
  92778. var _this = _super.call(this, containerElement, initialConfiguration) || this;
  92779. _this.containerElement = containerElement;
  92780. _this.onModelLoaded = function (model) {
  92781. _this.configureTemplate(model);
  92782. var hideLoadingDelay = 500;
  92783. if (_this.configuration.lab && _this.configuration.lab.hideLoadingDelay !== undefined) {
  92784. hideLoadingDelay = _this.configuration.lab.hideLoadingDelay;
  92785. }
  92786. setTimeout(function () {
  92787. _this.hideLoadingScreen();
  92788. }, hideLoadingDelay);
  92789. return;
  92790. };
  92791. _this.onModelLoadedObservable.add(_this.onModelLoaded);
  92792. return _this;
  92793. }
  92794. DefaultViewer.prototype.initScene = function () {
  92795. var _this = this;
  92796. return _super.prototype.initScene.call(this).then(function () {
  92797. _this.extendClassWithConfig(_this.scene, _this.configuration.scene);
  92798. return _this.scene;
  92799. });
  92800. };
  92801. DefaultViewer.prototype.onTemplatesLoaded = function () {
  92802. var _this = this;
  92803. this.showLoadingScreen();
  92804. this.initNavbar();
  92805. var closeButton = document.getElementById('close-button');
  92806. if (closeButton) {
  92807. closeButton.addEventListener('pointerdown', function () {
  92808. _this.hideOverlayScreen();
  92809. });
  92810. }
  92811. return _super.prototype.onTemplatesLoaded.call(this);
  92812. };
  92813. DefaultViewer.prototype.initNavbar = function () {
  92814. var navbar = this.templateManager.getTemplate('navBar');
  92815. if (navbar) {
  92816. var navbarHeight_1 = navbar.parent.clientHeight + 'px';
  92817. var navbarShown_1 = true;
  92818. var timeoutCancel_1;
  92819. var triggerNavbar = function (show, evt) {
  92820. if (show === void 0) { show = false; }
  92821. if (!navbar || evt.button > 0)
  92822. return;
  92823. timeoutCancel_1 && clearTimeout(timeoutCancel_1);
  92824. if (show === navbarShown_1)
  92825. return;
  92826. if (show) {
  92827. navbar.parent.style.bottom = show ? '0px' : '-' + navbarHeight_1;
  92828. navbarShown_1 = show;
  92829. }
  92830. else {
  92831. var visibilityTimeout = 2000;
  92832. if (navbar.configuration.params && navbar.configuration.params.visibilityTimeout !== undefined) {
  92833. visibilityTimeout = navbar.configuration.params.visibilityTimeout;
  92834. }
  92835. timeoutCancel_1 = setTimeout(function () {
  92836. if (navbar) {
  92837. navbar.parent.style.bottom = '-' + navbarHeight_1;
  92838. }
  92839. navbarShown_1 = show;
  92840. }, visibilityTimeout);
  92841. }
  92842. };
  92843. this.templateManager.eventManager.registerCallback('viewer', triggerNavbar.bind(this, false), 'pointerout');
  92844. this.templateManager.eventManager.registerCallback('viewer', triggerNavbar.bind(this, true), 'pointerdown');
  92845. this.templateManager.eventManager.registerCallback('viewer', triggerNavbar.bind(this, false), 'pointerup');
  92846. this.templateManager.eventManager.registerCallback('navBar', triggerNavbar.bind(this, true), 'pointerover');
  92847. var viewerTemplate = this.templateManager.getTemplate('viewer');
  92848. var viewerElement_1 = viewerTemplate && viewerTemplate.parent;
  92849. var triggerFullscren = function (eventData) {
  92850. if (viewerElement_1) {
  92851. var fullscreenElement = document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement;
  92852. if (!fullscreenElement) {
  92853. var requestFullScreen = viewerElement_1.requestFullscreen || viewerElement_1.webkitRequestFullscreen || viewerElement_1.msRequestFullscreen || viewerElement_1.mozRequestFullScreen;
  92854. requestFullScreen.call(viewerElement_1);
  92855. }
  92856. else {
  92857. var exitFullscreen = document.exitFullscreen || document.webkitExitFullscreen || document.msExitFullscreen || document.mozCancelFullScreen;
  92858. exitFullscreen.call(document);
  92859. }
  92860. }
  92861. };
  92862. this.templateManager.eventManager.registerCallback('navBar', triggerFullscren, 'pointerdown', '#fullscreen-button');
  92863. }
  92864. };
  92865. DefaultViewer.prototype.prepareContainerElement = function () {
  92866. this.containerElement.style.position = 'relative';
  92867. this.containerElement.style.display = 'flex';
  92868. };
  92869. DefaultViewer.prototype.configureTemplate = function (model) {
  92870. var navbar = this.templateManager.getTemplate('navBar');
  92871. if (!navbar)
  92872. return;
  92873. var modelConfiguration = model.configuration;
  92874. var metadataContainer = navbar.parent.querySelector('#model-metadata');
  92875. if (metadataContainer) {
  92876. if (modelConfiguration.title !== undefined) {
  92877. var element = metadataContainer.querySelector('span.model-title');
  92878. if (element) {
  92879. element.innerHTML = modelConfiguration.title;
  92880. }
  92881. }
  92882. if (modelConfiguration.subtitle !== undefined) {
  92883. var element = metadataContainer.querySelector('span.model-subtitle');
  92884. if (element) {
  92885. element.innerHTML = modelConfiguration.subtitle;
  92886. }
  92887. }
  92888. if (modelConfiguration.thumbnail !== undefined) {
  92889. metadataContainer.querySelector('.thumbnail').style.backgroundImage = "url('" + modelConfiguration.thumbnail + "')";
  92890. }
  92891. }
  92892. };
  92893. DefaultViewer.prototype.loadModel = function (model) {
  92894. var _this = this;
  92895. if (model === void 0) { model = this.configuration.model; }
  92896. this.showLoadingScreen();
  92897. return _super.prototype.loadModel.call(this, model, true).catch(function (error) {
  92898. console.log(error);
  92899. _this.hideLoadingScreen();
  92900. _this.showOverlayScreen('error');
  92901. return Promise.reject(error);
  92902. });
  92903. };
  92904. DefaultViewer.prototype.showOverlayScreen = function (subScreen) {
  92905. var _this = this;
  92906. var template = this.templateManager.getTemplate('overlay');
  92907. if (!template)
  92908. return Promise.resolve('Overlay template not found');
  92909. return template.show((function (template) {
  92910. var canvasRect = _this.containerElement.getBoundingClientRect();
  92911. var canvasPositioning = window.getComputedStyle(_this.containerElement).position;
  92912. template.parent.style.display = 'flex';
  92913. template.parent.style.width = canvasRect.width + "px";
  92914. template.parent.style.height = canvasRect.height + "px";
  92915. template.parent.style.opacity = "1";
  92916. var subTemplate = _this.templateManager.getTemplate(subScreen);
  92917. if (!subTemplate) {
  92918. return Promise.reject(subScreen + ' template not found');
  92919. }
  92920. return subTemplate.show((function (template) {
  92921. template.parent.style.display = 'flex';
  92922. return Promise.resolve(template);
  92923. }));
  92924. }));
  92925. };
  92926. DefaultViewer.prototype.hideOverlayScreen = function () {
  92927. var template = this.templateManager.getTemplate('overlay');
  92928. if (!template)
  92929. return Promise.resolve('Overlay template not found');
  92930. return template.hide((function (template) {
  92931. template.parent.style.opacity = "0";
  92932. var onTransitionEnd = function () {
  92933. template.parent.removeEventListener("transitionend", onTransitionEnd);
  92934. template.parent.style.display = 'none';
  92935. };
  92936. template.parent.addEventListener("transitionend", onTransitionEnd);
  92937. var overlays = template.parent.querySelectorAll('.overlay');
  92938. if (overlays) {
  92939. for (var i = 0; i < overlays.length; ++i) {
  92940. var htmlElement = overlays.item(i);
  92941. htmlElement.style.display = 'none';
  92942. }
  92943. }
  92944. return Promise.resolve(template);
  92945. }));
  92946. };
  92947. DefaultViewer.prototype.showLoadingScreen = function () {
  92948. var _this = this;
  92949. var template = this.templateManager.getTemplate('loadingScreen');
  92950. if (!template)
  92951. return Promise.resolve('Loading Screen template not found');
  92952. return template.show((function (template) {
  92953. var canvasRect = _this.containerElement.getBoundingClientRect();
  92954. var canvasPositioning = window.getComputedStyle(_this.containerElement).position;
  92955. template.parent.style.display = 'flex';
  92956. template.parent.style.width = canvasRect.width + "px";
  92957. template.parent.style.height = canvasRect.height + "px";
  92958. template.parent.style.opacity = "1";
  92959. template.parent.style.backgroundColor = "black";
  92960. return Promise.resolve(template);
  92961. }));
  92962. };
  92963. DefaultViewer.prototype.hideLoadingScreen = function () {
  92964. var template = this.templateManager.getTemplate('loadingScreen');
  92965. if (!template)
  92966. return Promise.resolve('Loading Screen template not found');
  92967. return template.hide((function (template) {
  92968. template.parent.style.opacity = "0";
  92969. var onTransitionEnd = function () {
  92970. template.parent.removeEventListener("transitionend", onTransitionEnd);
  92971. template.parent.style.display = 'none';
  92972. };
  92973. template.parent.addEventListener("transitionend", onTransitionEnd);
  92974. return Promise.resolve(template);
  92975. }));
  92976. };
  92977. DefaultViewer.prototype.configureLights = function (lightsConfiguration, model) {
  92978. var _this = this;
  92979. if (lightsConfiguration === void 0) { lightsConfiguration = {}; }
  92980. _super.prototype.configureLights.call(this, lightsConfiguration, model);
  92981. if (this.configuration.lab && this.configuration.lab.flashlight) {
  92982. var pointerPosition = babylonjs_1.Vector3.Zero();
  92983. var lightTarget_1;
  92984. var angle = 0.5;
  92985. var exponent = Math.PI / 2;
  92986. if (typeof this.configuration.lab.flashlight === "object") {
  92987. exponent = this.configuration.lab.flashlight.exponent || exponent;
  92988. angle = this.configuration.lab.flashlight.angle || angle;
  92989. }
  92990. var flashlight = new babylonjs_1.SpotLight("flashlight", babylonjs_1.Vector3.Zero(), babylonjs_1.Vector3.Zero(), exponent, angle, this.scene);
  92991. if (typeof this.configuration.lab.flashlight === "object") {
  92992. flashlight.intensity = this.configuration.lab.flashlight.intensity || flashlight.intensity;
  92993. if (this.configuration.lab.flashlight.diffuse) {
  92994. flashlight.diffuse.r = this.configuration.lab.flashlight.diffuse.r;
  92995. flashlight.diffuse.g = this.configuration.lab.flashlight.diffuse.g;
  92996. flashlight.diffuse.b = this.configuration.lab.flashlight.diffuse.b;
  92997. }
  92998. if (this.configuration.lab.flashlight.specular) {
  92999. flashlight.specular.r = this.configuration.lab.flashlight.specular.r;
  93000. flashlight.specular.g = this.configuration.lab.flashlight.specular.g;
  93001. flashlight.specular.b = this.configuration.lab.flashlight.specular.b;
  93002. }
  93003. }
  93004. this.scene.constantlyUpdateMeshUnderPointer = true;
  93005. this.scene.onPointerObservable.add(function (eventData, eventState) {
  93006. if (eventData.type === 4 && eventData.pickInfo) {
  93007. lightTarget_1 = (eventData.pickInfo.pickedPoint);
  93008. }
  93009. else {
  93010. lightTarget_1 = undefined;
  93011. }
  93012. });
  93013. var updateFlashlightFunction = function () {
  93014. if (_this.camera && flashlight) {
  93015. flashlight.position.copyFrom(_this.camera.position);
  93016. if (lightTarget_1) {
  93017. lightTarget_1.subtractToRef(flashlight.position, flashlight.direction);
  93018. }
  93019. }
  93020. };
  93021. this.scene.registerBeforeRender(updateFlashlightFunction);
  93022. this.registeredOnBeforerenderFunctions.push(updateFlashlightFunction);
  93023. }
  93024. };
  93025. return DefaultViewer;
  93026. }(viewer_1.AbstractViewer));
  93027. exports.DefaultViewer = DefaultViewer;
  93028. /***/ }),
  93029. /* 6 */
  93030. /***/ (function(module, exports, __webpack_require__) {
  93031. "use strict";
  93032. Object.defineProperty(exports, "__esModule", { value: true });
  93033. var viewerManager_1 = __webpack_require__(4);
  93034. var templateManager_1 = __webpack_require__(21);
  93035. var loader_1 = __webpack_require__(24);
  93036. var babylonjs_1 = __webpack_require__(0);
  93037. var deepmerge = __webpack_require__(2);
  93038. var modelLoader_1 = __webpack_require__(14);
  93039. var AbstractViewer = (function () {
  93040. function AbstractViewer(containerElement, initialConfiguration) {
  93041. if (initialConfiguration === void 0) { initialConfiguration = {}; }
  93042. var _this = this;
  93043. this.containerElement = containerElement;
  93044. this._isDisposed = false;
  93045. this.resize = function () {
  93046. if (!_this.isCanvasInDOM()) {
  93047. return;
  93048. }
  93049. if (_this.canvas.clientWidth <= 0 || _this.canvas.clientHeight <= 0) {
  93050. return;
  93051. }
  93052. _this.engine.resize();
  93053. };
  93054. this.render = function () {
  93055. _this.scene && _this.scene.activeCamera && _this.scene.render();
  93056. };
  93057. if (containerElement.id) {
  93058. this.baseId = containerElement.id;
  93059. }
  93060. else {
  93061. this.baseId = containerElement.id = 'bjs' + Math.random().toString(32).substr(2, 8);
  93062. }
  93063. this.onSceneInitObservable = new babylonjs_1.Observable();
  93064. this.onEngineInitObservable = new babylonjs_1.Observable();
  93065. this.onModelLoadedObservable = new babylonjs_1.Observable();
  93066. this.onModelLoadProgressObservable = new babylonjs_1.Observable();
  93067. this.onModelLoadErrorObservable = new babylonjs_1.Observable();
  93068. this.onInitDoneObservable = new babylonjs_1.Observable();
  93069. this.onLoaderInitObservable = new babylonjs_1.Observable();
  93070. this.registeredOnBeforerenderFunctions = [];
  93071. this.models = [];
  93072. this.modelLoader = new modelLoader_1.ModelLoader(this);
  93073. viewerManager_1.viewerManager.addViewer(this);
  93074. this.templateManager = new templateManager_1.TemplateManager(containerElement);
  93075. this.prepareContainerElement();
  93076. this._configurationLoader = new loader_1.ConfigurationLoader();
  93077. this._configurationLoader.loadConfiguration(initialConfiguration, function (configuration) {
  93078. _this.configuration = deepmerge(_this.configuration || {}, configuration);
  93079. if (_this.configuration.observers) {
  93080. _this.configureObservers(_this.configuration.observers);
  93081. }
  93082. var templateConfiguration = _this.configuration.templates || {};
  93083. _this.templateManager.initTemplate(templateConfiguration);
  93084. _this.templateManager.onAllLoaded.add(function () {
  93085. var canvas = _this.templateManager.getCanvas();
  93086. if (canvas) {
  93087. _this.canvas = canvas;
  93088. }
  93089. _this._onTemplateLoaded();
  93090. });
  93091. });
  93092. }
  93093. Object.defineProperty(AbstractViewer.prototype, "isHdrSupported", {
  93094. get: function () {
  93095. return this._hdrSupport;
  93096. },
  93097. enumerable: true,
  93098. configurable: true
  93099. });
  93100. AbstractViewer.prototype.getBaseId = function () {
  93101. return this.baseId;
  93102. };
  93103. AbstractViewer.prototype.isCanvasInDOM = function () {
  93104. return !!this.canvas && !!this.canvas.parentElement;
  93105. };
  93106. AbstractViewer.prototype.updateConfiguration = function (newConfiguration) {
  93107. if (newConfiguration === void 0) { newConfiguration = this.configuration; }
  93108. this.configuration = deepmerge(this.configuration || {}, newConfiguration);
  93109. if (newConfiguration.scene) {
  93110. this.configureScene(newConfiguration.scene);
  93111. }
  93112. if (newConfiguration.optimizer) {
  93113. this.configureOptimizer(newConfiguration.optimizer);
  93114. }
  93115. if (newConfiguration.observers) {
  93116. this.configureObservers(newConfiguration.observers);
  93117. }
  93118. if (newConfiguration.model && typeof newConfiguration.model === 'object') {
  93119. this.configureModel(newConfiguration.model);
  93120. }
  93121. if (newConfiguration.lights) {
  93122. this.configureLights(newConfiguration.lights);
  93123. }
  93124. if (newConfiguration.skybox !== undefined || newConfiguration.ground !== undefined) {
  93125. this.configureEnvironment(newConfiguration.skybox, newConfiguration.ground);
  93126. }
  93127. if (newConfiguration.camera) {
  93128. this.configureCamera(newConfiguration.camera);
  93129. }
  93130. };
  93131. AbstractViewer.prototype.configureEnvironment = function (skyboxConifguration, groundConfiguration) {
  93132. if (!skyboxConifguration && !groundConfiguration) {
  93133. if (this.environmentHelper) {
  93134. this.environmentHelper.dispose();
  93135. delete this.environmentHelper;
  93136. }
  93137. ;
  93138. return Promise.resolve(this.scene);
  93139. }
  93140. var options = {
  93141. createGround: !!groundConfiguration,
  93142. createSkybox: !!skyboxConifguration,
  93143. setupImageProcessing: false
  93144. };
  93145. if (groundConfiguration) {
  93146. var groundConfig = (typeof groundConfiguration === 'boolean') ? {} : groundConfiguration;
  93147. var groundSize = groundConfig.size || (typeof skyboxConifguration === 'object' && skyboxConifguration.scale);
  93148. if (groundSize) {
  93149. options.groundSize = groundSize;
  93150. }
  93151. options.enableGroundShadow = groundConfig === true || groundConfig.receiveShadows;
  93152. if (groundConfig.shadowLevel !== undefined) {
  93153. options.groundShadowLevel = groundConfig.shadowLevel;
  93154. }
  93155. options.enableGroundMirror = !!groundConfig.mirror;
  93156. if (groundConfig.texture) {
  93157. options.groundTexture = groundConfig.texture;
  93158. }
  93159. if (groundConfig.color) {
  93160. options.groundColor = new babylonjs_1.Color3(groundConfig.color.r, groundConfig.color.g, groundConfig.color.b);
  93161. }
  93162. if (groundConfig.opacity !== undefined) {
  93163. options.groundOpacity = groundConfig.opacity;
  93164. }
  93165. if (groundConfig.mirror) {
  93166. options.enableGroundMirror = true;
  93167. if (typeof groundConfig.mirror === "object") {
  93168. if (groundConfig.mirror.amount !== undefined)
  93169. options.groundMirrorAmount = groundConfig.mirror.amount;
  93170. if (groundConfig.mirror.sizeRatio !== undefined)
  93171. options.groundMirrorSizeRatio = groundConfig.mirror.sizeRatio;
  93172. if (groundConfig.mirror.blurKernel !== undefined)
  93173. options.groundMirrorBlurKernel = groundConfig.mirror.blurKernel;
  93174. if (groundConfig.mirror.fresnelWeight !== undefined)
  93175. options.groundMirrorFresnelWeight = groundConfig.mirror.fresnelWeight;
  93176. if (groundConfig.mirror.fallOffDistance !== undefined)
  93177. options.groundMirrorFallOffDistance = groundConfig.mirror.fallOffDistance;
  93178. if (this.defaultPipelineTextureType !== undefined)
  93179. options.groundMirrorTextureType = this.defaultPipelineTextureType;
  93180. }
  93181. }
  93182. }
  93183. var postInitSkyboxMaterial = false;
  93184. if (skyboxConifguration) {
  93185. var conf = skyboxConifguration === true ? {} : skyboxConifguration;
  93186. if (conf.material && conf.material.imageProcessingConfiguration) {
  93187. options.setupImageProcessing = false;
  93188. }
  93189. var skyboxSize = conf.scale;
  93190. if (skyboxSize) {
  93191. options.skyboxSize = skyboxSize;
  93192. }
  93193. options.sizeAuto = !options.skyboxSize;
  93194. if (conf.color) {
  93195. options.skyboxColor = new babylonjs_1.Color3(conf.color.r, conf.color.g, conf.color.b);
  93196. }
  93197. if (conf.cubeTexture && conf.cubeTexture.url) {
  93198. if (typeof conf.cubeTexture.url === "string") {
  93199. options.skyboxTexture = conf.cubeTexture.url;
  93200. }
  93201. else {
  93202. postInitSkyboxMaterial = true;
  93203. }
  93204. }
  93205. if (conf.material && conf.material.imageProcessingConfiguration) {
  93206. postInitSkyboxMaterial = true;
  93207. }
  93208. }
  93209. options.setupImageProcessing = false;
  93210. if (!this.environmentHelper) {
  93211. this.environmentHelper = this.scene.createDefaultEnvironment(options);
  93212. }
  93213. else {
  93214. var scene = this.environmentHelper.rootMesh.getScene();
  93215. if (scene !== this.scene) {
  93216. this.environmentHelper.dispose();
  93217. this.environmentHelper = this.scene.createDefaultEnvironment(options);
  93218. }
  93219. else {
  93220. this.environmentHelper.updateOptions(options);
  93221. }
  93222. }
  93223. if (postInitSkyboxMaterial) {
  93224. var skyboxMaterial = this.environmentHelper.skyboxMaterial;
  93225. if (skyboxMaterial) {
  93226. if (typeof skyboxConifguration === 'object' && skyboxConifguration.material && skyboxConifguration.material.imageProcessingConfiguration) {
  93227. this.extendClassWithConfig(skyboxMaterial.imageProcessingConfiguration, skyboxConifguration.material.imageProcessingConfiguration);
  93228. }
  93229. }
  93230. }
  93231. };
  93232. AbstractViewer.prototype.configureScene = function (sceneConfig, optimizerConfig) {
  93233. if (!this.scene) {
  93234. return;
  93235. }
  93236. if (sceneConfig.debug) {
  93237. this.scene.debugLayer.show();
  93238. }
  93239. else {
  93240. if (this.scene.debugLayer.isVisible()) {
  93241. this.scene.debugLayer.hide();
  93242. }
  93243. }
  93244. if (sceneConfig.clearColor) {
  93245. var cc = sceneConfig.clearColor;
  93246. var oldcc = this.scene.clearColor;
  93247. if (cc.r !== undefined) {
  93248. oldcc.r = cc.r;
  93249. }
  93250. if (cc.g !== undefined) {
  93251. oldcc.g = cc.g;
  93252. }
  93253. if (cc.b !== undefined) {
  93254. oldcc.b = cc.b;
  93255. }
  93256. if (cc.a !== undefined) {
  93257. oldcc.a = cc.a;
  93258. }
  93259. }
  93260. if (sceneConfig.imageProcessingConfiguration) {
  93261. this.extendClassWithConfig(this.scene.imageProcessingConfiguration, sceneConfig.imageProcessingConfiguration);
  93262. }
  93263. if (sceneConfig.environmentTexture) {
  93264. if (this.scene.environmentTexture) {
  93265. this.scene.environmentTexture.dispose();
  93266. }
  93267. var environmentTexture = babylonjs_1.CubeTexture.CreateFromPrefilteredData(sceneConfig.environmentTexture, this.scene);
  93268. this.scene.environmentTexture = environmentTexture;
  93269. }
  93270. if (sceneConfig.autoRotate) {
  93271. this.camera.useAutoRotationBehavior = true;
  93272. }
  93273. };
  93274. AbstractViewer.prototype.configureOptimizer = function (optimizerConfig) {
  93275. if (typeof optimizerConfig === 'boolean') {
  93276. if (this.sceneOptimizer) {
  93277. this.sceneOptimizer.stop();
  93278. this.sceneOptimizer.dispose();
  93279. delete this.sceneOptimizer;
  93280. }
  93281. if (optimizerConfig) {
  93282. this.sceneOptimizer = new babylonjs_1.SceneOptimizer(this.scene);
  93283. this.sceneOptimizer.start();
  93284. }
  93285. }
  93286. else {
  93287. var optimizerOptions = new babylonjs_1.SceneOptimizerOptions(optimizerConfig.targetFrameRate, optimizerConfig.trackerDuration);
  93288. if (optimizerConfig.degradation) {
  93289. switch (optimizerConfig.degradation) {
  93290. case "low":
  93291. optimizerOptions = babylonjs_1.SceneOptimizerOptions.LowDegradationAllowed(optimizerConfig.targetFrameRate);
  93292. break;
  93293. case "moderate":
  93294. optimizerOptions = babylonjs_1.SceneOptimizerOptions.ModerateDegradationAllowed(optimizerConfig.targetFrameRate);
  93295. break;
  93296. case "hight":
  93297. optimizerOptions = babylonjs_1.SceneOptimizerOptions.HighDegradationAllowed(optimizerConfig.targetFrameRate);
  93298. break;
  93299. }
  93300. }
  93301. if (this.sceneOptimizer) {
  93302. this.sceneOptimizer.stop();
  93303. this.sceneOptimizer.dispose();
  93304. }
  93305. this.sceneOptimizer = new babylonjs_1.SceneOptimizer(this.scene, optimizerOptions, optimizerConfig.autoGeneratePriorities, optimizerConfig.improvementMode);
  93306. this.sceneOptimizer.start();
  93307. }
  93308. };
  93309. AbstractViewer.prototype.configureObservers = function (observersConfiguration) {
  93310. if (observersConfiguration.onEngineInit) {
  93311. this.onEngineInitObservable.add(window[observersConfiguration.onEngineInit]);
  93312. }
  93313. else {
  93314. if (observersConfiguration.onEngineInit === '' && this.configuration.observers && this.configuration.observers.onEngineInit) {
  93315. this.onEngineInitObservable.removeCallback(window[this.configuration.observers.onEngineInit]);
  93316. }
  93317. }
  93318. if (observersConfiguration.onSceneInit) {
  93319. this.onSceneInitObservable.add(window[observersConfiguration.onSceneInit]);
  93320. }
  93321. else {
  93322. if (observersConfiguration.onSceneInit === '' && this.configuration.observers && this.configuration.observers.onSceneInit) {
  93323. this.onSceneInitObservable.removeCallback(window[this.configuration.observers.onSceneInit]);
  93324. }
  93325. }
  93326. if (observersConfiguration.onModelLoaded) {
  93327. this.onModelLoadedObservable.add(window[observersConfiguration.onModelLoaded]);
  93328. }
  93329. else {
  93330. if (observersConfiguration.onModelLoaded === '' && this.configuration.observers && this.configuration.observers.onModelLoaded) {
  93331. this.onModelLoadedObservable.removeCallback(window[this.configuration.observers.onModelLoaded]);
  93332. }
  93333. }
  93334. };
  93335. AbstractViewer.prototype.configureCamera = function (cameraConfig, model) {
  93336. var _this = this;
  93337. var focusMeshes = model ? model.meshes : this.scene.meshes;
  93338. if (!this.scene.activeCamera) {
  93339. this.scene.createDefaultCamera(true, true, true);
  93340. this.camera = this.scene.activeCamera;
  93341. }
  93342. if (cameraConfig.position) {
  93343. this.camera.position.copyFromFloats(cameraConfig.position.x || 0, cameraConfig.position.y || 0, cameraConfig.position.z || 0);
  93344. }
  93345. if (cameraConfig.rotation) {
  93346. this.camera.rotationQuaternion = new babylonjs_1.Quaternion(cameraConfig.rotation.x || 0, cameraConfig.rotation.y || 0, cameraConfig.rotation.z || 0, cameraConfig.rotation.w || 0);
  93347. }
  93348. this.extendClassWithConfig(this.camera, cameraConfig);
  93349. this.camera.minZ = cameraConfig.minZ || this.camera.minZ;
  93350. this.camera.maxZ = cameraConfig.maxZ || this.camera.maxZ;
  93351. if (cameraConfig.behaviors) {
  93352. for (var name_1 in cameraConfig.behaviors) {
  93353. this.setCameraBehavior(cameraConfig.behaviors[name_1], focusMeshes);
  93354. }
  93355. }
  93356. ;
  93357. var sceneExtends = this.scene.getWorldExtends(function (mesh) {
  93358. return !_this.environmentHelper || (mesh !== _this.environmentHelper.ground && mesh !== _this.environmentHelper.rootMesh && mesh !== _this.environmentHelper.skybox);
  93359. });
  93360. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  93361. var sceneDiagonalLenght = sceneDiagonal.length();
  93362. if (isFinite(sceneDiagonalLenght))
  93363. this.camera.upperRadiusLimit = sceneDiagonalLenght * 3;
  93364. };
  93365. AbstractViewer.prototype.configureLights = function (lightsConfiguration, model) {
  93366. var _this = this;
  93367. if (lightsConfiguration === void 0) { lightsConfiguration = {}; }
  93368. var focusMeshes = model ? model.meshes : this.scene.meshes;
  93369. if (!Object.keys(lightsConfiguration).length)
  93370. return;
  93371. var lightsAvailable = this.scene.lights.map(function (light) { return light.name; });
  93372. var lightsToConfigure = Object.keys(this.configuration.lights || []);
  93373. if (Object.keys(lightsToConfigure).length !== lightsAvailable.length) {
  93374. lightsAvailable.forEach(function (lName) {
  93375. if (lightsToConfigure.indexOf(lName) === -1) {
  93376. _this.scene.getLightByName(lName).dispose();
  93377. }
  93378. });
  93379. }
  93380. Object.keys(lightsConfiguration).forEach(function (name, idx) {
  93381. var lightConfig = { type: 0 };
  93382. if (typeof lightsConfiguration[name] === 'object') {
  93383. lightConfig = lightsConfiguration[name];
  93384. }
  93385. lightConfig.name = name;
  93386. var light;
  93387. if (lightsAvailable.indexOf(name) === -1) {
  93388. var constructor = babylonjs_1.Light.GetConstructorFromName(lightConfig.type, lightConfig.name, _this.scene);
  93389. if (!constructor)
  93390. return;
  93391. light = constructor();
  93392. }
  93393. else {
  93394. light = _this.scene.getLightByName(name);
  93395. lightsAvailable = lightsAvailable.filter(function (ln) { return ln !== name; });
  93396. if (lightConfig.type !== undefined && light.getTypeID() !== lightConfig.type) {
  93397. light.dispose();
  93398. var constructor = babylonjs_1.Light.GetConstructorFromName(lightConfig.type, lightConfig.name, _this.scene);
  93399. if (!constructor)
  93400. return;
  93401. light = constructor();
  93402. }
  93403. }
  93404. if (lightsConfiguration[name] === false) {
  93405. light.dispose();
  93406. return;
  93407. }
  93408. var enabled = lightConfig.enabled !== undefined ? lightConfig.enabled : !lightConfig.disabled;
  93409. light.setEnabled(enabled);
  93410. _this.extendClassWithConfig(light, lightConfig);
  93411. if (light instanceof babylonjs_1.ShadowLight) {
  93412. if (lightConfig.target) {
  93413. if (light.setDirectionToTarget) {
  93414. var target = babylonjs_1.Vector3.Zero().copyFrom(lightConfig.target);
  93415. light.setDirectionToTarget(target);
  93416. }
  93417. }
  93418. else if (lightConfig.direction) {
  93419. var direction = babylonjs_1.Vector3.Zero().copyFrom(lightConfig.direction);
  93420. light.direction = direction;
  93421. }
  93422. var shadowGenerator = light.getShadowGenerator();
  93423. if (lightConfig.shadowEnabled && _this.maxShadows) {
  93424. if (!shadowGenerator) {
  93425. shadowGenerator = new babylonjs_1.ShadowGenerator(512, light);
  93426. }
  93427. _this.extendClassWithConfig(shadowGenerator, lightConfig.shadowConfig || {});
  93428. var shadownMap = shadowGenerator.getShadowMap();
  93429. if (!shadownMap)
  93430. return;
  93431. var renderList = shadownMap.renderList;
  93432. for (var index = 0; index < focusMeshes.length; index++) {
  93433. if (babylonjs_1.Tags.MatchesQuery(focusMeshes[index], 'castShadow')) {
  93434. renderList && renderList.push(focusMeshes[index]);
  93435. }
  93436. }
  93437. }
  93438. else if (shadowGenerator) {
  93439. shadowGenerator.dispose();
  93440. }
  93441. }
  93442. });
  93443. };
  93444. AbstractViewer.prototype.configureModel = function (modelConfiguration, model) {
  93445. this.models.forEach(function (model) {
  93446. model.configuration = modelConfiguration;
  93447. });
  93448. };
  93449. AbstractViewer.prototype.dispose = function () {
  93450. if (this._isDisposed) {
  93451. return;
  93452. }
  93453. window.removeEventListener('resize', this.resize);
  93454. if (this.sceneOptimizer) {
  93455. this.sceneOptimizer.stop();
  93456. this.sceneOptimizer.dispose();
  93457. }
  93458. if (this.environmentHelper) {
  93459. this.environmentHelper.dispose();
  93460. }
  93461. if (this._configurationLoader) {
  93462. this._configurationLoader.dispose();
  93463. }
  93464. this.onEngineInitObservable.clear();
  93465. delete this.onEngineInitObservable;
  93466. this.onInitDoneObservable.clear();
  93467. delete this.onInitDoneObservable;
  93468. this.onLoaderInitObservable.clear();
  93469. delete this.onLoaderInitObservable;
  93470. this.onModelLoadedObservable.clear();
  93471. delete this.onModelLoadedObservable;
  93472. this.onModelLoadErrorObservable.clear();
  93473. delete this.onModelLoadErrorObservable;
  93474. this.onModelLoadProgressObservable.clear();
  93475. delete this.onModelLoadProgressObservable;
  93476. this.onSceneInitObservable.clear();
  93477. delete this.onSceneInitObservable;
  93478. if (this.scene.activeCamera) {
  93479. this.scene.activeCamera.detachControl(this.canvas);
  93480. }
  93481. this.modelLoader.dispose();
  93482. this.models.forEach(function (model) {
  93483. model.dispose();
  93484. });
  93485. this.models.length = 0;
  93486. this.scene.dispose();
  93487. this.engine.dispose();
  93488. this.templateManager.dispose();
  93489. viewerManager_1.viewerManager.removeViewer(this);
  93490. this._isDisposed = true;
  93491. };
  93492. AbstractViewer.prototype.onTemplatesLoaded = function () {
  93493. return Promise.resolve(this);
  93494. };
  93495. AbstractViewer.prototype._onTemplateLoaded = function () {
  93496. var _this = this;
  93497. return this.onTemplatesLoaded().then(function () {
  93498. var autoLoadModel = _this.configuration.model;
  93499. return _this.initEngine().then(function (engine) {
  93500. return _this.onEngineInitObservable.notifyObserversWithPromise(engine);
  93501. }).then(function () {
  93502. if (autoLoadModel) {
  93503. return _this.loadModel().catch(function (e) { }).then(function () { return _this.scene; });
  93504. }
  93505. else {
  93506. return _this.scene || _this.initScene();
  93507. }
  93508. }).then(function (scene) {
  93509. return _this.onSceneInitObservable.notifyObserversWithPromise(scene);
  93510. }).then(function () {
  93511. return _this.onInitDoneObservable.notifyObserversWithPromise(_this);
  93512. }).catch(function (e) {
  93513. babylonjs_1.Tools.Warn(e.toString());
  93514. return _this;
  93515. });
  93516. });
  93517. };
  93518. AbstractViewer.prototype.initEngine = function () {
  93519. this.injectCustomShaders();
  93520. var canvasElement = this.templateManager.getCanvas();
  93521. if (!canvasElement) {
  93522. return Promise.reject('Canvas element not found!');
  93523. }
  93524. var config = this.configuration.engine || {};
  93525. this.engine = new babylonjs_1.Engine(canvasElement, !!config.antialiasing, config.engineOptions);
  93526. babylonjs_1.Database.IDBStorageEnabled = false;
  93527. if (!config.disableResize) {
  93528. window.addEventListener('resize', this.resize);
  93529. }
  93530. this.engine.runRenderLoop(this.render);
  93531. if (this.configuration.engine && this.configuration.engine.adaptiveQuality) {
  93532. var scale = Math.max(0.5, 1 / (window.devicePixelRatio || 2));
  93533. this.engine.setHardwareScalingLevel(scale);
  93534. }
  93535. this.handleHardwareLimitations();
  93536. return Promise.resolve(this.engine);
  93537. };
  93538. AbstractViewer.prototype.initScene = function () {
  93539. if (this.scene) {
  93540. this.scene.dispose();
  93541. }
  93542. this.scene = new babylonjs_1.Scene(this.engine);
  93543. this.scene.createDefaultLight(true);
  93544. if (this.configuration.scene) {
  93545. this.configureScene(this.configuration.scene);
  93546. if (this.configuration.optimizer) {
  93547. this.configureOptimizer(this.configuration.optimizer);
  93548. }
  93549. }
  93550. return Promise.resolve(this.scene);
  93551. };
  93552. AbstractViewer.prototype.initModel = function (modelConfig, clearScene) {
  93553. var _this = this;
  93554. if (modelConfig === void 0) { modelConfig = this.configuration.model; }
  93555. if (clearScene === void 0) { clearScene = true; }
  93556. var model = this.modelLoader.load(modelConfig);
  93557. if (clearScene) {
  93558. this.models.forEach(function (m) { return m.dispose(); });
  93559. this.models.length = 0;
  93560. }
  93561. this.models.push(model);
  93562. this.lastUsedLoader = model.loader;
  93563. model.onLoadErrorObservable.add(function (errorObject) {
  93564. _this.onModelLoadErrorObservable.notifyObserversWithPromise(errorObject);
  93565. });
  93566. model.onLoadProgressObservable.add(function (progressEvent) {
  93567. return _this.onModelLoadProgressObservable.notifyObserversWithPromise(progressEvent);
  93568. });
  93569. this.onLoaderInitObservable.notifyObserversWithPromise(this.lastUsedLoader);
  93570. model.onLoadedObservable.add(function () {
  93571. _this.onModelLoadedObservable.notifyObserversWithPromise(model)
  93572. .then(function () {
  93573. _this.configureLights(_this.configuration.lights);
  93574. if (_this.configuration.camera) {
  93575. _this.configureCamera(_this.configuration.camera, model);
  93576. }
  93577. return _this.initEnvironment(model);
  93578. }).then(function () {
  93579. _this.isLoading = false;
  93580. return model;
  93581. });
  93582. });
  93583. return model;
  93584. };
  93585. AbstractViewer.prototype.loadModel = function (modelConfig, clearScene) {
  93586. var _this = this;
  93587. if (modelConfig === void 0) { modelConfig = this.configuration.model; }
  93588. if (clearScene === void 0) { clearScene = true; }
  93589. var modelUrl = (typeof modelConfig === 'string') ? modelConfig : modelConfig.url;
  93590. if (!modelUrl) {
  93591. return Promise.reject("no model configuration found");
  93592. }
  93593. if (this.isLoading) {
  93594. return Promise.reject("another model is curently being loaded.");
  93595. }
  93596. this.isLoading = true;
  93597. if ((typeof modelConfig === 'string')) {
  93598. if (this.configuration.model && typeof this.configuration.model === 'object') {
  93599. this.configuration.model.url = modelConfig;
  93600. }
  93601. }
  93602. else {
  93603. if (this.configuration.model) {
  93604. deepmerge(this.configuration.model, modelConfig);
  93605. }
  93606. else {
  93607. this.configuration.model = modelConfig;
  93608. }
  93609. }
  93610. return Promise.resolve(this.scene).then(function (scene) {
  93611. if (!scene)
  93612. return _this.initScene();
  93613. return scene;
  93614. }).then(function () {
  93615. return new Promise(function (resolve, reject) {
  93616. return _this.initModel(modelConfig, clearScene);
  93617. });
  93618. });
  93619. };
  93620. AbstractViewer.prototype.initEnvironment = function (model) {
  93621. this.configureEnvironment(this.configuration.skybox, this.configuration.ground);
  93622. return Promise.resolve(this.scene);
  93623. };
  93624. AbstractViewer.prototype.handleHardwareLimitations = function () {
  93625. var maxVaryingRows = this.engine.getCaps().maxVaryingVectors;
  93626. var maxFragmentSamplers = this.engine.getCaps().maxTexturesImageUnits;
  93627. if ((maxVaryingRows < 8) || (maxFragmentSamplers < 8)) {
  93628. this.maxShadows = 0;
  93629. }
  93630. else {
  93631. this.maxShadows = 3;
  93632. }
  93633. var caps = this.engine.getCaps();
  93634. var linearHalfFloatTargets = caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering;
  93635. var linearFloatTargets = caps.textureFloatRender && caps.textureFloatLinearFiltering;
  93636. this._hdrSupport = !!(linearFloatTargets || linearHalfFloatTargets);
  93637. if (linearHalfFloatTargets) {
  93638. this.defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_HALF_FLOAT;
  93639. this.shadowGeneratorBias = 0.002;
  93640. }
  93641. else if (linearFloatTargets) {
  93642. this.defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_FLOAT;
  93643. this.shadowGeneratorBias = 0.001;
  93644. }
  93645. else {
  93646. this.defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_UNSIGNED_INT;
  93647. this.shadowGeneratorBias = 0.001;
  93648. }
  93649. this.defaultPipelineTextureType = this._hdrSupport ? this.defaultHighpTextureType : babylonjs_1.Engine.TEXTURETYPE_UNSIGNED_INT;
  93650. };
  93651. AbstractViewer.prototype.injectCustomShaders = function () {
  93652. var customShaders = this.configuration.customShaders;
  93653. if (!customShaders) {
  93654. return;
  93655. }
  93656. if (customShaders.shaders) {
  93657. Object.keys(customShaders.shaders).forEach(function (key) {
  93658. babylonjs_1.Effect.ShadersStore[key] = customShaders.shaders[key];
  93659. });
  93660. }
  93661. if (customShaders.includes) {
  93662. Object.keys(customShaders.includes).forEach(function (key) {
  93663. babylonjs_1.Effect.IncludesShadersStore[key] = customShaders.includes[key];
  93664. });
  93665. }
  93666. };
  93667. AbstractViewer.prototype.extendClassWithConfig = function (object, config) {
  93668. var _this = this;
  93669. if (!config)
  93670. return;
  93671. Object.keys(config).forEach(function (key) {
  93672. if (key in object && typeof object[key] !== 'function') {
  93673. if (typeof object[key] === 'object') {
  93674. _this.extendClassWithConfig(object[key], config[key]);
  93675. }
  93676. else {
  93677. if (config[key] !== undefined) {
  93678. object[key] = config[key];
  93679. }
  93680. }
  93681. }
  93682. });
  93683. };
  93684. AbstractViewer.prototype.setCameraBehavior = function (behaviorConfig, payload) {
  93685. var behavior;
  93686. var type = (typeof behaviorConfig !== "object") ? behaviorConfig : behaviorConfig.type;
  93687. var config = (typeof behaviorConfig === "object") ? behaviorConfig : {};
  93688. switch (type) {
  93689. case 0:
  93690. this.camera.useAutoRotationBehavior = true;
  93691. behavior = this.camera.autoRotationBehavior;
  93692. break;
  93693. case 1:
  93694. this.camera.useBouncingBehavior = true;
  93695. behavior = this.camera.bouncingBehavior;
  93696. break;
  93697. case 2:
  93698. this.camera.useFramingBehavior = true;
  93699. behavior = this.camera.framingBehavior;
  93700. break;
  93701. default:
  93702. behavior = null;
  93703. break;
  93704. }
  93705. if (behavior) {
  93706. if (typeof behaviorConfig === "object") {
  93707. this.extendClassWithConfig(behavior, behaviorConfig);
  93708. }
  93709. }
  93710. switch (type) {
  93711. case 0:
  93712. break;
  93713. case 1:
  93714. break;
  93715. case 2:
  93716. if (config.zoomOnBoundingInfo) {
  93717. var meshes = payload;
  93718. var bounding = meshes[0].getHierarchyBoundingVectors();
  93719. behavior.zoomOnBoundingInfo(bounding.min, bounding.max);
  93720. }
  93721. break;
  93722. }
  93723. };
  93724. return AbstractViewer;
  93725. }());
  93726. exports.AbstractViewer = AbstractViewer;
  93727. /***/ }),
  93728. /* 7 */
  93729. /***/ (function(module, exports) {
  93730. module.exports = "<viewer></viewer> <loading-screen></loading-screen> <overlay></overlay>";
  93731. /***/ }),
  93732. /* 8 */
  93733. /***/ (function(module, exports) {
  93734. 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}}>";
  93735. /***/ }),
  93736. /* 9 */
  93737. /***/ (function(module, exports) {
  93738. 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=="
  93739. /***/ }),
  93740. /* 10 */
  93741. /***/ (function(module, exports) {
  93742. 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>";
  93743. /***/ }),
  93744. /* 11 */
  93745. /***/ (function(module, exports) {
  93746. 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>";
  93747. /***/ }),
  93748. /* 12 */
  93749. /***/ (function(module, exports) {
  93750. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAQAAAD9CzEMAAAAt0lEQVR42u2WAQbDQBBFQ9IbRtDcrrqK3LBbXrEH6OuHEPMBjPd2xHyZKtdNpcLMg11Pr7y4/YdvwIdd4jtw4BU0Rjrbz9mNzkjzgpU3wNhCvH5M3i1fKzzeK3K8V+R4r8jxTpHjlULhc0WOd8fU6e4I8y3y13tFjHel4GswwAvFSR/ZN6Zv2gjvmzbGhwqPzxUenys83is8Pld4vFac/9sy8/SVNrbgYJl8WGhsvkpoA1+pVK6ZLyLNXm2txsT5AAAAAElFTkSuQmCC"
  93751. /***/ }),
  93752. /* 13 */
  93753. /***/ (function(module, exports) {
  93754. module.exports = "Error loading the model";
  93755. /***/ }),
  93756. /* 14 */
  93757. /***/ (function(module, exports, __webpack_require__) {
  93758. "use strict";
  93759. Object.defineProperty(exports, "__esModule", { value: true });
  93760. var viewerModel_1 = __webpack_require__(15);
  93761. var ModelLoader = (function () {
  93762. function ModelLoader(_viewer) {
  93763. this._viewer = _viewer;
  93764. this._disposed = false;
  93765. this._loaders = [];
  93766. this._loadId = 0;
  93767. }
  93768. ModelLoader.prototype.load = function (modelConfiguration) {
  93769. var model = new viewerModel_1.ViewerModel(this._viewer.scene, modelConfiguration);
  93770. model.loadId = this._loadId++;
  93771. this._loaders.push(model.loader);
  93772. return model;
  93773. };
  93774. ModelLoader.prototype.dispose = function () {
  93775. this._loaders.forEach(function (loader) {
  93776. if (loader.name === "gltf") {
  93777. loader.dispose();
  93778. }
  93779. });
  93780. this._loaders.length = 0;
  93781. this._disposed = true;
  93782. };
  93783. return ModelLoader;
  93784. }());
  93785. exports.ModelLoader = ModelLoader;
  93786. /***/ }),
  93787. /* 15 */
  93788. /***/ (function(module, exports, __webpack_require__) {
  93789. "use strict";
  93790. Object.defineProperty(exports, "__esModule", { value: true });
  93791. var babylonjs_1 = __webpack_require__(0);
  93792. var modelAnimation_1 = __webpack_require__(32);
  93793. var deepmerge = __webpack_require__(2);
  93794. var ModelState;
  93795. (function (ModelState) {
  93796. ModelState[ModelState["INIT"] = 0] = "INIT";
  93797. ModelState[ModelState["LOADING"] = 1] = "LOADING";
  93798. ModelState[ModelState["LOADED"] = 2] = "LOADED";
  93799. ModelState[ModelState["CANCELED"] = 3] = "CANCELED";
  93800. ModelState[ModelState["ERROR"] = 4] = "ERROR";
  93801. })(ModelState = exports.ModelState || (exports.ModelState = {}));
  93802. var ViewerModel = (function () {
  93803. function ViewerModel(_scene, _modelConfiguration, disableAutoLoad) {
  93804. if (disableAutoLoad === void 0) { disableAutoLoad = false; }
  93805. this._scene = _scene;
  93806. this._modelConfiguration = _modelConfiguration;
  93807. this.meshes = [];
  93808. this.particleSystems = [];
  93809. this.skeletons = [];
  93810. this._loaderDisposed = false;
  93811. this.onLoadedObservable = new babylonjs_1.Observable();
  93812. this.onLoadErrorObservable = new babylonjs_1.Observable();
  93813. this.onLoadProgressObservable = new babylonjs_1.Observable();
  93814. this.onAfterConfigure = new babylonjs_1.Observable();
  93815. this.state = ModelState.INIT;
  93816. this._animations = [];
  93817. if (!disableAutoLoad) {
  93818. this._initLoad();
  93819. }
  93820. }
  93821. ViewerModel.prototype.load = function () {
  93822. if (this.loader) {
  93823. babylonjs_1.Tools.Error("Model was already loaded or in the process of loading.");
  93824. }
  93825. else {
  93826. this._initLoad();
  93827. }
  93828. };
  93829. ViewerModel.prototype.cancelLoad = function () {
  93830. if (this.loader && this.loader.name === "gltf") {
  93831. var gltfLoader = this.loader;
  93832. gltfLoader.dispose();
  93833. this.state = ModelState.CANCELED;
  93834. }
  93835. };
  93836. Object.defineProperty(ViewerModel.prototype, "configuration", {
  93837. get: function () {
  93838. return this._modelConfiguration;
  93839. },
  93840. set: function (newConfiguration) {
  93841. this._modelConfiguration = newConfiguration;
  93842. this._configureModel();
  93843. },
  93844. enumerable: true,
  93845. configurable: true
  93846. });
  93847. ViewerModel.prototype.updateConfiguration = function (newConfiguration) {
  93848. this._modelConfiguration = deepmerge(this._modelConfiguration, newConfiguration);
  93849. this._configureModel();
  93850. };
  93851. ViewerModel.prototype.initAnimations = function () {
  93852. var _this = this;
  93853. this._animations.forEach(function (a) {
  93854. a.dispose();
  93855. });
  93856. this._animations.length = 0;
  93857. if (this.loader.name !== 'gltf') {
  93858. this.skeletons.forEach(function (skeleton, idx) {
  93859. var ag = new babylonjs_1.AnimationGroup("animation-" + idx, _this._scene);
  93860. skeleton.getAnimatables().forEach(function (a) {
  93861. if (a.animations[0]) {
  93862. ag.addTargetedAnimation(a.animations[0], a);
  93863. }
  93864. });
  93865. _this.addAnimationGroup(ag);
  93866. });
  93867. }
  93868. if (!this._modelConfiguration)
  93869. return;
  93870. if (this._modelConfiguration.animation) {
  93871. if (this._modelConfiguration.animation.playOnce) {
  93872. this._animations.forEach(function (a) {
  93873. a.playMode = modelAnimation_1.AnimationPlayMode.ONCE;
  93874. });
  93875. }
  93876. if (this._modelConfiguration.animation.autoStart && this._animations.length) {
  93877. var animationName = this._modelConfiguration.animation.autoStart === true ?
  93878. this._animations[0].name : this._modelConfiguration.animation.autoStart;
  93879. this.playAnimation(animationName);
  93880. }
  93881. }
  93882. };
  93883. ViewerModel.prototype.addAnimationGroup = function (animationGroup) {
  93884. this._animations.push(new modelAnimation_1.GroupModelAnimation(animationGroup));
  93885. };
  93886. ViewerModel.prototype.getAnimations = function () {
  93887. return this._animations;
  93888. };
  93889. ViewerModel.prototype.getAnimationNames = function () {
  93890. return this._animations.map(function (a) { return a.name; });
  93891. };
  93892. ViewerModel.prototype._getAnimationByName = function (name) {
  93893. var filtered = this._animations.filter(function (a) { return a.name === name; });
  93894. if (filtered.length === 1) {
  93895. return filtered[0];
  93896. }
  93897. else {
  93898. return null;
  93899. }
  93900. };
  93901. ViewerModel.prototype.playAnimation = function (name) {
  93902. var animation = this._getAnimationByName(name);
  93903. if (animation) {
  93904. if (this.currentAnimation) {
  93905. this.currentAnimation.stop();
  93906. }
  93907. this.currentAnimation = animation;
  93908. animation.start();
  93909. return animation;
  93910. }
  93911. else {
  93912. throw new Error("animation not found - " + name);
  93913. }
  93914. };
  93915. ViewerModel.prototype._configureModel = function () {
  93916. var meshesWithNoParent = this.meshes.filter(function (m) { return !m.parent; });
  93917. var updateMeshesWithNoParent = function (variable, value, param) {
  93918. meshesWithNoParent.forEach(function (mesh) {
  93919. if (param) {
  93920. mesh[variable][param] = value;
  93921. }
  93922. else {
  93923. mesh[variable] = value;
  93924. }
  93925. });
  93926. };
  93927. var updateXYZ = function (variable, configValues) {
  93928. if (configValues.x !== undefined) {
  93929. updateMeshesWithNoParent(variable, configValues.x, 'x');
  93930. }
  93931. if (configValues.y !== undefined) {
  93932. updateMeshesWithNoParent(variable, configValues.y, 'y');
  93933. }
  93934. if (configValues.z !== undefined) {
  93935. updateMeshesWithNoParent(variable, configValues.z, 'z');
  93936. }
  93937. if (configValues.w !== undefined) {
  93938. updateMeshesWithNoParent(variable, configValues.w, 'w');
  93939. }
  93940. };
  93941. if (this._modelConfiguration.position) {
  93942. updateXYZ('position', this._modelConfiguration.position);
  93943. }
  93944. if (this._modelConfiguration.rotation) {
  93945. if (this._modelConfiguration.rotation.w) {
  93946. meshesWithNoParent.forEach(function (mesh) {
  93947. if (!mesh.rotationQuaternion) {
  93948. mesh.rotationQuaternion = new babylonjs_1.Quaternion();
  93949. }
  93950. });
  93951. updateXYZ('rotationQuaternion', this._modelConfiguration.rotation);
  93952. }
  93953. else {
  93954. updateXYZ('rotation', this._modelConfiguration.rotation);
  93955. }
  93956. }
  93957. if (this._modelConfiguration.scaling) {
  93958. updateXYZ('scaling', this._modelConfiguration.scaling);
  93959. }
  93960. if (this._modelConfiguration.castShadow) {
  93961. this.meshes.forEach(function (mesh) {
  93962. babylonjs_1.Tags.AddTagsTo(mesh, 'castShadow');
  93963. });
  93964. }
  93965. if (this._modelConfiguration.normalize) {
  93966. var center = false;
  93967. var unitSize = false;
  93968. var parentIndex = void 0;
  93969. if (this._modelConfiguration.normalize === true) {
  93970. center = true;
  93971. unitSize = true;
  93972. parentIndex = 0;
  93973. }
  93974. else {
  93975. center = !!this._modelConfiguration.normalize.center;
  93976. unitSize = !!this._modelConfiguration.normalize.unitSize;
  93977. parentIndex = this._modelConfiguration.normalize.parentIndex;
  93978. }
  93979. var meshesToNormalize = [];
  93980. if (parentIndex !== undefined) {
  93981. meshesToNormalize.push(this.meshes[parentIndex]);
  93982. }
  93983. else {
  93984. meshesToNormalize = meshesWithNoParent;
  93985. }
  93986. if (unitSize) {
  93987. meshesToNormalize.forEach(function (mesh) {
  93988. mesh.normalizeToUnitCube(true);
  93989. mesh.computeWorldMatrix(true);
  93990. });
  93991. }
  93992. if (center) {
  93993. meshesToNormalize.forEach(function (mesh) {
  93994. var boundingInfo = mesh.getHierarchyBoundingVectors(true);
  93995. var sizeVec = boundingInfo.max.subtract(boundingInfo.min);
  93996. var halfSizeVec = sizeVec.scale(0.5);
  93997. var center = boundingInfo.min.add(halfSizeVec);
  93998. mesh.position = center.scale(-1);
  93999. mesh.position.y += halfSizeVec.y;
  94000. mesh.computeWorldMatrix(true);
  94001. });
  94002. }
  94003. }
  94004. this.onAfterConfigure.notifyObservers(this);
  94005. };
  94006. ViewerModel.prototype._initLoad = function () {
  94007. var _this = this;
  94008. if (!this._modelConfiguration.url) {
  94009. this.state = ModelState.ERROR;
  94010. babylonjs_1.Tools.Error("No URL provided");
  94011. return;
  94012. }
  94013. var filename = babylonjs_1.Tools.GetFilename(this._modelConfiguration.url) || this._modelConfiguration.url;
  94014. var base = this._modelConfiguration.root || babylonjs_1.Tools.GetFolderPath(this._modelConfiguration.url);
  94015. var plugin = this._modelConfiguration.loader;
  94016. this._loadedUrl = this._modelConfiguration.url;
  94017. this.loader = babylonjs_1.SceneLoader.ImportMesh(undefined, base, filename, this._scene, function (meshes, particleSystems, skeletons) {
  94018. meshes.forEach(function (mesh) {
  94019. babylonjs_1.Tags.AddTagsTo(mesh, "viewerMesh");
  94020. });
  94021. _this.meshes = meshes;
  94022. _this.particleSystems = particleSystems;
  94023. _this.skeletons = skeletons;
  94024. _this.initAnimations();
  94025. _this.onLoadedObservable.notifyObserversWithPromise(_this);
  94026. }, function (progressEvent) {
  94027. _this.onLoadProgressObservable.notifyObserversWithPromise(progressEvent);
  94028. }, function (e, m, exception) {
  94029. _this.state = ModelState.ERROR;
  94030. babylonjs_1.Tools.Error("Load Error: There was an error loading the model. " + m);
  94031. _this.onLoadErrorObservable.notifyObserversWithPromise({ message: m, exception: exception });
  94032. }, plugin);
  94033. if (this.loader.name === "gltf") {
  94034. var gltfLoader = this.loader;
  94035. gltfLoader.animationStartMode = 0;
  94036. gltfLoader.onDispose = function () {
  94037. _this._loaderDisposed = true;
  94038. };
  94039. gltfLoader.onAnimationGroupLoaded = function (ag) {
  94040. _this.addAnimationGroup(ag);
  94041. };
  94042. }
  94043. };
  94044. ViewerModel.prototype.dispose = function () {
  94045. this.onAfterConfigure.clear();
  94046. this.onLoadedObservable.clear();
  94047. this.onLoadErrorObservable.clear();
  94048. this.onLoadProgressObservable.clear();
  94049. if (this.loader && this.loader.name === "gltf") {
  94050. this.loader.dispose();
  94051. }
  94052. this.particleSystems.forEach(function (ps) { return ps.dispose(); });
  94053. this.particleSystems.length = 0;
  94054. this.skeletons.forEach(function (s) { return s.dispose(); });
  94055. this.skeletons.length = 0;
  94056. this._animations.forEach(function (ag) { return ag.dispose(); });
  94057. this._animations.length = 0;
  94058. this.meshes.forEach(function (m) { return m.dispose(); });
  94059. this.meshes.length = 0;
  94060. };
  94061. return ViewerModel;
  94062. }());
  94063. exports.ViewerModel = ViewerModel;
  94064. /***/ }),
  94065. /* 16 */
  94066. /***/ (function(module, exports, __webpack_require__) {
  94067. module.exports = __webpack_require__(17);
  94068. /***/ }),
  94069. /* 17 */
  94070. /***/ (function(module, exports, __webpack_require__) {
  94071. "use strict";
  94072. Object.defineProperty(exports, "__esModule", { value: true });
  94073. var mappers_1 = __webpack_require__(1);
  94074. exports.mapperManager = mappers_1.mapperManager;
  94075. var viewerManager_1 = __webpack_require__(4);
  94076. exports.viewerManager = viewerManager_1.viewerManager;
  94077. var defaultViewer_1 = __webpack_require__(5);
  94078. exports.DefaultViewer = defaultViewer_1.DefaultViewer;
  94079. var viewer_1 = __webpack_require__(6);
  94080. exports.AbstractViewer = viewer_1.AbstractViewer;
  94081. var modelLoader_1 = __webpack_require__(14);
  94082. exports.ModelLoader = modelLoader_1.ModelLoader;
  94083. var viewerModel_1 = __webpack_require__(15);
  94084. exports.ViewerModel = viewerModel_1.ViewerModel;
  94085. var babylonjs_1 = __webpack_require__(0);
  94086. __webpack_require__(33);
  94087. __webpack_require__(34);
  94088. var initializer_1 = __webpack_require__(35);
  94089. exports.InitTags = initializer_1.InitTags;
  94090. babylonjs_1.PromisePolyfill.Apply();
  94091. exports.disableInit = false;
  94092. document.addEventListener("DOMContentLoaded", init);
  94093. function init(event) {
  94094. document.removeEventListener("DOMContentLoaded", init);
  94095. if (exports.disableInit)
  94096. return;
  94097. initializer_1.InitTags();
  94098. }
  94099. function disposeAll() {
  94100. viewerManager_1.viewerManager.dispose();
  94101. mappers_1.mapperManager.dispose();
  94102. }
  94103. exports.disposeAll = disposeAll;
  94104. /***/ }),
  94105. /* 18 */
  94106. /***/ (function(module, exports) {
  94107. var g;
  94108. // This works in non-strict mode
  94109. g = (function() {
  94110. return this;
  94111. })();
  94112. try {
  94113. // This works if eval is allowed (see CSP)
  94114. g = g || Function("return this")() || (1,eval)("this");
  94115. } catch(e) {
  94116. // This works if the window reference is available
  94117. if(typeof window === "object")
  94118. g = window;
  94119. }
  94120. // g can still be undefined, but nothing to do about it...
  94121. // We return undefined, instead of nothing here, so it's
  94122. // easier to handle this case. if(!global) { ...}
  94123. module.exports = g;
  94124. /***/ }),
  94125. /* 19 */
  94126. /***/ (function(module, exports) {
  94127. if(typeof CANNON === 'undefined') {var e = new Error("Cannot find module \"CANNON\""); e.code = 'MODULE_NOT_FOUND'; throw e;}
  94128. module.exports = CANNON;
  94129. /***/ }),
  94130. /* 20 */
  94131. /***/ (function(module, exports) {
  94132. if(typeof OIMO === 'undefined') {var e = new Error("Cannot find module \"OIMO\""); e.code = 'MODULE_NOT_FOUND'; throw e;}
  94133. module.exports = OIMO;
  94134. /***/ }),
  94135. /* 21 */
  94136. /***/ (function(module, exports, __webpack_require__) {
  94137. "use strict";
  94138. Object.defineProperty(exports, "__esModule", { value: true });
  94139. var babylonjs_1 = __webpack_require__(0);
  94140. var helper_1 = __webpack_require__(3);
  94141. var TemplateManager = (function () {
  94142. function TemplateManager(containerElement) {
  94143. this.containerElement = containerElement;
  94144. this.templates = {};
  94145. this.onInit = new babylonjs_1.Observable();
  94146. this.onLoaded = new babylonjs_1.Observable();
  94147. this.onStateChange = new babylonjs_1.Observable();
  94148. this.onAllLoaded = new babylonjs_1.Observable();
  94149. this.onEventTriggered = new babylonjs_1.Observable();
  94150. this.eventManager = new eventManager_1.EventManager(this);
  94151. }
  94152. TemplateManager.prototype.initTemplate = function (templates) {
  94153. var _this = this;
  94154. var internalInit = function (dependencyMap, name, parentTemplate) {
  94155. var template = _this.templates[name];
  94156. var childrenTemplates = Object.keys(dependencyMap).map(function (childName) {
  94157. return internalInit(dependencyMap[childName], childName, template);
  94158. });
  94159. var addToParent = function () {
  94160. var containingElement = parentTemplate && parentTemplate.parent.querySelector(helper_1.camelToKebab(name)) || _this.containerElement;
  94161. template.appendTo(containingElement);
  94162. _this.checkLoadedState();
  94163. };
  94164. if (parentTemplate && !parentTemplate.parent) {
  94165. parentTemplate.onAppended.add(function () {
  94166. addToParent();
  94167. });
  94168. }
  94169. else {
  94170. addToParent();
  94171. }
  94172. return template;
  94173. };
  94174. return this.buildHTMLTree(templates).then(function (htmlTree) {
  94175. if (_this.templates['main']) {
  94176. internalInit(htmlTree, 'main');
  94177. }
  94178. else {
  94179. _this.checkLoadedState();
  94180. }
  94181. return;
  94182. });
  94183. };
  94184. TemplateManager.prototype.buildHTMLTree = function (templates) {
  94185. var _this = this;
  94186. var promises = Object.keys(templates).map(function (name) {
  94187. if (!templates[name])
  94188. return Promise.resolve(false);
  94189. var template = new Template(name, templates[name]);
  94190. template.onEventTriggered.add(function (eventData) { return _this.onEventTriggered.notifyObservers(eventData); });
  94191. _this.templates[name] = template;
  94192. return template.initPromise;
  94193. });
  94194. return Promise.all(promises).then(function () {
  94195. var templateStructure = {};
  94196. var buildTree = function (parentObject, name) {
  94197. _this.templates[name].isInHtmlTree = true;
  94198. var childNodes = _this.templates[name].getChildElements().filter(function (n) { return !!_this.templates[n]; });
  94199. childNodes.forEach(function (element) {
  94200. parentObject[element] = {};
  94201. buildTree(parentObject[element], element);
  94202. });
  94203. };
  94204. if (_this.templates['main']) {
  94205. buildTree(templateStructure, "main");
  94206. }
  94207. return templateStructure;
  94208. });
  94209. };
  94210. TemplateManager.prototype.getCanvas = function () {
  94211. return this.containerElement.querySelector('canvas');
  94212. };
  94213. TemplateManager.prototype.getTemplate = function (name) {
  94214. return this.templates[name];
  94215. };
  94216. TemplateManager.prototype.checkLoadedState = function () {
  94217. var _this = this;
  94218. var done = Object.keys(this.templates).length === 0 || Object.keys(this.templates).every(function (key) {
  94219. return (_this.templates[key].isLoaded && !!_this.templates[key].parent) || !_this.templates[key].isInHtmlTree;
  94220. });
  94221. if (done) {
  94222. this.onAllLoaded.notifyObservers(this);
  94223. }
  94224. };
  94225. TemplateManager.prototype.dispose = function () {
  94226. var _this = this;
  94227. Object.keys(this.templates).forEach(function (template) {
  94228. _this.templates[template].dispose();
  94229. });
  94230. this.templates = {};
  94231. this.eventManager.dispose();
  94232. this.onInit.clear();
  94233. this.onAllLoaded.clear();
  94234. this.onEventTriggered.clear();
  94235. this.onLoaded.clear();
  94236. this.onStateChange.clear();
  94237. };
  94238. return TemplateManager;
  94239. }());
  94240. exports.TemplateManager = TemplateManager;
  94241. var Handlebars = __webpack_require__(22);
  94242. var eventManager_1 = __webpack_require__(23);
  94243. Handlebars.registerHelper('eachInMap', function (map, block) {
  94244. var out = '';
  94245. Object.keys(map).map(function (prop) {
  94246. var data = map[prop];
  94247. if (typeof data === 'object') {
  94248. data.id = data.id || prop;
  94249. out += block.fn(data);
  94250. }
  94251. else {
  94252. out += block.fn({ id: prop, value: data });
  94253. }
  94254. });
  94255. return out;
  94256. });
  94257. var Template = (function () {
  94258. function Template(name, _configuration) {
  94259. var _this = this;
  94260. this.name = name;
  94261. this._configuration = _configuration;
  94262. this.onInit = new babylonjs_1.Observable();
  94263. this.onLoaded = new babylonjs_1.Observable();
  94264. this.onAppended = new babylonjs_1.Observable();
  94265. this.onStateChange = new babylonjs_1.Observable();
  94266. this.onEventTriggered = new babylonjs_1.Observable();
  94267. this.loadRequests = [];
  94268. this.isLoaded = false;
  94269. this.isShown = false;
  94270. this.isInHtmlTree = false;
  94271. this.onInit.notifyObservers(this);
  94272. var htmlContentPromise = this.getTemplateAsHtml(_configuration);
  94273. this.initPromise = htmlContentPromise.then(function (htmlTemplate) {
  94274. if (htmlTemplate) {
  94275. _this.htmlTemplate = htmlTemplate;
  94276. var compiledTemplate = Handlebars.compile(htmlTemplate);
  94277. var config = _this._configuration.params || {};
  94278. var rawHtml = compiledTemplate(config);
  94279. _this.fragment = document.createRange().createContextualFragment(rawHtml);
  94280. _this.isLoaded = true;
  94281. _this.isShown = true;
  94282. _this.onLoaded.notifyObservers(_this);
  94283. }
  94284. return _this;
  94285. });
  94286. }
  94287. Template.prototype.updateParams = function (params) {
  94288. this._configuration.params = params;
  94289. if (this.isLoaded) {
  94290. this.dispose();
  94291. }
  94292. var compiledTemplate = Handlebars.compile(this.htmlTemplate);
  94293. var config = this._configuration.params || {};
  94294. var rawHtml = compiledTemplate(config);
  94295. this.fragment = document.createRange().createContextualFragment(rawHtml);
  94296. if (this.parent) {
  94297. this.appendTo(this.parent, true);
  94298. }
  94299. };
  94300. Object.defineProperty(Template.prototype, "configuration", {
  94301. get: function () {
  94302. return this._configuration;
  94303. },
  94304. enumerable: true,
  94305. configurable: true
  94306. });
  94307. Template.prototype.getChildElements = function () {
  94308. var childrenArray = [];
  94309. var children = this.fragment.children;
  94310. if (!children) {
  94311. children = this.fragment.querySelectorAll('*');
  94312. }
  94313. for (var i = 0; i < children.length; ++i) {
  94314. childrenArray.push(helper_1.kebabToCamel(children.item(i).nodeName.toLowerCase()));
  94315. }
  94316. return childrenArray;
  94317. };
  94318. Template.prototype.appendTo = function (parent, forceRemove) {
  94319. var _this = this;
  94320. if (this.parent) {
  94321. if (forceRemove) {
  94322. this.parent.removeChild(this.fragment);
  94323. }
  94324. else {
  94325. return;
  94326. }
  94327. }
  94328. this.parent = parent;
  94329. if (this._configuration.id) {
  94330. this.parent.id = this._configuration.id;
  94331. }
  94332. this.fragment = this.parent.appendChild(this.fragment);
  94333. setTimeout(function () {
  94334. _this.registerEvents();
  94335. _this.onAppended.notifyObservers(_this);
  94336. });
  94337. };
  94338. Template.prototype.show = function (visibilityFunction) {
  94339. var _this = this;
  94340. if (this.isHiding)
  94341. return Promise.resolve(this);
  94342. return Promise.resolve().then(function () {
  94343. _this.isShowing = true;
  94344. if (visibilityFunction) {
  94345. return visibilityFunction(_this);
  94346. }
  94347. else {
  94348. _this.parent.style.display = 'flex';
  94349. return _this;
  94350. }
  94351. }).then(function () {
  94352. _this.isShown = true;
  94353. _this.isShowing = false;
  94354. _this.onStateChange.notifyObservers(_this);
  94355. return _this;
  94356. });
  94357. };
  94358. Template.prototype.hide = function (visibilityFunction) {
  94359. var _this = this;
  94360. if (this.isShowing)
  94361. return Promise.resolve(this);
  94362. return Promise.resolve().then(function () {
  94363. _this.isHiding = true;
  94364. if (visibilityFunction) {
  94365. return visibilityFunction(_this);
  94366. }
  94367. else {
  94368. _this.parent.style.display = 'hide';
  94369. return _this;
  94370. }
  94371. }).then(function () {
  94372. _this.isShown = false;
  94373. _this.isHiding = false;
  94374. _this.onStateChange.notifyObservers(_this);
  94375. return _this;
  94376. });
  94377. };
  94378. Template.prototype.dispose = function () {
  94379. this.onAppended.clear();
  94380. this.onEventTriggered.clear();
  94381. this.onInit.clear();
  94382. this.onLoaded.clear();
  94383. this.onStateChange.clear();
  94384. this.isLoaded = false;
  94385. try {
  94386. this.parent.removeChild(this.fragment);
  94387. }
  94388. catch (e) {
  94389. }
  94390. this.loadRequests.forEach(function (request) {
  94391. request.abort();
  94392. });
  94393. if (this.registeredEvents) {
  94394. this.registeredEvents.forEach(function (evt) {
  94395. evt.htmlElement.removeEventListener(evt.eventName, evt.function);
  94396. });
  94397. }
  94398. delete this.fragment;
  94399. };
  94400. Template.prototype.getTemplateAsHtml = function (templateConfig) {
  94401. var _this = this;
  94402. if (!templateConfig) {
  94403. return Promise.reject('No templateConfig provided');
  94404. }
  94405. else if (templateConfig.html !== undefined) {
  94406. return Promise.resolve(templateConfig.html);
  94407. }
  94408. else {
  94409. var location_1 = getTemplateLocation(templateConfig);
  94410. if (helper_1.isUrl(location_1)) {
  94411. return new Promise(function (resolve, reject) {
  94412. var fileRequest = babylonjs_1.Tools.LoadFile(location_1, function (data) {
  94413. resolve(data);
  94414. }, undefined, undefined, false, function (request, error) {
  94415. reject(error);
  94416. });
  94417. _this.loadRequests.push(fileRequest);
  94418. });
  94419. }
  94420. else {
  94421. location_1 = location_1.replace('#', '');
  94422. var element = document.getElementById(location_1);
  94423. if (element) {
  94424. return Promise.resolve(element.innerHTML);
  94425. }
  94426. else {
  94427. return Promise.reject('Template ID not found');
  94428. }
  94429. }
  94430. }
  94431. };
  94432. Template.prototype.registerEvents = function () {
  94433. var _this = this;
  94434. this.registeredEvents = this.registeredEvents || [];
  94435. if (this.registeredEvents.length) {
  94436. this.registeredEvents.forEach(function (evt) {
  94437. evt.htmlElement.removeEventListener(evt.eventName, evt.function);
  94438. });
  94439. }
  94440. if (this._configuration.events) {
  94441. var _loop_1 = function (eventName) {
  94442. if (this_1._configuration.events && this_1._configuration.events[eventName]) {
  94443. var functionToFire_1 = function (selector, event) {
  94444. _this.onEventTriggered.notifyObservers({ event: event, template: _this, selector: selector });
  94445. };
  94446. if (typeof this_1._configuration.events[eventName] === 'boolean') {
  94447. var binding = functionToFire_1.bind(this_1, '#' + this_1.parent.id);
  94448. this_1.parent.addEventListener(eventName, functionToFire_1.bind(this_1, '#' + this_1.parent.id), false);
  94449. this_1.registeredEvents.push({
  94450. htmlElement: this_1.parent,
  94451. eventName: eventName,
  94452. function: binding
  94453. });
  94454. }
  94455. else if (typeof this_1._configuration.events[eventName] === 'object') {
  94456. var selectorsArray = Object.keys(this_1._configuration.events[eventName] || {});
  94457. var event_1 = this_1._configuration.events[eventName] || {};
  94458. selectorsArray.filter(function (selector) { return event_1[selector]; }).forEach(function (selector) {
  94459. if (selector && selector.indexOf('#') !== 0) {
  94460. selector = '#' + selector;
  94461. }
  94462. var htmlElement = _this.parent.querySelector(selector);
  94463. if (htmlElement) {
  94464. var binding = functionToFire_1.bind(_this, selector);
  94465. htmlElement.addEventListener(eventName, binding, false);
  94466. _this.registeredEvents.push({
  94467. htmlElement: htmlElement,
  94468. eventName: eventName,
  94469. function: binding
  94470. });
  94471. }
  94472. });
  94473. }
  94474. }
  94475. };
  94476. var this_1 = this;
  94477. for (var eventName in this._configuration.events) {
  94478. _loop_1(eventName);
  94479. }
  94480. }
  94481. };
  94482. return Template;
  94483. }());
  94484. exports.Template = Template;
  94485. function getTemplateLocation(templateConfig) {
  94486. if (!templateConfig || typeof templateConfig === 'string') {
  94487. return templateConfig;
  94488. }
  94489. else {
  94490. return templateConfig.location;
  94491. }
  94492. }
  94493. exports.getTemplateLocation = getTemplateLocation;
  94494. /***/ }),
  94495. /* 22 */
  94496. /***/ (function(module, exports, __webpack_require__) {
  94497. /**!
  94498. @license
  94499. handlebars v4.0.11
  94500. Copyright (C) 2011-2017 by Yehuda Katz
  94501. Permission is hereby granted, free of charge, to any person obtaining a copy
  94502. of this software and associated documentation files (the "Software"), to deal
  94503. in the Software without restriction, including without limitation the rights
  94504. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  94505. copies of the Software, and to permit persons to whom the Software is
  94506. furnished to do so, subject to the following conditions:
  94507. The above copyright notice and this permission notice shall be included in
  94508. all copies or substantial portions of the Software.
  94509. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  94510. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  94511. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  94512. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  94513. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  94514. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  94515. THE SOFTWARE.
  94516. */
  94517. !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],
  94518. 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){
  94519. 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"]}])});
  94520. /***/ }),
  94521. /* 23 */
  94522. /***/ (function(module, exports, __webpack_require__) {
  94523. "use strict";
  94524. Object.defineProperty(exports, "__esModule", { value: true });
  94525. var EventManager = (function () {
  94526. function EventManager(templateManager) {
  94527. var _this = this;
  94528. this.templateManager = templateManager;
  94529. this.callbacksContainer = {};
  94530. this.templateManager.onEventTriggered.add(function (eventData) {
  94531. _this.eventTriggered(eventData);
  94532. });
  94533. }
  94534. EventManager.prototype.registerCallback = function (templateName, callback, eventType, selector) {
  94535. if (!this.callbacksContainer[templateName]) {
  94536. this.callbacksContainer[templateName] = [];
  94537. }
  94538. this.callbacksContainer[templateName].push({
  94539. eventType: eventType,
  94540. callback: callback
  94541. });
  94542. };
  94543. EventManager.prototype.unregisterCallback = function (templateName, callback, eventType, selector) {
  94544. var callbackDefs = this.callbacksContainer[templateName] || [];
  94545. this.callbacksContainer[templateName] = callbackDefs.filter(function (callbackDef) { return (!callbackDef.eventType || callbackDef.eventType === eventType) && (!callbackDef.selector || callbackDef.selector === selector); });
  94546. };
  94547. EventManager.prototype.eventTriggered = function (data) {
  94548. var templateName = data.template.name;
  94549. var eventType = data.event.type;
  94550. var selector = data.selector;
  94551. var callbackDefs = this.callbacksContainer[templateName] || [];
  94552. callbackDefs.filter(function (callbackDef) { return (!callbackDef.eventType || callbackDef.eventType === eventType) && (!callbackDef.selector || callbackDef.selector === selector); }).forEach(function (callbackDef) {
  94553. callbackDef.callback(data);
  94554. });
  94555. };
  94556. EventManager.prototype.dispose = function () {
  94557. this.callbacksContainer = {};
  94558. };
  94559. return EventManager;
  94560. }());
  94561. exports.EventManager = EventManager;
  94562. /***/ }),
  94563. /* 24 */
  94564. /***/ (function(module, exports, __webpack_require__) {
  94565. "use strict";
  94566. Object.defineProperty(exports, "__esModule", { value: true });
  94567. var mappers_1 = __webpack_require__(1);
  94568. var types_1 = __webpack_require__(25);
  94569. var deepmerge = __webpack_require__(2);
  94570. var babylonjs_1 = __webpack_require__(0);
  94571. var ConfigurationLoader = (function () {
  94572. function ConfigurationLoader(_enableCache) {
  94573. if (_enableCache === void 0) { _enableCache = false; }
  94574. this._enableCache = _enableCache;
  94575. this.configurationCache = {};
  94576. this.loadRequests = [];
  94577. }
  94578. ConfigurationLoader.prototype.loadConfiguration = function (initConfig, callback) {
  94579. var _this = this;
  94580. if (initConfig === void 0) { initConfig = {}; }
  94581. var loadedConfig = deepmerge({}, initConfig);
  94582. var extendedConfiguration = types_1.getConfigurationType(loadedConfig.extends || "");
  94583. loadedConfig = deepmerge(extendedConfiguration, loadedConfig);
  94584. if (loadedConfig.configuration) {
  94585. var mapperType_1 = "json";
  94586. return Promise.resolve().then(function () {
  94587. if (typeof loadedConfig.configuration === "string" || (loadedConfig.configuration && loadedConfig.configuration.url)) {
  94588. var url = '';
  94589. if (typeof loadedConfig.configuration === "string") {
  94590. url = loadedConfig.configuration;
  94591. }
  94592. if (typeof loadedConfig.configuration === "object" && loadedConfig.configuration.url) {
  94593. url = loadedConfig.configuration.url;
  94594. var type = loadedConfig.configuration.mapper;
  94595. if (!type) {
  94596. type = loadedConfig.configuration.url.split('.').pop();
  94597. }
  94598. mapperType_1 = type || mapperType_1;
  94599. }
  94600. return _this.loadFile(url);
  94601. }
  94602. else {
  94603. if (typeof loadedConfig.configuration === "object") {
  94604. mapperType_1 = loadedConfig.configuration.mapper || mapperType_1;
  94605. return loadedConfig.configuration.payload || {};
  94606. }
  94607. return {};
  94608. }
  94609. }).then(function (data) {
  94610. var mapper = mappers_1.mapperManager.getMapper(mapperType_1);
  94611. var parsed = mapper.map(data);
  94612. var merged = deepmerge(loadedConfig, parsed);
  94613. if (callback)
  94614. callback(merged);
  94615. return merged;
  94616. });
  94617. }
  94618. else {
  94619. if (callback)
  94620. callback(loadedConfig);
  94621. return Promise.resolve(loadedConfig);
  94622. }
  94623. };
  94624. ConfigurationLoader.prototype.dispose = function () {
  94625. this.loadRequests.forEach(function (request) {
  94626. request.abort();
  94627. });
  94628. this.loadRequests.length = 0;
  94629. };
  94630. ConfigurationLoader.prototype.loadFile = function (url) {
  94631. var _this = this;
  94632. var cacheReference = this.configurationCache;
  94633. if (this._enableCache && cacheReference[url]) {
  94634. return Promise.resolve(cacheReference[url]);
  94635. }
  94636. return new Promise(function (resolve, reject) {
  94637. var fileRequest = babylonjs_1.Tools.LoadFile(url, function (result) {
  94638. var idx = _this.loadRequests.indexOf(fileRequest);
  94639. if (idx !== -1)
  94640. _this.loadRequests.splice(idx, 1);
  94641. if (_this._enableCache)
  94642. cacheReference[url] = result;
  94643. resolve(result);
  94644. }, undefined, undefined, false, function (request, error) {
  94645. var idx = _this.loadRequests.indexOf(fileRequest);
  94646. if (idx !== -1)
  94647. _this.loadRequests.splice(idx, 1);
  94648. reject(error);
  94649. });
  94650. _this.loadRequests.push(fileRequest);
  94651. });
  94652. };
  94653. return ConfigurationLoader;
  94654. }());
  94655. exports.ConfigurationLoader = ConfigurationLoader;
  94656. /***/ }),
  94657. /* 25 */
  94658. /***/ (function(module, exports, __webpack_require__) {
  94659. "use strict";
  94660. Object.defineProperty(exports, "__esModule", { value: true });
  94661. var minimal_1 = __webpack_require__(26);
  94662. exports.minimalConfiguration = minimal_1.minimalConfiguration;
  94663. var default_1 = __webpack_require__(27);
  94664. exports.defaultConfiguration = default_1.defaultConfiguration;
  94665. var getConfigurationType = function (type) {
  94666. switch (type) {
  94667. case 'default':
  94668. return default_1.defaultConfiguration;
  94669. case 'minimal':
  94670. return minimal_1.minimalConfiguration;
  94671. case 'none':
  94672. return {};
  94673. default:
  94674. return default_1.defaultConfiguration;
  94675. }
  94676. };
  94677. exports.getConfigurationType = getConfigurationType;
  94678. /***/ }),
  94679. /* 26 */
  94680. /***/ (function(module, exports, __webpack_require__) {
  94681. "use strict";
  94682. Object.defineProperty(exports, "__esModule", { value: true });
  94683. exports.minimalConfiguration = {
  94684. version: "0.1",
  94685. templates: {
  94686. main: {
  94687. html: __webpack_require__(7)
  94688. },
  94689. loadingScreen: {
  94690. html: __webpack_require__(8),
  94691. params: {
  94692. backgroundColor: "#000000",
  94693. loadingImage: __webpack_require__(9)
  94694. }
  94695. },
  94696. viewer: {
  94697. html: __webpack_require__(10),
  94698. },
  94699. overlay: {
  94700. html: __webpack_require__(11),
  94701. params: {
  94702. closeImage: __webpack_require__(12),
  94703. closeText: 'Close'
  94704. }
  94705. },
  94706. error: {
  94707. html: __webpack_require__(13)
  94708. }
  94709. },
  94710. engine: {
  94711. antialiasing: true
  94712. }
  94713. };
  94714. /***/ }),
  94715. /* 27 */
  94716. /***/ (function(module, exports, __webpack_require__) {
  94717. "use strict";
  94718. Object.defineProperty(exports, "__esModule", { value: true });
  94719. exports.defaultConfiguration = {
  94720. version: "3.2.0-alpha4",
  94721. templates: {
  94722. main: {
  94723. html: __webpack_require__(7)
  94724. },
  94725. loadingScreen: {
  94726. html: __webpack_require__(8),
  94727. params: {
  94728. backgroundColor: "#000000",
  94729. loadingImage: __webpack_require__(9)
  94730. }
  94731. },
  94732. viewer: {
  94733. html: __webpack_require__(10),
  94734. events: {
  94735. pointerout: true,
  94736. pointerdown: true,
  94737. pointerup: true
  94738. }
  94739. },
  94740. navBar: {
  94741. html: __webpack_require__(28),
  94742. params: {
  94743. buttons: {
  94744. "fullscreen-button": {
  94745. altText: "Fullscreen",
  94746. image: __webpack_require__(29)
  94747. }
  94748. },
  94749. visibilityTimeout: 2000
  94750. },
  94751. events: {
  94752. pointerdown: { 'fullscreen-button': true },
  94753. pointerover: true
  94754. }
  94755. },
  94756. overlay: {
  94757. html: __webpack_require__(11),
  94758. params: {
  94759. closeImage: __webpack_require__(12),
  94760. closeText: 'Close'
  94761. }
  94762. },
  94763. help: {
  94764. html: __webpack_require__(30)
  94765. },
  94766. share: {
  94767. html: __webpack_require__(31)
  94768. },
  94769. error: {
  94770. html: __webpack_require__(13)
  94771. }
  94772. },
  94773. camera: {
  94774. behaviors: {
  94775. autoRotate: 0,
  94776. framing: {
  94777. type: 2,
  94778. zoomOnBoundingInfo: true,
  94779. zoomStopsAnimation: false
  94780. }
  94781. }
  94782. },
  94783. skybox: {
  94784. pbr: true,
  94785. blur: 0.7,
  94786. infiniteDIstance: false,
  94787. },
  94788. ground: true,
  94789. engine: {
  94790. antialiasing: true
  94791. },
  94792. scene: {
  94793. imageProcessingConfiguration: {
  94794. exposure: 1.4,
  94795. contrast: 1.66,
  94796. toneMappingEnabled: true
  94797. }
  94798. }
  94799. };
  94800. /***/ }),
  94801. /* 28 */
  94802. /***/ (function(module, exports) {
  94803. 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>";
  94804. /***/ }),
  94805. /* 29 */
  94806. /***/ (function(module, exports) {
  94807. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwAQAAAAB/ecQqAAAAAnRSTlMAAHaTzTgAAAAeSURBVHgBY6ASsP/A/wcXZQNGhCkyAfE24HUndQAAXlkXcQ24P7gAAAAASUVORK5CYII="
  94808. /***/ }),
  94809. /* 30 */
  94810. /***/ (function(module, exports) {
  94811. module.exports = "HELP";
  94812. /***/ }),
  94813. /* 31 */
  94814. /***/ (function(module, exports) {
  94815. module.exports = "SHARE";
  94816. /***/ }),
  94817. /* 32 */
  94818. /***/ (function(module, exports, __webpack_require__) {
  94819. "use strict";
  94820. Object.defineProperty(exports, "__esModule", { value: true });
  94821. var AnimationPlayMode;
  94822. (function (AnimationPlayMode) {
  94823. AnimationPlayMode[AnimationPlayMode["ONCE"] = 0] = "ONCE";
  94824. AnimationPlayMode[AnimationPlayMode["LOOP"] = 1] = "LOOP";
  94825. })(AnimationPlayMode = exports.AnimationPlayMode || (exports.AnimationPlayMode = {}));
  94826. var AnimationState;
  94827. (function (AnimationState) {
  94828. AnimationState[AnimationState["INIT"] = 0] = "INIT";
  94829. AnimationState[AnimationState["PLAYING"] = 1] = "PLAYING";
  94830. AnimationState[AnimationState["PAUSED"] = 2] = "PAUSED";
  94831. AnimationState[AnimationState["STOPPED"] = 3] = "STOPPED";
  94832. AnimationState[AnimationState["ENDED"] = 4] = "ENDED";
  94833. })(AnimationState = exports.AnimationState || (exports.AnimationState = {}));
  94834. var GroupModelAnimation = (function () {
  94835. function GroupModelAnimation(_animationGroup) {
  94836. var _this = this;
  94837. this._animationGroup = _animationGroup;
  94838. this._state = AnimationState.INIT;
  94839. this._playMode = AnimationPlayMode.LOOP;
  94840. this._animationGroup.onAnimationEndObservable.add(function () {
  94841. _this.stop();
  94842. _this._state = AnimationState.ENDED;
  94843. });
  94844. }
  94845. Object.defineProperty(GroupModelAnimation.prototype, "name", {
  94846. get: function () {
  94847. return this._animationGroup.name;
  94848. },
  94849. enumerable: true,
  94850. configurable: true
  94851. });
  94852. Object.defineProperty(GroupModelAnimation.prototype, "state", {
  94853. get: function () {
  94854. return this._state;
  94855. },
  94856. enumerable: true,
  94857. configurable: true
  94858. });
  94859. Object.defineProperty(GroupModelAnimation.prototype, "speedRatio", {
  94860. get: function () {
  94861. return this._animationGroup.speedRatio;
  94862. },
  94863. set: function (value) {
  94864. this._animationGroup.speedRatio = value;
  94865. },
  94866. enumerable: true,
  94867. configurable: true
  94868. });
  94869. Object.defineProperty(GroupModelAnimation.prototype, "frames", {
  94870. get: function () {
  94871. var animationFrames = this._animationGroup.targetedAnimations.map(function (ta) {
  94872. var keys = ta.animation.getKeys();
  94873. return keys[keys.length - 1].frame;
  94874. });
  94875. return Math.max.apply(null, animationFrames);
  94876. },
  94877. enumerable: true,
  94878. configurable: true
  94879. });
  94880. Object.defineProperty(GroupModelAnimation.prototype, "currentFrame", {
  94881. get: function () {
  94882. for (var i = 0; i < this._animationGroup.animatables.length; ++i) {
  94883. var animatable = this._animationGroup.animatables[i];
  94884. var animations = animatable.getAnimations();
  94885. if (!animations || !animations.length) {
  94886. continue;
  94887. }
  94888. for (var idx = 0; idx < animations.length; ++idx) {
  94889. if (animations[idx].currentFrame) {
  94890. return animations[idx].currentFrame;
  94891. }
  94892. }
  94893. }
  94894. return 0;
  94895. },
  94896. enumerable: true,
  94897. configurable: true
  94898. });
  94899. Object.defineProperty(GroupModelAnimation.prototype, "fps", {
  94900. get: function () {
  94901. for (var i = 0; i < this._animationGroup.animatables.length; ++i) {
  94902. var animatable = this._animationGroup.animatables[i];
  94903. var animations = animatable.getAnimations();
  94904. if (!animations || !animations.length) {
  94905. continue;
  94906. }
  94907. for (var idx = 0; idx < animations.length; ++idx) {
  94908. if (animations[idx].animation && animations[idx].animation.framePerSecond) {
  94909. return animations[idx].animation.framePerSecond;
  94910. }
  94911. }
  94912. }
  94913. return 0;
  94914. },
  94915. enumerable: true,
  94916. configurable: true
  94917. });
  94918. Object.defineProperty(GroupModelAnimation.prototype, "playMode", {
  94919. get: function () {
  94920. return this._playMode;
  94921. },
  94922. set: function (value) {
  94923. if (value === this._playMode) {
  94924. return;
  94925. }
  94926. this._playMode = value;
  94927. if (this.state === AnimationState.PLAYING) {
  94928. this._animationGroup.play(this._playMode === AnimationPlayMode.LOOP);
  94929. }
  94930. else {
  94931. this._animationGroup.reset();
  94932. this._state = AnimationState.INIT;
  94933. }
  94934. },
  94935. enumerable: true,
  94936. configurable: true
  94937. });
  94938. GroupModelAnimation.prototype.reset = function () {
  94939. this._animationGroup.reset();
  94940. };
  94941. GroupModelAnimation.prototype.restart = function () {
  94942. this._animationGroup.restart();
  94943. };
  94944. GroupModelAnimation.prototype.goToFrame = function (frameNumber) {
  94945. this._animationGroup['_animatables'].forEach(function (a) {
  94946. a.goToFrame(frameNumber);
  94947. });
  94948. };
  94949. GroupModelAnimation.prototype.start = function () {
  94950. this._animationGroup.start(this.playMode === AnimationPlayMode.LOOP, this.speedRatio);
  94951. if (this._animationGroup.isStarted) {
  94952. this._state = AnimationState.PLAYING;
  94953. }
  94954. };
  94955. GroupModelAnimation.prototype.pause = function () {
  94956. this._animationGroup.pause();
  94957. this._state = AnimationState.PAUSED;
  94958. };
  94959. GroupModelAnimation.prototype.stop = function () {
  94960. this._animationGroup.stop();
  94961. if (!this._animationGroup.isStarted) {
  94962. this._state = AnimationState.STOPPED;
  94963. }
  94964. };
  94965. GroupModelAnimation.prototype.dispose = function () {
  94966. this._animationGroup.dispose();
  94967. };
  94968. return GroupModelAnimation;
  94969. }());
  94970. exports.GroupModelAnimation = GroupModelAnimation;
  94971. /***/ }),
  94972. /* 33 */
  94973. /***/ (function(module, exports, __webpack_require__) {
  94974. 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};
  94975. 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)}}();
  94976. (function universalModuleDefinition(root, factory) {
  94977. var amdDependencies = [];
  94978. var BABYLON = root.BABYLON;
  94979. if(true) {
  94980. BABYLON = BABYLON || __webpack_require__(0);
  94981. module.exports = factory(BABYLON);
  94982. } else if(typeof define === 'function' && define.amd) {
  94983. amdDependencies.push("babylonjs");
  94984. define("babylonjs-loaders", amdDependencies, factory);
  94985. } else if(typeof exports === 'object') {
  94986. BABYLON = BABYLON || require("babylonjs");
  94987. exports["babylonjs-loaders"] = factory(BABYLON);
  94988. } else {
  94989. root["BABYLON"] = factory(BABYLON);
  94990. }
  94991. })(this, function(BABYLON) {
  94992. BABYLON = BABYLON || this.BABYLON;
  94993. "use strict";
  94994. var BABYLON;
  94995. (function (BABYLON) {
  94996. var STLFileLoader = /** @class */ (function () {
  94997. function STLFileLoader() {
  94998. this.solidPattern = /solid (\S*)([\S\s]*)endsolid[ ]*(\S*)/g;
  94999. this.facetsPattern = /facet([\s\S]*?)endfacet/g;
  95000. 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;
  95001. 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;
  95002. this.name = "stl";
  95003. // force data to come in as an ArrayBuffer
  95004. // we'll convert to string if it looks like it's an ASCII .stl
  95005. this.extensions = {
  95006. ".stl": { isBinary: true },
  95007. };
  95008. }
  95009. STLFileLoader.prototype.importMesh = function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  95010. var matches;
  95011. if (this.isBinary(data)) {
  95012. // binary .stl
  95013. var babylonMesh = new BABYLON.Mesh("stlmesh", scene);
  95014. this.parseBinary(babylonMesh, data);
  95015. if (meshes) {
  95016. meshes.push(babylonMesh);
  95017. }
  95018. return true;
  95019. }
  95020. // ASCII .stl
  95021. // convert to string
  95022. var array_buffer = new Uint8Array(data);
  95023. var str = '';
  95024. for (var i = 0; i < data.byteLength; i++) {
  95025. str += String.fromCharCode(array_buffer[i]); // implicitly assumes little-endian
  95026. }
  95027. data = str;
  95028. while (matches = this.solidPattern.exec(data)) {
  95029. var meshName = matches[1];
  95030. var meshNameFromEnd = matches[3];
  95031. if (meshName != meshNameFromEnd) {
  95032. BABYLON.Tools.Error("Error in STL, solid name != endsolid name");
  95033. return false;
  95034. }
  95035. // check meshesNames
  95036. if (meshesNames && meshName) {
  95037. if (meshesNames instanceof Array) {
  95038. if (!meshesNames.indexOf(meshName)) {
  95039. continue;
  95040. }
  95041. }
  95042. else {
  95043. if (meshName !== meshesNames) {
  95044. continue;
  95045. }
  95046. }
  95047. }
  95048. // stl mesh name can be empty as well
  95049. meshName = meshName || "stlmesh";
  95050. var babylonMesh = new BABYLON.Mesh(meshName, scene);
  95051. this.parseASCII(babylonMesh, matches[2]);
  95052. if (meshes) {
  95053. meshes.push(babylonMesh);
  95054. }
  95055. }
  95056. return true;
  95057. };
  95058. STLFileLoader.prototype.load = function (scene, data, rootUrl) {
  95059. var result = this.importMesh(null, scene, data, rootUrl, null, null, null);
  95060. if (result) {
  95061. scene.createDefaultCameraOrLight();
  95062. }
  95063. return result;
  95064. };
  95065. STLFileLoader.prototype.loadAssetContainer = function (scene, data, rootUrl, onError) {
  95066. var container = new BABYLON.AssetContainer(scene);
  95067. this.importMesh(null, scene, data, rootUrl, container.meshes, null, null);
  95068. container.removeAllFromScene();
  95069. return container;
  95070. };
  95071. STLFileLoader.prototype.isBinary = function (data) {
  95072. // check if file size is correct for binary stl
  95073. var faceSize, nFaces, reader;
  95074. reader = new DataView(data);
  95075. faceSize = (32 / 8 * 3) + ((32 / 8 * 3) * 3) + (16 / 8);
  95076. nFaces = reader.getUint32(80, true);
  95077. if (80 + (32 / 8) + (nFaces * faceSize) === reader.byteLength) {
  95078. return true;
  95079. }
  95080. // check characters higher than ASCII to confirm binary
  95081. var fileLength = reader.byteLength;
  95082. for (var index = 0; index < fileLength; index++) {
  95083. if (reader.getUint8(index) > 127) {
  95084. return true;
  95085. }
  95086. }
  95087. return false;
  95088. };
  95089. STLFileLoader.prototype.parseBinary = function (mesh, data) {
  95090. var reader = new DataView(data);
  95091. var faces = reader.getUint32(80, true);
  95092. var dataOffset = 84;
  95093. var faceLength = 12 * 4 + 2;
  95094. var offset = 0;
  95095. var positions = new Float32Array(faces * 3 * 3);
  95096. var normals = new Float32Array(faces * 3 * 3);
  95097. var indices = new Uint32Array(faces * 3);
  95098. var indicesCount = 0;
  95099. for (var face = 0; face < faces; face++) {
  95100. var start = dataOffset + face * faceLength;
  95101. var normalX = reader.getFloat32(start, true);
  95102. var normalY = reader.getFloat32(start + 4, true);
  95103. var normalZ = reader.getFloat32(start + 8, true);
  95104. for (var i = 1; i <= 3; i++) {
  95105. var vertexstart = start + i * 12;
  95106. // ordering is intentional to match ascii import
  95107. positions[offset] = reader.getFloat32(vertexstart, true);
  95108. positions[offset + 2] = reader.getFloat32(vertexstart + 4, true);
  95109. positions[offset + 1] = reader.getFloat32(vertexstart + 8, true);
  95110. normals[offset] = normalX;
  95111. normals[offset + 2] = normalY;
  95112. normals[offset + 1] = normalZ;
  95113. offset += 3;
  95114. }
  95115. indices[indicesCount] = indicesCount++;
  95116. indices[indicesCount] = indicesCount++;
  95117. indices[indicesCount] = indicesCount++;
  95118. }
  95119. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  95120. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  95121. mesh.setIndices(indices);
  95122. mesh.computeWorldMatrix(true);
  95123. };
  95124. STLFileLoader.prototype.parseASCII = function (mesh, solidData) {
  95125. var positions = [];
  95126. var normals = [];
  95127. var indices = [];
  95128. var indicesCount = 0;
  95129. //load facets, ignoring loop as the standard doesn't define it can contain more than vertices
  95130. var matches;
  95131. while (matches = this.facetsPattern.exec(solidData)) {
  95132. var facet = matches[1];
  95133. //one normal per face
  95134. var normalMatches = this.normalPattern.exec(facet);
  95135. this.normalPattern.lastIndex = 0;
  95136. if (!normalMatches) {
  95137. continue;
  95138. }
  95139. var normal = [Number(normalMatches[1]), Number(normalMatches[5]), Number(normalMatches[3])];
  95140. var vertexMatch;
  95141. while (vertexMatch = this.vertexPattern.exec(facet)) {
  95142. positions.push(Number(vertexMatch[1]), Number(vertexMatch[5]), Number(vertexMatch[3]));
  95143. normals.push(normal[0], normal[1], normal[2]);
  95144. }
  95145. indices.push(indicesCount++, indicesCount++, indicesCount++);
  95146. this.vertexPattern.lastIndex = 0;
  95147. }
  95148. this.facetsPattern.lastIndex = 0;
  95149. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  95150. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  95151. mesh.setIndices(indices);
  95152. mesh.computeWorldMatrix(true);
  95153. };
  95154. return STLFileLoader;
  95155. }());
  95156. BABYLON.STLFileLoader = STLFileLoader;
  95157. if (BABYLON.SceneLoader) {
  95158. BABYLON.SceneLoader.RegisterPlugin(new STLFileLoader());
  95159. }
  95160. })(BABYLON || (BABYLON = {}));
  95161. //# sourceMappingURL=babylon.stlFileLoader.js.map
  95162. "use strict";
  95163. var BABYLON;
  95164. (function (BABYLON) {
  95165. /**
  95166. * Class reading and parsing the MTL file bundled with the obj file.
  95167. */
  95168. var MTLFileLoader = /** @class */ (function () {
  95169. function MTLFileLoader() {
  95170. // All material loaded from the mtl will be set here
  95171. this.materials = [];
  95172. }
  95173. /**
  95174. * This function will read the mtl file and create each material described inside
  95175. * This function could be improve by adding :
  95176. * -some component missing (Ni, Tf...)
  95177. * -including the specific options available
  95178. *
  95179. * @param scene
  95180. * @param data
  95181. * @param rootUrl
  95182. */
  95183. MTLFileLoader.prototype.parseMTL = function (scene, data, rootUrl) {
  95184. if (data instanceof ArrayBuffer) {
  95185. return;
  95186. }
  95187. //Split the lines from the file
  95188. var lines = data.split('\n');
  95189. //Space char
  95190. var delimiter_pattern = /\s+/;
  95191. //Array with RGB colors
  95192. var color;
  95193. //New material
  95194. var material = null;
  95195. //Look at each line
  95196. for (var i = 0; i < lines.length; i++) {
  95197. var line = lines[i].trim();
  95198. // Blank line or comment
  95199. if (line.length === 0 || line.charAt(0) === '#') {
  95200. continue;
  95201. }
  95202. //Get the first parameter (keyword)
  95203. var pos = line.indexOf(' ');
  95204. var key = (pos >= 0) ? line.substring(0, pos) : line;
  95205. key = key.toLowerCase();
  95206. //Get the data following the key
  95207. var value = (pos >= 0) ? line.substring(pos + 1).trim() : "";
  95208. //This mtl keyword will create the new material
  95209. if (key === "newmtl") {
  95210. //Check if it is the first material.
  95211. // Materials specifications are described after this keyword.
  95212. if (material) {
  95213. //Add the previous material in the material array.
  95214. this.materials.push(material);
  95215. }
  95216. //Create a new material.
  95217. // value is the name of the material read in the mtl file
  95218. material = new BABYLON.StandardMaterial(value, scene);
  95219. }
  95220. else if (key === "kd" && material) {
  95221. // Diffuse color (color under white light) using RGB values
  95222. //value = "r g b"
  95223. color = value.split(delimiter_pattern, 3).map(parseFloat);
  95224. //color = [r,g,b]
  95225. //Set tghe color into the material
  95226. material.diffuseColor = BABYLON.Color3.FromArray(color);
  95227. }
  95228. else if (key === "ka" && material) {
  95229. // Ambient color (color under shadow) using RGB values
  95230. //value = "r g b"
  95231. color = value.split(delimiter_pattern, 3).map(parseFloat);
  95232. //color = [r,g,b]
  95233. //Set tghe color into the material
  95234. material.ambientColor = BABYLON.Color3.FromArray(color);
  95235. }
  95236. else if (key === "ks" && material) {
  95237. // Specular color (color when light is reflected from shiny surface) using RGB values
  95238. //value = "r g b"
  95239. color = value.split(delimiter_pattern, 3).map(parseFloat);
  95240. //color = [r,g,b]
  95241. //Set the color into the material
  95242. material.specularColor = BABYLON.Color3.FromArray(color);
  95243. }
  95244. else if (key === "ke" && material) {
  95245. // Emissive color using RGB values
  95246. color = value.split(delimiter_pattern, 3).map(parseFloat);
  95247. material.emissiveColor = BABYLON.Color3.FromArray(color);
  95248. }
  95249. else if (key === "ns" && material) {
  95250. //value = "Integer"
  95251. material.specularPower = parseFloat(value);
  95252. }
  95253. else if (key === "d" && material) {
  95254. //d is dissolve for current material. It mean alpha for BABYLON
  95255. material.alpha = parseFloat(value);
  95256. //Texture
  95257. //This part can be improved by adding the possible options of texture
  95258. }
  95259. else if (key === "map_ka" && material) {
  95260. // ambient texture map with a loaded image
  95261. //We must first get the folder of the image
  95262. material.ambientTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  95263. }
  95264. else if (key === "map_kd" && material) {
  95265. // Diffuse texture map with a loaded image
  95266. material.diffuseTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  95267. }
  95268. else if (key === "map_ks" && material) {
  95269. // Specular texture map with a loaded image
  95270. //We must first get the folder of the image
  95271. material.specularTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  95272. }
  95273. else if (key === "map_ns") {
  95274. //Specular
  95275. //Specular highlight component
  95276. //We must first get the folder of the image
  95277. //
  95278. //Not supported by BABYLON
  95279. //
  95280. // continue;
  95281. }
  95282. else if (key === "map_bump" && material) {
  95283. //The bump texture
  95284. material.bumpTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  95285. }
  95286. else if (key === "map_d" && material) {
  95287. // The dissolve of the material
  95288. material.opacityTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  95289. //Options for illumination
  95290. }
  95291. else if (key === "illum") {
  95292. //Illumination
  95293. if (value === "0") {
  95294. //That mean Kd == Kd
  95295. }
  95296. else if (value === "1") {
  95297. //Color on and Ambient on
  95298. }
  95299. else if (value === "2") {
  95300. //Highlight on
  95301. }
  95302. else if (value === "3") {
  95303. //Reflection on and Ray trace on
  95304. }
  95305. else if (value === "4") {
  95306. //Transparency: Glass on, Reflection: Ray trace on
  95307. }
  95308. else if (value === "5") {
  95309. //Reflection: Fresnel on and Ray trace on
  95310. }
  95311. else if (value === "6") {
  95312. //Transparency: Refraction on, Reflection: Fresnel off and Ray trace on
  95313. }
  95314. else if (value === "7") {
  95315. //Transparency: Refraction on, Reflection: Fresnel on and Ray trace on
  95316. }
  95317. else if (value === "8") {
  95318. //Reflection on and Ray trace off
  95319. }
  95320. else if (value === "9") {
  95321. //Transparency: Glass on, Reflection: Ray trace off
  95322. }
  95323. else if (value === "10") {
  95324. //Casts shadows onto invisible surfaces
  95325. }
  95326. }
  95327. else {
  95328. // console.log("Unhandled expression at line : " + i +'\n' + "with value : " + line);
  95329. }
  95330. }
  95331. //At the end of the file, add the last material
  95332. if (material) {
  95333. this.materials.push(material);
  95334. }
  95335. };
  95336. /**
  95337. * Gets the texture for the material.
  95338. *
  95339. * If the material is imported from input file,
  95340. * We sanitize the url to ensure it takes the textre from aside the material.
  95341. *
  95342. * @param rootUrl The root url to load from
  95343. * @param value The value stored in the mtl
  95344. * @return The Texture
  95345. */
  95346. MTLFileLoader._getTexture = function (rootUrl, value, scene) {
  95347. if (!value) {
  95348. return null;
  95349. }
  95350. var url = rootUrl;
  95351. // Load from input file.
  95352. if (rootUrl === "file:") {
  95353. var lastDelimiter = value.lastIndexOf("\\");
  95354. if (lastDelimiter === -1) {
  95355. lastDelimiter = value.lastIndexOf("/");
  95356. }
  95357. if (lastDelimiter > -1) {
  95358. url += value.substr(lastDelimiter + 1);
  95359. }
  95360. else {
  95361. url += value;
  95362. }
  95363. }
  95364. else {
  95365. url += value;
  95366. }
  95367. return new BABYLON.Texture(url, scene);
  95368. };
  95369. return MTLFileLoader;
  95370. }());
  95371. BABYLON.MTLFileLoader = MTLFileLoader;
  95372. var OBJFileLoader = /** @class */ (function () {
  95373. function OBJFileLoader() {
  95374. this.name = "obj";
  95375. this.extensions = ".obj";
  95376. this.obj = /^o/;
  95377. this.group = /^g/;
  95378. this.mtllib = /^mtllib /;
  95379. this.usemtl = /^usemtl /;
  95380. this.smooth = /^s /;
  95381. this.vertexPattern = /v( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  95382. // vn float float float
  95383. this.normalPattern = /vn( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  95384. // vt float float
  95385. this.uvPattern = /vt( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  95386. // f vertex vertex vertex ...
  95387. this.facePattern1 = /f\s+(([\d]{1,}[\s]?){3,})+/;
  95388. // f vertex/uvs vertex/uvs vertex/uvs ...
  95389. this.facePattern2 = /f\s+((([\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;
  95390. // f vertex/uvs/normal vertex/uvs/normal vertex/uvs/normal ...
  95391. this.facePattern3 = /f\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;
  95392. // f vertex//normal vertex//normal vertex//normal ...
  95393. this.facePattern4 = /f\s+((([\d]{1,}\/\/[\d]{1,}[\s]?){3,})+)/;
  95394. }
  95395. /**
  95396. * Calls synchronously the MTL file attached to this obj.
  95397. * Load function or importMesh function don't enable to load 2 files in the same time asynchronously.
  95398. * Without this function materials are not displayed in the first frame (but displayed after).
  95399. * In consequence it is impossible to get material information in your HTML file
  95400. *
  95401. * @param url The URL of the MTL file
  95402. * @param rootUrl
  95403. * @param onSuccess Callback function to be called when the MTL file is loaded
  95404. * @private
  95405. */
  95406. OBJFileLoader.prototype._loadMTL = function (url, rootUrl, onSuccess) {
  95407. //The complete path to the mtl file
  95408. var pathOfFile = BABYLON.Tools.BaseUrl + rootUrl + url;
  95409. // Loads through the babylon tools to allow fileInput search.
  95410. BABYLON.Tools.LoadFile(pathOfFile, onSuccess, undefined, undefined, false, function () { console.warn("Error - Unable to load " + pathOfFile); });
  95411. };
  95412. OBJFileLoader.prototype.importMesh = function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  95413. //get the meshes from OBJ file
  95414. var loadedMeshes = this._parseSolid(meshesNames, scene, data, rootUrl);
  95415. //Push meshes from OBJ file into the variable mesh of this function
  95416. if (meshes) {
  95417. loadedMeshes.forEach(function (mesh) {
  95418. meshes.push(mesh);
  95419. });
  95420. }
  95421. return true;
  95422. };
  95423. OBJFileLoader.prototype.load = function (scene, data, rootUrl) {
  95424. //Get the 3D model
  95425. return this.importMesh(null, scene, data, rootUrl, null, null, null);
  95426. };
  95427. OBJFileLoader.prototype.loadAssetContainer = function (scene, data, rootUrl, onError) {
  95428. var container = new BABYLON.AssetContainer(scene);
  95429. this.importMesh(null, scene, data, rootUrl, container.meshes, null, null);
  95430. container.removeAllFromScene();
  95431. return container;
  95432. };
  95433. /**
  95434. * Read the OBJ file and create an Array of meshes.
  95435. * Each mesh contains all information given by the OBJ and the MTL file.
  95436. * i.e. vertices positions and indices, optional normals values, optional UV values, optional material
  95437. *
  95438. * @param meshesNames
  95439. * @param scene BABYLON.Scene The scene where are displayed the data
  95440. * @param data String The content of the obj file
  95441. * @param rootUrl String The path to the folder
  95442. * @returns Array<AbstractMesh>
  95443. * @private
  95444. */
  95445. OBJFileLoader.prototype._parseSolid = function (meshesNames, scene, data, rootUrl) {
  95446. var positions = []; //values for the positions of vertices
  95447. var normals = []; //Values for the normals
  95448. var uvs = []; //Values for the textures
  95449. var meshesFromObj = []; //[mesh] Contains all the obj meshes
  95450. var handledMesh; //The current mesh of meshes array
  95451. var indicesForBabylon = []; //The list of indices for VertexData
  95452. var wrappedPositionForBabylon = []; //The list of position in vectors
  95453. var wrappedUvsForBabylon = []; //Array with all value of uvs to match with the indices
  95454. var wrappedNormalsForBabylon = []; //Array with all value of normals to match with the indices
  95455. var tuplePosNorm = []; //Create a tuple with indice of Position, Normal, UV [pos, norm, uvs]
  95456. var curPositionInIndices = 0;
  95457. var hasMeshes = false; //Meshes are defined in the file
  95458. var unwrappedPositionsForBabylon = []; //Value of positionForBabylon w/o Vector3() [x,y,z]
  95459. var unwrappedNormalsForBabylon = []; //Value of normalsForBabylon w/o Vector3() [x,y,z]
  95460. var unwrappedUVForBabylon = []; //Value of uvsForBabylon w/o Vector3() [x,y,z]
  95461. var triangles = []; //Indices from new triangles coming from polygons
  95462. var materialNameFromObj = ""; //The name of the current material
  95463. var fileToLoad = ""; //The name of the mtlFile to load
  95464. var materialsFromMTLFile = new MTLFileLoader();
  95465. var objMeshName = ""; //The name of the current obj mesh
  95466. var increment = 1; //Id for meshes created by the multimaterial
  95467. var isFirstMaterial = true;
  95468. /**
  95469. * Search for obj in the given array.
  95470. * This function is called to check if a couple of data already exists in an array.
  95471. *
  95472. * If found, returns the index of the founded tuple index. Returns -1 if not found
  95473. * @param arr Array<{ normals: Array<number>, idx: Array<number> }>
  95474. * @param obj Array<number>
  95475. * @returns {boolean}
  95476. */
  95477. var isInArray = function (arr, obj) {
  95478. if (!arr[obj[0]])
  95479. arr[obj[0]] = { normals: [], idx: [] };
  95480. var idx = arr[obj[0]].normals.indexOf(obj[1]);
  95481. return idx === -1 ? -1 : arr[obj[0]].idx[idx];
  95482. };
  95483. var isInArrayUV = function (arr, obj) {
  95484. if (!arr[obj[0]])
  95485. arr[obj[0]] = { normals: [], idx: [], uv: [] };
  95486. var idx = arr[obj[0]].normals.indexOf(obj[1]);
  95487. if (idx != 1 && (obj[2] == arr[obj[0]].uv[idx])) {
  95488. return arr[obj[0]].idx[idx];
  95489. }
  95490. return -1;
  95491. };
  95492. /**
  95493. * This function set the data for each triangle.
  95494. * Data are position, normals and uvs
  95495. * If a tuple of (position, normal) is not set, add the data into the corresponding array
  95496. * If the tuple already exist, add only their indice
  95497. *
  95498. * @param indicePositionFromObj Integer The index in positions array
  95499. * @param indiceUvsFromObj Integer The index in uvs array
  95500. * @param indiceNormalFromObj Integer The index in normals array
  95501. * @param positionVectorFromOBJ Vector3 The value of position at index objIndice
  95502. * @param textureVectorFromOBJ Vector3 The value of uvs
  95503. * @param normalsVectorFromOBJ Vector3 The value of normals at index objNormale
  95504. */
  95505. var setData = function (indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positionVectorFromOBJ, textureVectorFromOBJ, normalsVectorFromOBJ) {
  95506. //Check if this tuple already exists in the list of tuples
  95507. var _index;
  95508. if (OBJFileLoader.OPTIMIZE_WITH_UV) {
  95509. _index = isInArrayUV(tuplePosNorm, [
  95510. indicePositionFromObj,
  95511. indiceNormalFromObj,
  95512. indiceUvsFromObj
  95513. ]);
  95514. }
  95515. else {
  95516. _index = isInArray(tuplePosNorm, [
  95517. indicePositionFromObj,
  95518. indiceNormalFromObj
  95519. ]);
  95520. }
  95521. //If it not exists
  95522. if (_index == -1) {
  95523. //Add an new indice.
  95524. //The array of indices is only an array with his length equal to the number of triangles - 1.
  95525. //We add vertices data in this order
  95526. indicesForBabylon.push(wrappedPositionForBabylon.length);
  95527. //Push the position of vertice for Babylon
  95528. //Each element is a BABYLON.Vector3(x,y,z)
  95529. wrappedPositionForBabylon.push(positionVectorFromOBJ);
  95530. //Push the uvs for Babylon
  95531. //Each element is a BABYLON.Vector3(u,v)
  95532. wrappedUvsForBabylon.push(textureVectorFromOBJ);
  95533. //Push the normals for Babylon
  95534. //Each element is a BABYLON.Vector3(x,y,z)
  95535. wrappedNormalsForBabylon.push(normalsVectorFromOBJ);
  95536. //Add the tuple in the comparison list
  95537. tuplePosNorm[indicePositionFromObj].normals.push(indiceNormalFromObj);
  95538. tuplePosNorm[indicePositionFromObj].idx.push(curPositionInIndices++);
  95539. if (OBJFileLoader.OPTIMIZE_WITH_UV)
  95540. tuplePosNorm[indicePositionFromObj].uv.push(indiceUvsFromObj);
  95541. }
  95542. else {
  95543. //The tuple already exists
  95544. //Add the index of the already existing tuple
  95545. //At this index we can get the value of position, normal and uvs of vertex
  95546. indicesForBabylon.push(_index);
  95547. }
  95548. };
  95549. /**
  95550. * Transform BABYLON.Vector() object onto 3 digits in an array
  95551. */
  95552. var unwrapData = function () {
  95553. //Every array has the same length
  95554. for (var l = 0; l < wrappedPositionForBabylon.length; l++) {
  95555. //Push the x, y, z values of each element in the unwrapped array
  95556. unwrappedPositionsForBabylon.push(wrappedPositionForBabylon[l].x, wrappedPositionForBabylon[l].y, wrappedPositionForBabylon[l].z);
  95557. unwrappedNormalsForBabylon.push(wrappedNormalsForBabylon[l].x, wrappedNormalsForBabylon[l].y, wrappedNormalsForBabylon[l].z);
  95558. unwrappedUVForBabylon.push(wrappedUvsForBabylon[l].x, wrappedUvsForBabylon[l].y); //z is an optional value not supported by BABYLON
  95559. }
  95560. // Reset arrays for the next new meshes
  95561. wrappedPositionForBabylon = [];
  95562. wrappedNormalsForBabylon = [];
  95563. wrappedUvsForBabylon = [];
  95564. tuplePosNorm = [];
  95565. curPositionInIndices = 0;
  95566. };
  95567. /**
  95568. * Create triangles from polygons by recursion
  95569. * The best to understand how it works is to draw it in the same time you get the recursion.
  95570. * It is important to notice that a triangle is a polygon
  95571. * We get 4 patterns of face defined in OBJ File :
  95572. * facePattern1 = ["1","2","3","4","5","6"]
  95573. * facePattern2 = ["1/1","2/2","3/3","4/4","5/5","6/6"]
  95574. * facePattern3 = ["1/1/1","2/2/2","3/3/3","4/4/4","5/5/5","6/6/6"]
  95575. * facePattern4 = ["1//1","2//2","3//3","4//4","5//5","6//6"]
  95576. * Each pattern is divided by the same method
  95577. * @param face Array[String] The indices of elements
  95578. * @param v Integer The variable to increment
  95579. */
  95580. var getTriangles = function (face, v) {
  95581. //Work for each element of the array
  95582. if (v + 1 < face.length) {
  95583. //Add on the triangle variable the indexes to obtain triangles
  95584. triangles.push(face[0], face[v], face[v + 1]);
  95585. //Incrementation for recursion
  95586. v += 1;
  95587. //Recursion
  95588. getTriangles(face, v);
  95589. }
  95590. //Result obtained after 2 iterations:
  95591. //Pattern1 => triangle = ["1","2","3","1","3","4"];
  95592. //Pattern2 => triangle = ["1/1","2/2","3/3","1/1","3/3","4/4"];
  95593. //Pattern3 => triangle = ["1/1/1","2/2/2","3/3/3","1/1/1","3/3/3","4/4/4"];
  95594. //Pattern4 => triangle = ["1//1","2//2","3//3","1//1","3//3","4//4"];
  95595. };
  95596. /**
  95597. * Create triangles and push the data for each polygon for the pattern 1
  95598. * In this pattern we get vertice positions
  95599. * @param face
  95600. * @param v
  95601. */
  95602. var setDataForCurrentFaceWithPattern1 = function (face, v) {
  95603. //Get the indices of triangles for each polygon
  95604. getTriangles(face, v);
  95605. //For each element in the triangles array.
  95606. //This var could contains 1 to an infinity of triangles
  95607. for (var k = 0; k < triangles.length; k++) {
  95608. // Set position indice
  95609. var indicePositionFromObj = parseInt(triangles[k]) - 1;
  95610. setData(indicePositionFromObj, 0, 0, //In the pattern 1, normals and uvs are not defined
  95611. positions[indicePositionFromObj], //Get the vectors data
  95612. BABYLON.Vector2.Zero(), BABYLON.Vector3.Up() //Create default vectors
  95613. );
  95614. }
  95615. //Reset variable for the next line
  95616. triangles = [];
  95617. };
  95618. /**
  95619. * Create triangles and push the data for each polygon for the pattern 2
  95620. * In this pattern we get vertice positions and uvsu
  95621. * @param face
  95622. * @param v
  95623. */
  95624. var setDataForCurrentFaceWithPattern2 = function (face, v) {
  95625. //Get the indices of triangles for each polygon
  95626. getTriangles(face, v);
  95627. for (var k = 0; k < triangles.length; k++) {
  95628. //triangle[k] = "1/1"
  95629. //Split the data for getting position and uv
  95630. var point = triangles[k].split("/"); // ["1", "1"]
  95631. //Set position indice
  95632. var indicePositionFromObj = parseInt(point[0]) - 1;
  95633. //Set uv indice
  95634. var indiceUvsFromObj = parseInt(point[1]) - 1;
  95635. setData(indicePositionFromObj, indiceUvsFromObj, 0, //Default value for normals
  95636. positions[indicePositionFromObj], //Get the values for each element
  95637. uvs[indiceUvsFromObj], BABYLON.Vector3.Up() //Default value for normals
  95638. );
  95639. }
  95640. //Reset variable for the next line
  95641. triangles = [];
  95642. };
  95643. /**
  95644. * Create triangles and push the data for each polygon for the pattern 3
  95645. * In this pattern we get vertice positions, uvs and normals
  95646. * @param face
  95647. * @param v
  95648. */
  95649. var setDataForCurrentFaceWithPattern3 = function (face, v) {
  95650. //Get the indices of triangles for each polygon
  95651. getTriangles(face, v);
  95652. for (var k = 0; k < triangles.length; k++) {
  95653. //triangle[k] = "1/1/1"
  95654. //Split the data for getting position, uv, and normals
  95655. var point = triangles[k].split("/"); // ["1", "1", "1"]
  95656. // Set position indice
  95657. var indicePositionFromObj = parseInt(point[0]) - 1;
  95658. // Set uv indice
  95659. var indiceUvsFromObj = parseInt(point[1]) - 1;
  95660. // Set normal indice
  95661. var indiceNormalFromObj = parseInt(point[2]) - 1;
  95662. setData(indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positions[indicePositionFromObj], uvs[indiceUvsFromObj], normals[indiceNormalFromObj] //Set the vector for each component
  95663. );
  95664. }
  95665. //Reset variable for the next line
  95666. triangles = [];
  95667. };
  95668. /**
  95669. * Create triangles and push the data for each polygon for the pattern 4
  95670. * In this pattern we get vertice positions and normals
  95671. * @param face
  95672. * @param v
  95673. */
  95674. var setDataForCurrentFaceWithPattern4 = function (face, v) {
  95675. getTriangles(face, v);
  95676. for (var k = 0; k < triangles.length; k++) {
  95677. //triangle[k] = "1//1"
  95678. //Split the data for getting position and normals
  95679. var point = triangles[k].split("//"); // ["1", "1"]
  95680. // We check indices, and normals
  95681. var indicePositionFromObj = parseInt(point[0]) - 1;
  95682. var indiceNormalFromObj = parseInt(point[1]) - 1;
  95683. setData(indicePositionFromObj, 1, //Default value for uv
  95684. indiceNormalFromObj, positions[indicePositionFromObj], //Get each vector of data
  95685. BABYLON.Vector2.Zero(), normals[indiceNormalFromObj]);
  95686. }
  95687. //Reset variable for the next line
  95688. triangles = [];
  95689. };
  95690. var addPreviousObjMesh = function () {
  95691. //Check if it is not the first mesh. Otherwise we don't have data.
  95692. if (meshesFromObj.length > 0) {
  95693. //Get the previous mesh for applying the data about the faces
  95694. //=> in obj file, faces definition append after the name of the mesh
  95695. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  95696. //Set the data into Array for the mesh
  95697. unwrapData();
  95698. // Reverse tab. Otherwise face are displayed in the wrong sens
  95699. indicesForBabylon.reverse();
  95700. //Set the information for the mesh
  95701. //Slice the array to avoid rewriting because of the fact this is the same var which be rewrited
  95702. handledMesh.indices = indicesForBabylon.slice();
  95703. handledMesh.positions = unwrappedPositionsForBabylon.slice();
  95704. handledMesh.normals = unwrappedNormalsForBabylon.slice();
  95705. handledMesh.uvs = unwrappedUVForBabylon.slice();
  95706. //Reset the array for the next mesh
  95707. indicesForBabylon = [];
  95708. unwrappedPositionsForBabylon = [];
  95709. unwrappedNormalsForBabylon = [];
  95710. unwrappedUVForBabylon = [];
  95711. }
  95712. };
  95713. //Main function
  95714. //Split the file into lines
  95715. var lines = data.split('\n');
  95716. //Look at each line
  95717. for (var i = 0; i < lines.length; i++) {
  95718. var line = lines[i].trim();
  95719. var result;
  95720. //Comment or newLine
  95721. if (line.length === 0 || line.charAt(0) === '#') {
  95722. continue;
  95723. //Get information about one position possible for the vertices
  95724. }
  95725. else if ((result = this.vertexPattern.exec(line)) !== null) {
  95726. //Create a Vector3 with the position x, y, z
  95727. //Value of result:
  95728. // ["v 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  95729. //Add the Vector in the list of positions
  95730. positions.push(new BABYLON.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));
  95731. }
  95732. else if ((result = this.normalPattern.exec(line)) !== null) {
  95733. //Create a Vector3 with the normals x, y, z
  95734. //Value of result
  95735. // ["vn 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  95736. //Add the Vector in the list of normals
  95737. normals.push(new BABYLON.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));
  95738. }
  95739. else if ((result = this.uvPattern.exec(line)) !== null) {
  95740. //Create a Vector2 with the normals u, v
  95741. //Value of result
  95742. // ["vt 0.1 0.2 0.3", "0.1", "0.2"]
  95743. //Add the Vector in the list of uvs
  95744. uvs.push(new BABYLON.Vector2(parseFloat(result[1]), parseFloat(result[2])));
  95745. //Identify patterns of faces
  95746. //Face could be defined in different type of pattern
  95747. }
  95748. else if ((result = this.facePattern3.exec(line)) !== null) {
  95749. //Value of result:
  95750. //["f 1/1/1 2/2/2 3/3/3", "1/1/1 2/2/2 3/3/3"...]
  95751. //Set the data for this face
  95752. setDataForCurrentFaceWithPattern3(result[1].trim().split(" "), // ["1/1/1", "2/2/2", "3/3/3"]
  95753. 1);
  95754. }
  95755. else if ((result = this.facePattern4.exec(line)) !== null) {
  95756. //Value of result:
  95757. //["f 1//1 2//2 3//3", "1//1 2//2 3//3"...]
  95758. //Set the data for this face
  95759. setDataForCurrentFaceWithPattern4(result[1].trim().split(" "), // ["1//1", "2//2", "3//3"]
  95760. 1);
  95761. }
  95762. else if ((result = this.facePattern2.exec(line)) !== null) {
  95763. //Value of result:
  95764. //["f 1/1 2/2 3/3", "1/1 2/2 3/3"...]
  95765. //Set the data for this face
  95766. setDataForCurrentFaceWithPattern2(result[1].trim().split(" "), // ["1/1", "2/2", "3/3"]
  95767. 1);
  95768. }
  95769. else if ((result = this.facePattern1.exec(line)) !== null) {
  95770. //Value of result
  95771. //["f 1 2 3", "1 2 3"...]
  95772. //Set the data for this face
  95773. setDataForCurrentFaceWithPattern1(result[1].trim().split(" "), // ["1", "2", "3"]
  95774. 1);
  95775. //Define a mesh or an object
  95776. //Each time this keyword is analysed, create a new Object with all data for creating a babylonMesh
  95777. }
  95778. else if (this.group.test(line) || this.obj.test(line)) {
  95779. //Create a new mesh corresponding to the name of the group.
  95780. //Definition of the mesh
  95781. var objMesh =
  95782. //Set the name of the current obj mesh
  95783. {
  95784. name: line.substring(2).trim(),
  95785. indices: undefined,
  95786. positions: undefined,
  95787. normals: undefined,
  95788. uvs: undefined,
  95789. materialName: ""
  95790. };
  95791. addPreviousObjMesh();
  95792. //Push the last mesh created with only the name
  95793. meshesFromObj.push(objMesh);
  95794. //Set this variable to indicate that now meshesFromObj has objects defined inside
  95795. hasMeshes = true;
  95796. isFirstMaterial = true;
  95797. increment = 1;
  95798. //Keyword for applying a material
  95799. }
  95800. else if (this.usemtl.test(line)) {
  95801. //Get the name of the material
  95802. materialNameFromObj = line.substring(7).trim();
  95803. //If this new material is in the same mesh
  95804. if (!isFirstMaterial) {
  95805. //Set the data for the previous mesh
  95806. addPreviousObjMesh();
  95807. //Create a new mesh
  95808. var objMesh =
  95809. //Set the name of the current obj mesh
  95810. {
  95811. name: objMeshName + "_mm" + increment.toString(),
  95812. indices: undefined,
  95813. positions: undefined,
  95814. normals: undefined,
  95815. uvs: undefined,
  95816. materialName: materialNameFromObj
  95817. };
  95818. increment++;
  95819. //If meshes are already defined
  95820. meshesFromObj.push(objMesh);
  95821. }
  95822. //Set the material name if the previous line define a mesh
  95823. if (hasMeshes && isFirstMaterial) {
  95824. //Set the material name to the previous mesh (1 material per mesh)
  95825. meshesFromObj[meshesFromObj.length - 1].materialName = materialNameFromObj;
  95826. isFirstMaterial = false;
  95827. }
  95828. //Keyword for loading the mtl file
  95829. }
  95830. else if (this.mtllib.test(line)) {
  95831. //Get the name of mtl file
  95832. fileToLoad = line.substring(7).trim();
  95833. //Apply smoothing
  95834. }
  95835. else if (this.smooth.test(line)) {
  95836. // smooth shading => apply smoothing
  95837. //Toda y I don't know it work with babylon and with obj.
  95838. //With the obj file an integer is set
  95839. }
  95840. else {
  95841. //If there is another possibility
  95842. console.log("Unhandled expression at line : " + line);
  95843. }
  95844. }
  95845. //At the end of the file, add the last mesh into the meshesFromObj array
  95846. if (hasMeshes) {
  95847. //Set the data for the last mesh
  95848. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  95849. //Reverse indices for displaying faces in the good sens
  95850. indicesForBabylon.reverse();
  95851. //Get the good array
  95852. unwrapData();
  95853. //Set array
  95854. handledMesh.indices = indicesForBabylon;
  95855. handledMesh.positions = unwrappedPositionsForBabylon;
  95856. handledMesh.normals = unwrappedNormalsForBabylon;
  95857. handledMesh.uvs = unwrappedUVForBabylon;
  95858. }
  95859. //If any o or g keyword found, create a mesj with a random id
  95860. if (!hasMeshes) {
  95861. // reverse tab of indices
  95862. indicesForBabylon.reverse();
  95863. //Get positions normals uvs
  95864. unwrapData();
  95865. //Set data for one mesh
  95866. meshesFromObj.push({
  95867. name: BABYLON.Geometry.RandomId(),
  95868. indices: indicesForBabylon,
  95869. positions: unwrappedPositionsForBabylon,
  95870. normals: unwrappedNormalsForBabylon,
  95871. uvs: unwrappedUVForBabylon,
  95872. materialName: materialNameFromObj
  95873. });
  95874. }
  95875. //Create a BABYLON.Mesh list
  95876. var babylonMeshesArray = []; //The mesh for babylon
  95877. var materialToUse = new Array();
  95878. //Set data for each mesh
  95879. for (var j = 0; j < meshesFromObj.length; j++) {
  95880. //check meshesNames (stlFileLoader)
  95881. if (meshesNames && meshesFromObj[j].name) {
  95882. if (meshesNames instanceof Array) {
  95883. if (meshesNames.indexOf(meshesFromObj[j].name) == -1) {
  95884. continue;
  95885. }
  95886. }
  95887. else {
  95888. if (meshesFromObj[j].name !== meshesNames) {
  95889. continue;
  95890. }
  95891. }
  95892. }
  95893. //Get the current mesh
  95894. //Set the data with VertexBuffer for each mesh
  95895. handledMesh = meshesFromObj[j];
  95896. //Create a BABYLON.Mesh with the name of the obj mesh
  95897. var babylonMesh = new BABYLON.Mesh(meshesFromObj[j].name, scene);
  95898. //Push the name of the material to an array
  95899. //This is indispensable for the importMesh function
  95900. materialToUse.push(meshesFromObj[j].materialName);
  95901. var vertexData = new BABYLON.VertexData(); //The container for the values
  95902. //Set the data for the babylonMesh
  95903. vertexData.positions = handledMesh.positions;
  95904. vertexData.normals = handledMesh.normals;
  95905. vertexData.uvs = handledMesh.uvs;
  95906. vertexData.indices = handledMesh.indices;
  95907. //Set the data from the VertexBuffer to the current BABYLON.Mesh
  95908. vertexData.applyToMesh(babylonMesh);
  95909. //Push the mesh into an array
  95910. babylonMeshesArray.push(babylonMesh);
  95911. }
  95912. //load the materials
  95913. //Check if we have a file to load
  95914. if (fileToLoad !== "") {
  95915. //Load the file synchronously
  95916. this._loadMTL(fileToLoad, rootUrl, function (dataLoaded) {
  95917. //Create materials thanks MTLLoader function
  95918. materialsFromMTLFile.parseMTL(scene, dataLoaded, rootUrl);
  95919. //Look at each material loaded in the mtl file
  95920. for (var n = 0; n < materialsFromMTLFile.materials.length; n++) {
  95921. //Three variables to get all meshes with the same material
  95922. var startIndex = 0;
  95923. var _indices = [];
  95924. var _index;
  95925. //The material from MTL file is used in the meshes loaded
  95926. //Push the indice in an array
  95927. //Check if the material is not used for another mesh
  95928. while ((_index = materialToUse.indexOf(materialsFromMTLFile.materials[n].name, startIndex)) > -1) {
  95929. _indices.push(_index);
  95930. startIndex = _index + 1;
  95931. }
  95932. //If the material is not used dispose it
  95933. if (_index == -1 && _indices.length == 0) {
  95934. //If the material is not needed, remove it
  95935. materialsFromMTLFile.materials[n].dispose();
  95936. }
  95937. else {
  95938. for (var o = 0; o < _indices.length; o++) {
  95939. //Apply the material to the BABYLON.Mesh for each mesh with the material
  95940. babylonMeshesArray[_indices[o]].material = materialsFromMTLFile.materials[n];
  95941. }
  95942. }
  95943. }
  95944. });
  95945. }
  95946. //Return an array with all BABYLON.Mesh
  95947. return babylonMeshesArray;
  95948. };
  95949. OBJFileLoader.OPTIMIZE_WITH_UV = false;
  95950. return OBJFileLoader;
  95951. }());
  95952. BABYLON.OBJFileLoader = OBJFileLoader;
  95953. if (BABYLON.SceneLoader) {
  95954. //Add this loader into the register plugin
  95955. BABYLON.SceneLoader.RegisterPlugin(new OBJFileLoader());
  95956. }
  95957. })(BABYLON || (BABYLON = {}));
  95958. //# sourceMappingURL=babylon.objFileLoader.js.map
  95959. "use strict";
  95960. var BABYLON;
  95961. (function (BABYLON) {
  95962. var GLTFLoaderCoordinateSystemMode;
  95963. (function (GLTFLoaderCoordinateSystemMode) {
  95964. /**
  95965. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  95966. */
  95967. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  95968. /**
  95969. * Sets the useRightHandedSystem flag on the scene.
  95970. */
  95971. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  95972. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  95973. var GLTFLoaderAnimationStartMode;
  95974. (function (GLTFLoaderAnimationStartMode) {
  95975. /**
  95976. * No animation will start.
  95977. */
  95978. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  95979. /**
  95980. * The first animation will start.
  95981. */
  95982. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  95983. /**
  95984. * All animations will start.
  95985. */
  95986. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  95987. })(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {}));
  95988. var GLTFLoaderState;
  95989. (function (GLTFLoaderState) {
  95990. GLTFLoaderState[GLTFLoaderState["Loading"] = 0] = "Loading";
  95991. GLTFLoaderState[GLTFLoaderState["Ready"] = 1] = "Ready";
  95992. GLTFLoaderState[GLTFLoaderState["Complete"] = 2] = "Complete";
  95993. })(GLTFLoaderState = BABYLON.GLTFLoaderState || (BABYLON.GLTFLoaderState = {}));
  95994. var GLTFFileLoader = /** @class */ (function () {
  95995. function GLTFFileLoader() {
  95996. // #region Common options
  95997. /**
  95998. * Raised when the asset has been parsed.
  95999. * The data.json property stores the glTF JSON.
  96000. * The data.bin property stores the BIN chunk from a glTF binary or null if the input is not a glTF binary.
  96001. */
  96002. this.onParsedObservable = new BABYLON.Observable();
  96003. // #endregion
  96004. // #region V2 options
  96005. /**
  96006. * The coordinate system mode (AUTO, FORCE_RIGHT_HANDED).
  96007. */
  96008. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  96009. /**
  96010. * The animation start mode (NONE, FIRST, ALL).
  96011. */
  96012. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  96013. /**
  96014. * Set to true to compile materials before raising the success callback.
  96015. */
  96016. this.compileMaterials = false;
  96017. /**
  96018. * Set to true to also compile materials with clip planes.
  96019. */
  96020. this.useClipPlane = false;
  96021. /**
  96022. * Set to true to compile shadow generators before raising the success callback.
  96023. */
  96024. this.compileShadowGenerators = false;
  96025. /**
  96026. * Raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  96027. */
  96028. this.onMeshLoadedObservable = new BABYLON.Observable();
  96029. /**
  96030. * Raised when the loader creates a texture after parsing the glTF properties of the texture.
  96031. */
  96032. this.onTextureLoadedObservable = new BABYLON.Observable();
  96033. /**
  96034. * Raised when the loader creates a material after parsing the glTF properties of the material.
  96035. */
  96036. this.onMaterialLoadedObservable = new BABYLON.Observable();
  96037. /**
  96038. * Raised when the loader creates an animation group after parsing the glTF properties of the animation.
  96039. */
  96040. this.onAnimationGroupLoadedObservable = new BABYLON.Observable();
  96041. /**
  96042. * Raised when the asset is completely loaded, immediately before the loader is disposed.
  96043. * For assets with LODs, raised when all of the LODs are complete.
  96044. * For assets without LODs, raised when the model is complete, immediately after onSuccess.
  96045. */
  96046. this.onCompleteObservable = new BABYLON.Observable();
  96047. /**
  96048. * Raised when the loader is disposed.
  96049. */
  96050. this.onDisposeObservable = new BABYLON.Observable();
  96051. /**
  96052. * Raised after a loader extension is created.
  96053. * Set additional options for a loader extension in this event.
  96054. */
  96055. this.onExtensionLoadedObservable = new BABYLON.Observable();
  96056. // #endregion
  96057. this._loader = null;
  96058. this.name = "gltf";
  96059. this.extensions = {
  96060. ".gltf": { isBinary: false },
  96061. ".glb": { isBinary: true }
  96062. };
  96063. }
  96064. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  96065. set: function (callback) {
  96066. if (this._onParsedObserver) {
  96067. this.onParsedObservable.remove(this._onParsedObserver);
  96068. }
  96069. this._onParsedObserver = this.onParsedObservable.add(callback);
  96070. },
  96071. enumerable: true,
  96072. configurable: true
  96073. });
  96074. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  96075. set: function (callback) {
  96076. if (this._onMeshLoadedObserver) {
  96077. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  96078. }
  96079. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  96080. },
  96081. enumerable: true,
  96082. configurable: true
  96083. });
  96084. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  96085. set: function (callback) {
  96086. if (this._onTextureLoadedObserver) {
  96087. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  96088. }
  96089. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  96090. },
  96091. enumerable: true,
  96092. configurable: true
  96093. });
  96094. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  96095. set: function (callback) {
  96096. if (this._onMaterialLoadedObserver) {
  96097. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  96098. }
  96099. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  96100. },
  96101. enumerable: true,
  96102. configurable: true
  96103. });
  96104. Object.defineProperty(GLTFFileLoader.prototype, "onAnimationGroupLoaded", {
  96105. set: function (callback) {
  96106. if (this._onAnimationGroupLoadedObserver) {
  96107. this.onAnimationGroupLoadedObservable.remove(this._onAnimationGroupLoadedObserver);
  96108. }
  96109. this._onAnimationGroupLoadedObserver = this.onAnimationGroupLoadedObservable.add(callback);
  96110. },
  96111. enumerable: true,
  96112. configurable: true
  96113. });
  96114. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  96115. set: function (callback) {
  96116. if (this._onCompleteObserver) {
  96117. this.onCompleteObservable.remove(this._onCompleteObserver);
  96118. }
  96119. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  96120. },
  96121. enumerable: true,
  96122. configurable: true
  96123. });
  96124. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  96125. set: function (callback) {
  96126. if (this._onDisposeObserver) {
  96127. this.onDisposeObservable.remove(this._onDisposeObserver);
  96128. }
  96129. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  96130. },
  96131. enumerable: true,
  96132. configurable: true
  96133. });
  96134. Object.defineProperty(GLTFFileLoader.prototype, "onExtensionLoaded", {
  96135. set: function (callback) {
  96136. if (this._onExtensionLoadedObserver) {
  96137. this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver);
  96138. }
  96139. this._onExtensionLoadedObserver = this.onExtensionLoadedObservable.add(callback);
  96140. },
  96141. enumerable: true,
  96142. configurable: true
  96143. });
  96144. /**
  96145. * Gets a promise that resolves when the asset is completely loaded.
  96146. * @returns A promise that resolves when the asset is completely loaded.
  96147. */
  96148. GLTFFileLoader.prototype.whenCompleteAsync = function () {
  96149. var _this = this;
  96150. return new Promise(function (resolve) {
  96151. _this.onCompleteObservable.add(function () {
  96152. resolve();
  96153. }, undefined, undefined, undefined, true);
  96154. });
  96155. };
  96156. Object.defineProperty(GLTFFileLoader.prototype, "loaderState", {
  96157. /**
  96158. * The loader state or null if not active.
  96159. */
  96160. get: function () {
  96161. return this._loader ? this._loader.state : null;
  96162. },
  96163. enumerable: true,
  96164. configurable: true
  96165. });
  96166. /**
  96167. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  96168. */
  96169. GLTFFileLoader.prototype.dispose = function () {
  96170. if (this._loader) {
  96171. this._loader.dispose();
  96172. this._loader = null;
  96173. }
  96174. this.onMeshLoadedObservable.clear();
  96175. this.onTextureLoadedObservable.clear();
  96176. this.onMaterialLoadedObservable.clear();
  96177. this.onDisposeObservable.notifyObservers(this);
  96178. this.onDisposeObservable.clear();
  96179. };
  96180. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  96181. var _this = this;
  96182. return Promise.resolve().then(function () {
  96183. var loaderData = _this._parse(data);
  96184. _this._loader = _this._getLoader(loaderData);
  96185. return _this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onProgress);
  96186. });
  96187. };
  96188. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  96189. var _this = this;
  96190. return Promise.resolve().then(function () {
  96191. var loaderData = _this._parse(data);
  96192. _this._loader = _this._getLoader(loaderData);
  96193. return _this._loader.loadAsync(scene, loaderData, rootUrl, onProgress);
  96194. });
  96195. };
  96196. GLTFFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress) {
  96197. var _this = this;
  96198. return Promise.resolve().then(function () {
  96199. var loaderData = _this._parse(data);
  96200. _this._loader = _this._getLoader(loaderData);
  96201. return _this._loader.importMeshAsync(null, scene, loaderData, rootUrl, onProgress).then(function (result) {
  96202. var container = new BABYLON.AssetContainer(scene);
  96203. Array.prototype.push.apply(container.meshes, result.meshes);
  96204. Array.prototype.push.apply(container.particleSystems, result.particleSystems);
  96205. Array.prototype.push.apply(container.skeletons, result.skeletons);
  96206. container.removeAllFromScene();
  96207. return container;
  96208. });
  96209. });
  96210. };
  96211. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  96212. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  96213. };
  96214. GLTFFileLoader.prototype.createPlugin = function () {
  96215. return new GLTFFileLoader();
  96216. };
  96217. GLTFFileLoader.prototype._parse = function (data) {
  96218. var parsedData;
  96219. if (data instanceof ArrayBuffer) {
  96220. parsedData = GLTFFileLoader._parseBinary(data);
  96221. }
  96222. else {
  96223. parsedData = {
  96224. json: JSON.parse(data),
  96225. bin: null
  96226. };
  96227. }
  96228. this.onParsedObservable.notifyObservers(parsedData);
  96229. this.onParsedObservable.clear();
  96230. return parsedData;
  96231. };
  96232. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  96233. var _this = this;
  96234. var loaderVersion = { major: 2, minor: 0 };
  96235. var asset = loaderData.json.asset || {};
  96236. var version = GLTFFileLoader._parseVersion(asset.version);
  96237. if (!version) {
  96238. throw new Error("Invalid version: " + asset.version);
  96239. }
  96240. if (asset.minVersion !== undefined) {
  96241. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  96242. if (!minVersion) {
  96243. throw new Error("Invalid minimum version: " + asset.minVersion);
  96244. }
  96245. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  96246. throw new Error("Incompatible minimum version: " + asset.minVersion);
  96247. }
  96248. }
  96249. var createLoaders = {
  96250. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  96251. 2: GLTFFileLoader.CreateGLTFLoaderV2
  96252. };
  96253. var createLoader = createLoaders[version.major];
  96254. if (!createLoader) {
  96255. throw new Error("Unsupported version: " + asset.version);
  96256. }
  96257. var loader = createLoader();
  96258. loader.coordinateSystemMode = this.coordinateSystemMode;
  96259. loader.animationStartMode = this.animationStartMode;
  96260. loader.compileMaterials = this.compileMaterials;
  96261. loader.useClipPlane = this.useClipPlane;
  96262. loader.compileShadowGenerators = this.compileShadowGenerators;
  96263. loader.onMeshLoadedObservable.add(function (mesh) { return _this.onMeshLoadedObservable.notifyObservers(mesh); });
  96264. loader.onTextureLoadedObservable.add(function (texture) { return _this.onTextureLoadedObservable.notifyObservers(texture); });
  96265. loader.onMaterialLoadedObservable.add(function (material) { return _this.onMaterialLoadedObservable.notifyObservers(material); });
  96266. loader.onExtensionLoadedObservable.add(function (extension) { return _this.onExtensionLoadedObservable.notifyObservers(extension); });
  96267. loader.onAnimationGroupLoadedObservable.add(function (animationGroup) { return _this.onAnimationGroupLoadedObservable.notifyObservers(animationGroup); });
  96268. loader.onCompleteObservable.add(function () {
  96269. _this.onMeshLoadedObservable.clear();
  96270. _this.onTextureLoadedObservable.clear();
  96271. _this.onMaterialLoadedObservable.clear();
  96272. _this.onCompleteObservable.notifyObservers(_this);
  96273. _this.onCompleteObservable.clear();
  96274. });
  96275. return loader;
  96276. };
  96277. GLTFFileLoader._parseBinary = function (data) {
  96278. var Binary = {
  96279. Magic: 0x46546C67
  96280. };
  96281. var binaryReader = new BinaryReader(data);
  96282. var magic = binaryReader.readUint32();
  96283. if (magic !== Binary.Magic) {
  96284. throw new Error("Unexpected magic: " + magic);
  96285. }
  96286. var version = binaryReader.readUint32();
  96287. switch (version) {
  96288. case 1: return GLTFFileLoader._parseV1(binaryReader);
  96289. case 2: return GLTFFileLoader._parseV2(binaryReader);
  96290. }
  96291. throw new Error("Unsupported version: " + version);
  96292. };
  96293. GLTFFileLoader._parseV1 = function (binaryReader) {
  96294. var ContentFormat = {
  96295. JSON: 0
  96296. };
  96297. var length = binaryReader.readUint32();
  96298. if (length != binaryReader.getLength()) {
  96299. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  96300. }
  96301. var contentLength = binaryReader.readUint32();
  96302. var contentFormat = binaryReader.readUint32();
  96303. var content;
  96304. switch (contentFormat) {
  96305. case ContentFormat.JSON: {
  96306. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  96307. break;
  96308. }
  96309. default: {
  96310. throw new Error("Unexpected content format: " + contentFormat);
  96311. }
  96312. }
  96313. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  96314. var body = binaryReader.readUint8Array(bytesRemaining);
  96315. return {
  96316. json: content,
  96317. bin: body
  96318. };
  96319. };
  96320. GLTFFileLoader._parseV2 = function (binaryReader) {
  96321. var ChunkFormat = {
  96322. JSON: 0x4E4F534A,
  96323. BIN: 0x004E4942
  96324. };
  96325. var length = binaryReader.readUint32();
  96326. if (length !== binaryReader.getLength()) {
  96327. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  96328. }
  96329. // JSON chunk
  96330. var chunkLength = binaryReader.readUint32();
  96331. var chunkFormat = binaryReader.readUint32();
  96332. if (chunkFormat !== ChunkFormat.JSON) {
  96333. throw new Error("First chunk format is not JSON");
  96334. }
  96335. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  96336. // Look for BIN chunk
  96337. var bin = null;
  96338. while (binaryReader.getPosition() < binaryReader.getLength()) {
  96339. var chunkLength_1 = binaryReader.readUint32();
  96340. var chunkFormat_1 = binaryReader.readUint32();
  96341. switch (chunkFormat_1) {
  96342. case ChunkFormat.JSON: {
  96343. throw new Error("Unexpected JSON chunk");
  96344. }
  96345. case ChunkFormat.BIN: {
  96346. bin = binaryReader.readUint8Array(chunkLength_1);
  96347. break;
  96348. }
  96349. default: {
  96350. // ignore unrecognized chunkFormat
  96351. binaryReader.skipBytes(chunkLength_1);
  96352. break;
  96353. }
  96354. }
  96355. }
  96356. return {
  96357. json: json,
  96358. bin: bin
  96359. };
  96360. };
  96361. GLTFFileLoader._parseVersion = function (version) {
  96362. if (version === "1.0" || version === "1.0.1") {
  96363. return {
  96364. major: 1,
  96365. minor: 0
  96366. };
  96367. }
  96368. var match = (version + "").match(/^(\d+)\.(\d+)/);
  96369. if (!match) {
  96370. return null;
  96371. }
  96372. return {
  96373. major: parseInt(match[1]),
  96374. minor: parseInt(match[2])
  96375. };
  96376. };
  96377. GLTFFileLoader._compareVersion = function (a, b) {
  96378. if (a.major > b.major)
  96379. return 1;
  96380. if (a.major < b.major)
  96381. return -1;
  96382. if (a.minor > b.minor)
  96383. return 1;
  96384. if (a.minor < b.minor)
  96385. return -1;
  96386. return 0;
  96387. };
  96388. GLTFFileLoader._decodeBufferToText = function (buffer) {
  96389. var result = "";
  96390. var length = buffer.byteLength;
  96391. for (var i = 0; i < length; i++) {
  96392. result += String.fromCharCode(buffer[i]);
  96393. }
  96394. return result;
  96395. };
  96396. // #endregion
  96397. // #region V1 options
  96398. GLTFFileLoader.IncrementalLoading = true;
  96399. GLTFFileLoader.HomogeneousCoordinates = false;
  96400. return GLTFFileLoader;
  96401. }());
  96402. BABYLON.GLTFFileLoader = GLTFFileLoader;
  96403. var BinaryReader = /** @class */ (function () {
  96404. function BinaryReader(arrayBuffer) {
  96405. this._arrayBuffer = arrayBuffer;
  96406. this._dataView = new DataView(arrayBuffer);
  96407. this._byteOffset = 0;
  96408. }
  96409. BinaryReader.prototype.getPosition = function () {
  96410. return this._byteOffset;
  96411. };
  96412. BinaryReader.prototype.getLength = function () {
  96413. return this._arrayBuffer.byteLength;
  96414. };
  96415. BinaryReader.prototype.readUint32 = function () {
  96416. var value = this._dataView.getUint32(this._byteOffset, true);
  96417. this._byteOffset += 4;
  96418. return value;
  96419. };
  96420. BinaryReader.prototype.readUint8Array = function (length) {
  96421. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  96422. this._byteOffset += length;
  96423. return value;
  96424. };
  96425. BinaryReader.prototype.skipBytes = function (length) {
  96426. this._byteOffset += length;
  96427. };
  96428. return BinaryReader;
  96429. }());
  96430. if (BABYLON.SceneLoader) {
  96431. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  96432. }
  96433. })(BABYLON || (BABYLON = {}));
  96434. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  96435. "use strict";
  96436. var BABYLON;
  96437. (function (BABYLON) {
  96438. var GLTF1;
  96439. (function (GLTF1) {
  96440. /**
  96441. * Enums
  96442. */
  96443. var EComponentType;
  96444. (function (EComponentType) {
  96445. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  96446. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  96447. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  96448. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  96449. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  96450. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  96451. var EShaderType;
  96452. (function (EShaderType) {
  96453. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  96454. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  96455. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  96456. var EParameterType;
  96457. (function (EParameterType) {
  96458. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  96459. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  96460. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  96461. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  96462. EParameterType[EParameterType["INT"] = 5124] = "INT";
  96463. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  96464. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  96465. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  96466. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  96467. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  96468. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  96469. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  96470. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  96471. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  96472. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  96473. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  96474. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  96475. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  96476. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  96477. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  96478. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  96479. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  96480. var ETextureWrapMode;
  96481. (function (ETextureWrapMode) {
  96482. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  96483. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  96484. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  96485. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  96486. var ETextureFilterType;
  96487. (function (ETextureFilterType) {
  96488. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  96489. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  96490. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  96491. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  96492. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  96493. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  96494. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  96495. var ETextureFormat;
  96496. (function (ETextureFormat) {
  96497. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  96498. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  96499. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  96500. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  96501. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  96502. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  96503. var ECullingType;
  96504. (function (ECullingType) {
  96505. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  96506. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  96507. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  96508. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  96509. var EBlendingFunction;
  96510. (function (EBlendingFunction) {
  96511. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  96512. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  96513. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  96514. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  96515. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  96516. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  96517. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  96518. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  96519. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  96520. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  96521. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  96522. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  96523. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  96524. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  96525. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  96526. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  96527. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  96528. })(BABYLON || (BABYLON = {}));
  96529. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  96530. "use strict";
  96531. var BABYLON;
  96532. (function (BABYLON) {
  96533. var GLTF1;
  96534. (function (GLTF1) {
  96535. /**
  96536. * Tokenizer. Used for shaders compatibility
  96537. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  96538. */
  96539. var ETokenType;
  96540. (function (ETokenType) {
  96541. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  96542. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  96543. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  96544. })(ETokenType || (ETokenType = {}));
  96545. var Tokenizer = /** @class */ (function () {
  96546. function Tokenizer(toParse) {
  96547. this._pos = 0;
  96548. this.currentToken = ETokenType.UNKNOWN;
  96549. this.currentIdentifier = "";
  96550. this.currentString = "";
  96551. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  96552. this._toParse = toParse;
  96553. this._maxPos = toParse.length;
  96554. }
  96555. Tokenizer.prototype.getNextToken = function () {
  96556. if (this.isEnd())
  96557. return ETokenType.END_OF_INPUT;
  96558. this.currentString = this.read();
  96559. this.currentToken = ETokenType.UNKNOWN;
  96560. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  96561. this.currentToken = ETokenType.IDENTIFIER;
  96562. this.currentIdentifier = this.currentString;
  96563. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  96564. this.currentIdentifier += this.currentString;
  96565. this.forward();
  96566. }
  96567. }
  96568. return this.currentToken;
  96569. };
  96570. Tokenizer.prototype.peek = function () {
  96571. return this._toParse[this._pos];
  96572. };
  96573. Tokenizer.prototype.read = function () {
  96574. return this._toParse[this._pos++];
  96575. };
  96576. Tokenizer.prototype.forward = function () {
  96577. this._pos++;
  96578. };
  96579. Tokenizer.prototype.isEnd = function () {
  96580. return this._pos >= this._maxPos;
  96581. };
  96582. return Tokenizer;
  96583. }());
  96584. /**
  96585. * Values
  96586. */
  96587. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  96588. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  96589. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  96590. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  96591. /**
  96592. * Parse
  96593. */
  96594. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  96595. for (var buf in parsedBuffers) {
  96596. var parsedBuffer = parsedBuffers[buf];
  96597. gltfRuntime.buffers[buf] = parsedBuffer;
  96598. gltfRuntime.buffersCount++;
  96599. }
  96600. };
  96601. var parseShaders = function (parsedShaders, gltfRuntime) {
  96602. for (var sha in parsedShaders) {
  96603. var parsedShader = parsedShaders[sha];
  96604. gltfRuntime.shaders[sha] = parsedShader;
  96605. gltfRuntime.shaderscount++;
  96606. }
  96607. };
  96608. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  96609. for (var object in parsedObjects) {
  96610. var parsedObject = parsedObjects[object];
  96611. gltfRuntime[runtimeProperty][object] = parsedObject;
  96612. }
  96613. };
  96614. /**
  96615. * Utils
  96616. */
  96617. var normalizeUVs = function (buffer) {
  96618. if (!buffer) {
  96619. return;
  96620. }
  96621. for (var i = 0; i < buffer.length / 2; i++) {
  96622. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  96623. }
  96624. };
  96625. var getAttribute = function (attributeParameter) {
  96626. if (attributeParameter.semantic === "NORMAL") {
  96627. return "normal";
  96628. }
  96629. else if (attributeParameter.semantic === "POSITION") {
  96630. return "position";
  96631. }
  96632. else if (attributeParameter.semantic === "JOINT") {
  96633. return "matricesIndices";
  96634. }
  96635. else if (attributeParameter.semantic === "WEIGHT") {
  96636. return "matricesWeights";
  96637. }
  96638. else if (attributeParameter.semantic === "COLOR") {
  96639. return "color";
  96640. }
  96641. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  96642. var channel = Number(attributeParameter.semantic.split("_")[1]);
  96643. return "uv" + (channel === 0 ? "" : channel + 1);
  96644. }
  96645. return null;
  96646. };
  96647. /**
  96648. * Loads and creates animations
  96649. */
  96650. var loadAnimations = function (gltfRuntime) {
  96651. for (var anim in gltfRuntime.animations) {
  96652. var animation = gltfRuntime.animations[anim];
  96653. if (!animation.channels || !animation.samplers) {
  96654. continue;
  96655. }
  96656. var lastAnimation = null;
  96657. for (var i = 0; i < animation.channels.length; i++) {
  96658. // Get parameters and load buffers
  96659. var channel = animation.channels[i];
  96660. var sampler = animation.samplers[channel.sampler];
  96661. if (!sampler) {
  96662. continue;
  96663. }
  96664. var inputData = null;
  96665. var outputData = null;
  96666. if (animation.parameters) {
  96667. inputData = animation.parameters[sampler.input];
  96668. outputData = animation.parameters[sampler.output];
  96669. }
  96670. else {
  96671. inputData = sampler.input;
  96672. outputData = sampler.output;
  96673. }
  96674. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  96675. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  96676. var targetID = channel.target.id;
  96677. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  96678. if (targetNode === null) {
  96679. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  96680. }
  96681. if (targetNode === null) {
  96682. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  96683. continue;
  96684. }
  96685. var isBone = targetNode instanceof BABYLON.Bone;
  96686. // Get target path (position, rotation or scaling)
  96687. var targetPath = channel.target.path;
  96688. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  96689. if (targetPathIndex !== -1) {
  96690. targetPath = babylonAnimationPaths[targetPathIndex];
  96691. }
  96692. // Determine animation type
  96693. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  96694. if (!isBone) {
  96695. if (targetPath === "rotationQuaternion") {
  96696. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  96697. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  96698. }
  96699. else {
  96700. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  96701. }
  96702. }
  96703. // Create animation and key frames
  96704. var babylonAnimation = null;
  96705. var keys = [];
  96706. var arrayOffset = 0;
  96707. var modifyKey = false;
  96708. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  96709. babylonAnimation = lastAnimation;
  96710. modifyKey = true;
  96711. }
  96712. if (!modifyKey) {
  96713. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  96714. }
  96715. // For each frame
  96716. for (var j = 0; j < bufferInput.length; j++) {
  96717. var value = null;
  96718. if (targetPath === "rotationQuaternion") {
  96719. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  96720. arrayOffset += 4;
  96721. }
  96722. else {
  96723. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  96724. arrayOffset += 3;
  96725. }
  96726. if (isBone) {
  96727. var bone = targetNode;
  96728. var translation = BABYLON.Vector3.Zero();
  96729. var rotationQuaternion = new BABYLON.Quaternion();
  96730. var scaling = BABYLON.Vector3.Zero();
  96731. // Warning on decompose
  96732. var mat = bone.getBaseMatrix();
  96733. if (modifyKey && lastAnimation) {
  96734. mat = lastAnimation.getKeys()[j].value;
  96735. }
  96736. mat.decompose(scaling, rotationQuaternion, translation);
  96737. if (targetPath === "position") {
  96738. translation = value;
  96739. }
  96740. else if (targetPath === "rotationQuaternion") {
  96741. rotationQuaternion = value;
  96742. }
  96743. else {
  96744. scaling = value;
  96745. }
  96746. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  96747. }
  96748. if (!modifyKey) {
  96749. keys.push({
  96750. frame: bufferInput[j],
  96751. value: value
  96752. });
  96753. }
  96754. else if (lastAnimation) {
  96755. lastAnimation.getKeys()[j].value = value;
  96756. }
  96757. }
  96758. // Finish
  96759. if (!modifyKey && babylonAnimation) {
  96760. babylonAnimation.setKeys(keys);
  96761. targetNode.animations.push(babylonAnimation);
  96762. }
  96763. lastAnimation = babylonAnimation;
  96764. gltfRuntime.scene.stopAnimation(targetNode);
  96765. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  96766. }
  96767. }
  96768. };
  96769. /**
  96770. * Returns the bones transformation matrix
  96771. */
  96772. var configureBoneTransformation = function (node) {
  96773. var mat = null;
  96774. if (node.translation || node.rotation || node.scale) {
  96775. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  96776. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  96777. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  96778. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  96779. }
  96780. else {
  96781. mat = BABYLON.Matrix.FromArray(node.matrix);
  96782. }
  96783. return mat;
  96784. };
  96785. /**
  96786. * Returns the parent bone
  96787. */
  96788. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  96789. // Try to find
  96790. for (var i = 0; i < newSkeleton.bones.length; i++) {
  96791. if (newSkeleton.bones[i].name === jointName) {
  96792. return newSkeleton.bones[i];
  96793. }
  96794. }
  96795. // Not found, search in gltf nodes
  96796. var nodes = gltfRuntime.nodes;
  96797. for (var nde in nodes) {
  96798. var node = nodes[nde];
  96799. if (!node.jointName) {
  96800. continue;
  96801. }
  96802. var children = node.children;
  96803. for (var i = 0; i < children.length; i++) {
  96804. var child = gltfRuntime.nodes[children[i]];
  96805. if (!child.jointName) {
  96806. continue;
  96807. }
  96808. if (child.jointName === jointName) {
  96809. var mat = configureBoneTransformation(node);
  96810. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  96811. bone.id = nde;
  96812. return bone;
  96813. }
  96814. }
  96815. }
  96816. return null;
  96817. };
  96818. /**
  96819. * Returns the appropriate root node
  96820. */
  96821. var getNodeToRoot = function (nodesToRoot, id) {
  96822. for (var i = 0; i < nodesToRoot.length; i++) {
  96823. var nodeToRoot = nodesToRoot[i];
  96824. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  96825. var child = nodeToRoot.node.children[j];
  96826. if (child === id) {
  96827. return nodeToRoot.bone;
  96828. }
  96829. }
  96830. }
  96831. return null;
  96832. };
  96833. /**
  96834. * Returns the node with the joint name
  96835. */
  96836. var getJointNode = function (gltfRuntime, jointName) {
  96837. var nodes = gltfRuntime.nodes;
  96838. var node = nodes[jointName];
  96839. if (node) {
  96840. return {
  96841. node: node,
  96842. id: jointName
  96843. };
  96844. }
  96845. for (var nde in nodes) {
  96846. node = nodes[nde];
  96847. if (node.jointName === jointName) {
  96848. return {
  96849. node: node,
  96850. id: nde
  96851. };
  96852. }
  96853. }
  96854. return null;
  96855. };
  96856. /**
  96857. * Checks if a nodes is in joints
  96858. */
  96859. var nodeIsInJoints = function (skins, id) {
  96860. for (var i = 0; i < skins.jointNames.length; i++) {
  96861. if (skins.jointNames[i] === id) {
  96862. return true;
  96863. }
  96864. }
  96865. return false;
  96866. };
  96867. /**
  96868. * Fills the nodes to root for bones and builds hierarchy
  96869. */
  96870. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  96871. // Creates nodes for root
  96872. for (var nde in gltfRuntime.nodes) {
  96873. var node = gltfRuntime.nodes[nde];
  96874. var id = nde;
  96875. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  96876. continue;
  96877. }
  96878. // Create node to root bone
  96879. var mat = configureBoneTransformation(node);
  96880. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  96881. bone.id = id;
  96882. nodesToRoot.push({ bone: bone, node: node, id: id });
  96883. }
  96884. // Parenting
  96885. for (var i = 0; i < nodesToRoot.length; i++) {
  96886. var nodeToRoot = nodesToRoot[i];
  96887. var children = nodeToRoot.node.children;
  96888. for (var j = 0; j < children.length; j++) {
  96889. var child = null;
  96890. for (var k = 0; k < nodesToRoot.length; k++) {
  96891. if (nodesToRoot[k].id === children[j]) {
  96892. child = nodesToRoot[k];
  96893. break;
  96894. }
  96895. }
  96896. if (child) {
  96897. child.bone._parent = nodeToRoot.bone;
  96898. nodeToRoot.bone.children.push(child.bone);
  96899. }
  96900. }
  96901. }
  96902. };
  96903. /**
  96904. * Imports a skeleton
  96905. */
  96906. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  96907. if (!newSkeleton) {
  96908. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  96909. }
  96910. if (!skins.babylonSkeleton) {
  96911. return newSkeleton;
  96912. }
  96913. // Find the root bones
  96914. var nodesToRoot = [];
  96915. var nodesToRootToAdd = [];
  96916. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  96917. newSkeleton.bones = [];
  96918. // Joints
  96919. for (var i = 0; i < skins.jointNames.length; i++) {
  96920. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  96921. if (!jointNode) {
  96922. continue;
  96923. }
  96924. var node = jointNode.node;
  96925. if (!node) {
  96926. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  96927. continue;
  96928. }
  96929. var id = jointNode.id;
  96930. // Optimize, if the bone already exists...
  96931. var existingBone = gltfRuntime.scene.getBoneByID(id);
  96932. if (existingBone) {
  96933. newSkeleton.bones.push(existingBone);
  96934. continue;
  96935. }
  96936. // Search for parent bone
  96937. var foundBone = false;
  96938. var parentBone = null;
  96939. for (var j = 0; j < i; j++) {
  96940. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  96941. if (!jointNode_1) {
  96942. continue;
  96943. }
  96944. var joint = jointNode_1.node;
  96945. if (!joint) {
  96946. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  96947. continue;
  96948. }
  96949. var children = joint.children;
  96950. if (!children) {
  96951. continue;
  96952. }
  96953. foundBone = false;
  96954. for (var k = 0; k < children.length; k++) {
  96955. if (children[k] === id) {
  96956. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  96957. foundBone = true;
  96958. break;
  96959. }
  96960. }
  96961. if (foundBone) {
  96962. break;
  96963. }
  96964. }
  96965. // Create bone
  96966. var mat = configureBoneTransformation(node);
  96967. if (!parentBone && nodesToRoot.length > 0) {
  96968. parentBone = getNodeToRoot(nodesToRoot, id);
  96969. if (parentBone) {
  96970. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  96971. nodesToRootToAdd.push(parentBone);
  96972. }
  96973. }
  96974. }
  96975. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  96976. bone.id = id;
  96977. }
  96978. // Polish
  96979. var bones = newSkeleton.bones;
  96980. newSkeleton.bones = [];
  96981. for (var i = 0; i < skins.jointNames.length; i++) {
  96982. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  96983. if (!jointNode) {
  96984. continue;
  96985. }
  96986. for (var j = 0; j < bones.length; j++) {
  96987. if (bones[j].id === jointNode.id) {
  96988. newSkeleton.bones.push(bones[j]);
  96989. break;
  96990. }
  96991. }
  96992. }
  96993. newSkeleton.prepare();
  96994. // Finish
  96995. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  96996. newSkeleton.bones.push(nodesToRootToAdd[i]);
  96997. }
  96998. return newSkeleton;
  96999. };
  97000. /**
  97001. * Imports a mesh and its geometries
  97002. */
  97003. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  97004. if (!newMesh) {
  97005. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  97006. newMesh.id = id;
  97007. }
  97008. if (!node.babylonNode) {
  97009. return newMesh;
  97010. }
  97011. var subMaterials = [];
  97012. var vertexData = null;
  97013. var verticesStarts = new Array();
  97014. var verticesCounts = new Array();
  97015. var indexStarts = new Array();
  97016. var indexCounts = new Array();
  97017. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  97018. var meshID = meshes[meshIndex];
  97019. var mesh = gltfRuntime.meshes[meshID];
  97020. if (!mesh) {
  97021. continue;
  97022. }
  97023. // Positions, normals and UVs
  97024. for (var i = 0; i < mesh.primitives.length; i++) {
  97025. // Temporary vertex data
  97026. var tempVertexData = new BABYLON.VertexData();
  97027. var primitive = mesh.primitives[i];
  97028. if (primitive.mode !== 4) {
  97029. // continue;
  97030. }
  97031. var attributes = primitive.attributes;
  97032. var accessor = null;
  97033. var buffer = null;
  97034. // Set positions, normal and uvs
  97035. for (var semantic in attributes) {
  97036. // Link accessor and buffer view
  97037. accessor = gltfRuntime.accessors[attributes[semantic]];
  97038. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  97039. if (semantic === "NORMAL") {
  97040. tempVertexData.normals = new Float32Array(buffer.length);
  97041. tempVertexData.normals.set(buffer);
  97042. }
  97043. else if (semantic === "POSITION") {
  97044. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  97045. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  97046. for (var j = 0; j < buffer.length; j += 4) {
  97047. tempVertexData.positions[j] = buffer[j];
  97048. tempVertexData.positions[j + 1] = buffer[j + 1];
  97049. tempVertexData.positions[j + 2] = buffer[j + 2];
  97050. }
  97051. }
  97052. else {
  97053. tempVertexData.positions = new Float32Array(buffer.length);
  97054. tempVertexData.positions.set(buffer);
  97055. }
  97056. verticesCounts.push(tempVertexData.positions.length);
  97057. }
  97058. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  97059. var channel = Number(semantic.split("_")[1]);
  97060. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  97061. var uvs = new Float32Array(buffer.length);
  97062. uvs.set(buffer);
  97063. normalizeUVs(uvs);
  97064. tempVertexData.set(uvs, uvKind);
  97065. }
  97066. else if (semantic === "JOINT") {
  97067. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  97068. tempVertexData.matricesIndices.set(buffer);
  97069. }
  97070. else if (semantic === "WEIGHT") {
  97071. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  97072. tempVertexData.matricesWeights.set(buffer);
  97073. }
  97074. else if (semantic === "COLOR") {
  97075. tempVertexData.colors = new Float32Array(buffer.length);
  97076. tempVertexData.colors.set(buffer);
  97077. }
  97078. }
  97079. // Indices
  97080. accessor = gltfRuntime.accessors[primitive.indices];
  97081. if (accessor) {
  97082. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  97083. tempVertexData.indices = new Int32Array(buffer.length);
  97084. tempVertexData.indices.set(buffer);
  97085. indexCounts.push(tempVertexData.indices.length);
  97086. }
  97087. else {
  97088. // Set indices on the fly
  97089. var indices = [];
  97090. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  97091. indices.push(j);
  97092. }
  97093. tempVertexData.indices = new Int32Array(indices);
  97094. indexCounts.push(tempVertexData.indices.length);
  97095. }
  97096. if (!vertexData) {
  97097. vertexData = tempVertexData;
  97098. }
  97099. else {
  97100. vertexData.merge(tempVertexData);
  97101. }
  97102. // Sub material
  97103. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  97104. subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  97105. // Update vertices start and index start
  97106. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  97107. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  97108. }
  97109. }
  97110. var material;
  97111. if (subMaterials.length > 1) {
  97112. material = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  97113. material.subMaterials = subMaterials;
  97114. }
  97115. else {
  97116. material = new BABYLON.StandardMaterial("multimat" + id, gltfRuntime.scene);
  97117. }
  97118. if (subMaterials.length === 1) {
  97119. material = subMaterials[0];
  97120. }
  97121. if (!newMesh.material) {
  97122. newMesh.material = material;
  97123. }
  97124. // Apply geometry
  97125. new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  97126. newMesh.computeWorldMatrix(true);
  97127. // Apply submeshes
  97128. newMesh.subMeshes = [];
  97129. var index = 0;
  97130. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  97131. var meshID = meshes[meshIndex];
  97132. var mesh = gltfRuntime.meshes[meshID];
  97133. if (!mesh) {
  97134. continue;
  97135. }
  97136. for (var i = 0; i < mesh.primitives.length; i++) {
  97137. if (mesh.primitives[i].mode !== 4) {
  97138. //continue;
  97139. }
  97140. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  97141. index++;
  97142. }
  97143. }
  97144. // Finish
  97145. return newMesh;
  97146. };
  97147. /**
  97148. * Configure node transformation from position, rotation and scaling
  97149. */
  97150. var configureNode = function (newNode, position, rotation, scaling) {
  97151. if (newNode.position) {
  97152. newNode.position = position;
  97153. }
  97154. if (newNode.rotationQuaternion || newNode.rotation) {
  97155. newNode.rotationQuaternion = rotation;
  97156. }
  97157. if (newNode.scaling) {
  97158. newNode.scaling = scaling;
  97159. }
  97160. };
  97161. /**
  97162. * Configures node from transformation matrix
  97163. */
  97164. var configureNodeFromMatrix = function (newNode, node, parent) {
  97165. if (node.matrix) {
  97166. var position = new BABYLON.Vector3(0, 0, 0);
  97167. var rotation = new BABYLON.Quaternion();
  97168. var scaling = new BABYLON.Vector3(0, 0, 0);
  97169. var mat = BABYLON.Matrix.FromArray(node.matrix);
  97170. mat.decompose(scaling, rotation, position);
  97171. configureNode(newNode, position, rotation, scaling);
  97172. }
  97173. else if (node.translation && node.rotation && node.scale) {
  97174. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  97175. }
  97176. newNode.computeWorldMatrix(true);
  97177. };
  97178. /**
  97179. * Imports a node
  97180. */
  97181. var importNode = function (gltfRuntime, node, id, parent) {
  97182. var lastNode = null;
  97183. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  97184. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  97185. return null;
  97186. }
  97187. }
  97188. // Meshes
  97189. if (node.skin) {
  97190. if (node.meshes) {
  97191. var skin = gltfRuntime.skins[node.skin];
  97192. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  97193. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  97194. if (newMesh.skeleton === null) {
  97195. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  97196. if (!skin.babylonSkeleton) {
  97197. skin.babylonSkeleton = newMesh.skeleton;
  97198. }
  97199. }
  97200. lastNode = newMesh;
  97201. }
  97202. }
  97203. else if (node.meshes) {
  97204. /**
  97205. * Improve meshes property
  97206. */
  97207. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  97208. lastNode = newMesh;
  97209. }
  97210. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  97211. var light = gltfRuntime.lights[node.light];
  97212. if (light) {
  97213. if (light.type === "ambient") {
  97214. var ambienLight = light[light.type];
  97215. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  97216. hemiLight.name = node.name || "";
  97217. if (ambienLight.color) {
  97218. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  97219. }
  97220. lastNode = hemiLight;
  97221. }
  97222. else if (light.type === "directional") {
  97223. var directionalLight = light[light.type];
  97224. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  97225. dirLight.name = node.name || "";
  97226. if (directionalLight.color) {
  97227. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  97228. }
  97229. lastNode = dirLight;
  97230. }
  97231. else if (light.type === "point") {
  97232. var pointLight = light[light.type];
  97233. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  97234. ptLight.name = node.name || "";
  97235. if (pointLight.color) {
  97236. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  97237. }
  97238. lastNode = ptLight;
  97239. }
  97240. else if (light.type === "spot") {
  97241. var spotLight = light[light.type];
  97242. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  97243. spLight.name = node.name || "";
  97244. if (spotLight.color) {
  97245. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  97246. }
  97247. if (spotLight.fallOfAngle) {
  97248. spLight.angle = spotLight.fallOfAngle;
  97249. }
  97250. if (spotLight.fallOffExponent) {
  97251. spLight.exponent = spotLight.fallOffExponent;
  97252. }
  97253. lastNode = spLight;
  97254. }
  97255. }
  97256. }
  97257. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  97258. var camera = gltfRuntime.cameras[node.camera];
  97259. if (camera) {
  97260. if (camera.type === "orthographic") {
  97261. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  97262. orthoCamera.name = node.name || "";
  97263. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  97264. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  97265. lastNode = orthoCamera;
  97266. }
  97267. else if (camera.type === "perspective") {
  97268. var perspectiveCamera = camera[camera.type];
  97269. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  97270. persCamera.name = node.name || "";
  97271. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  97272. if (!perspectiveCamera.aspectRatio) {
  97273. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  97274. }
  97275. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  97276. persCamera.maxZ = perspectiveCamera.zfar;
  97277. persCamera.minZ = perspectiveCamera.znear;
  97278. }
  97279. lastNode = persCamera;
  97280. }
  97281. }
  97282. }
  97283. // Empty node
  97284. if (!node.jointName) {
  97285. if (node.babylonNode) {
  97286. return node.babylonNode;
  97287. }
  97288. else if (lastNode === null) {
  97289. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  97290. node.babylonNode = dummy;
  97291. lastNode = dummy;
  97292. }
  97293. }
  97294. if (lastNode !== null) {
  97295. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  97296. configureNodeFromMatrix(lastNode, node, parent);
  97297. }
  97298. else {
  97299. var translation = node.translation || [0, 0, 0];
  97300. var rotation = node.rotation || [0, 0, 0, 1];
  97301. var scale = node.scale || [1, 1, 1];
  97302. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  97303. }
  97304. lastNode.updateCache(true);
  97305. node.babylonNode = lastNode;
  97306. }
  97307. return lastNode;
  97308. };
  97309. /**
  97310. * Traverses nodes and creates them
  97311. */
  97312. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  97313. if (meshIncluded === void 0) { meshIncluded = false; }
  97314. var node = gltfRuntime.nodes[id];
  97315. var newNode = null;
  97316. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  97317. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  97318. meshIncluded = true;
  97319. }
  97320. else {
  97321. meshIncluded = false;
  97322. }
  97323. }
  97324. else {
  97325. meshIncluded = true;
  97326. }
  97327. if (!node.jointName && meshIncluded) {
  97328. newNode = importNode(gltfRuntime, node, id, parent);
  97329. if (newNode !== null) {
  97330. newNode.id = id;
  97331. newNode.parent = parent;
  97332. }
  97333. }
  97334. if (node.children) {
  97335. for (var i = 0; i < node.children.length; i++) {
  97336. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  97337. }
  97338. }
  97339. };
  97340. /**
  97341. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  97342. */
  97343. var postLoad = function (gltfRuntime) {
  97344. // Nodes
  97345. var currentScene = gltfRuntime.currentScene;
  97346. if (currentScene) {
  97347. for (var i = 0; i < currentScene.nodes.length; i++) {
  97348. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  97349. }
  97350. }
  97351. else {
  97352. for (var thing in gltfRuntime.scenes) {
  97353. currentScene = gltfRuntime.scenes[thing];
  97354. for (var i = 0; i < currentScene.nodes.length; i++) {
  97355. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  97356. }
  97357. }
  97358. }
  97359. // Set animations
  97360. loadAnimations(gltfRuntime);
  97361. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  97362. var skeleton = gltfRuntime.scene.skeletons[i];
  97363. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  97364. }
  97365. };
  97366. /**
  97367. * onBind shaderrs callback to set uniforms and matrices
  97368. */
  97369. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  97370. var materialValues = material.values || technique.parameters;
  97371. for (var unif in unTreatedUniforms) {
  97372. var uniform = unTreatedUniforms[unif];
  97373. var type = uniform.type;
  97374. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  97375. if (uniform.semantic && !uniform.source && !uniform.node) {
  97376. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  97377. }
  97378. else if (uniform.semantic && (uniform.source || uniform.node)) {
  97379. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  97380. if (source === null) {
  97381. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  97382. }
  97383. if (source === null) {
  97384. continue;
  97385. }
  97386. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  97387. }
  97388. }
  97389. else {
  97390. var value = materialValues[technique.uniforms[unif]];
  97391. if (!value) {
  97392. continue;
  97393. }
  97394. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  97395. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  97396. if (texture === null || texture === undefined) {
  97397. continue;
  97398. }
  97399. shaderMaterial.getEffect().setTexture(unif, texture);
  97400. }
  97401. else {
  97402. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  97403. }
  97404. }
  97405. }
  97406. onSuccess(shaderMaterial);
  97407. };
  97408. /**
  97409. * Prepare uniforms to send the only one time
  97410. * Loads the appropriate textures
  97411. */
  97412. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  97413. var materialValues = material.values || technique.parameters;
  97414. var techniqueUniforms = technique.uniforms;
  97415. /**
  97416. * Prepare values here (not matrices)
  97417. */
  97418. for (var unif in unTreatedUniforms) {
  97419. var uniform = unTreatedUniforms[unif];
  97420. var type = uniform.type;
  97421. var value = materialValues[techniqueUniforms[unif]];
  97422. if (value === undefined) {
  97423. // In case the value is the same for all materials
  97424. value = uniform.value;
  97425. }
  97426. if (!value) {
  97427. continue;
  97428. }
  97429. var onLoadTexture = function (uniformName) {
  97430. return function (texture) {
  97431. if (uniform.value && uniformName) {
  97432. // Static uniform
  97433. shaderMaterial.setTexture(uniformName, texture);
  97434. delete unTreatedUniforms[uniformName];
  97435. }
  97436. };
  97437. };
  97438. // Texture (sampler2D)
  97439. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  97440. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  97441. }
  97442. else {
  97443. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  97444. // Static uniform
  97445. delete unTreatedUniforms[unif];
  97446. }
  97447. }
  97448. }
  97449. };
  97450. /**
  97451. * Shader compilation failed
  97452. */
  97453. var onShaderCompileError = function (program, shaderMaterial, onError) {
  97454. return function (effect, error) {
  97455. shaderMaterial.dispose(true);
  97456. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  97457. };
  97458. };
  97459. /**
  97460. * Shader compilation success
  97461. */
  97462. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  97463. return function (_) {
  97464. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  97465. shaderMaterial.onBind = function (mesh) {
  97466. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  97467. };
  97468. };
  97469. };
  97470. /**
  97471. * Returns the appropriate uniform if already handled by babylon
  97472. */
  97473. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  97474. for (var unif in technique.uniforms) {
  97475. var uniform = technique.uniforms[unif];
  97476. var uniformParameter = technique.parameters[uniform];
  97477. if (tokenizer.currentIdentifier === unif) {
  97478. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  97479. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  97480. if (transformIndex !== -1) {
  97481. delete unTreatedUniforms[unif];
  97482. return babylonTransforms[transformIndex];
  97483. }
  97484. }
  97485. }
  97486. }
  97487. return tokenizer.currentIdentifier;
  97488. };
  97489. /**
  97490. * All shaders loaded. Create materials one by one
  97491. */
  97492. var importMaterials = function (gltfRuntime) {
  97493. // Create materials
  97494. for (var mat in gltfRuntime.materials) {
  97495. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  97496. }
  97497. };
  97498. /**
  97499. * Implementation of the base glTF spec
  97500. */
  97501. var GLTFLoaderBase = /** @class */ (function () {
  97502. function GLTFLoaderBase() {
  97503. }
  97504. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  97505. var gltfRuntime = {
  97506. extensions: {},
  97507. accessors: {},
  97508. buffers: {},
  97509. bufferViews: {},
  97510. meshes: {},
  97511. lights: {},
  97512. cameras: {},
  97513. nodes: {},
  97514. images: {},
  97515. textures: {},
  97516. shaders: {},
  97517. programs: {},
  97518. samplers: {},
  97519. techniques: {},
  97520. materials: {},
  97521. animations: {},
  97522. skins: {},
  97523. extensionsUsed: [],
  97524. scenes: {},
  97525. buffersCount: 0,
  97526. shaderscount: 0,
  97527. scene: scene,
  97528. rootUrl: rootUrl,
  97529. loadedBufferCount: 0,
  97530. loadedBufferViews: {},
  97531. loadedShaderCount: 0,
  97532. importOnlyMeshes: false,
  97533. dummyNodes: []
  97534. };
  97535. // Parse
  97536. if (parsedData.extensions) {
  97537. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  97538. }
  97539. if (parsedData.extensionsUsed) {
  97540. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  97541. }
  97542. if (parsedData.buffers) {
  97543. parseBuffers(parsedData.buffers, gltfRuntime);
  97544. }
  97545. if (parsedData.bufferViews) {
  97546. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  97547. }
  97548. if (parsedData.accessors) {
  97549. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  97550. }
  97551. if (parsedData.meshes) {
  97552. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  97553. }
  97554. if (parsedData.lights) {
  97555. parseObject(parsedData.lights, "lights", gltfRuntime);
  97556. }
  97557. if (parsedData.cameras) {
  97558. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  97559. }
  97560. if (parsedData.nodes) {
  97561. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  97562. }
  97563. if (parsedData.images) {
  97564. parseObject(parsedData.images, "images", gltfRuntime);
  97565. }
  97566. if (parsedData.textures) {
  97567. parseObject(parsedData.textures, "textures", gltfRuntime);
  97568. }
  97569. if (parsedData.shaders) {
  97570. parseShaders(parsedData.shaders, gltfRuntime);
  97571. }
  97572. if (parsedData.programs) {
  97573. parseObject(parsedData.programs, "programs", gltfRuntime);
  97574. }
  97575. if (parsedData.samplers) {
  97576. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  97577. }
  97578. if (parsedData.techniques) {
  97579. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  97580. }
  97581. if (parsedData.materials) {
  97582. parseObject(parsedData.materials, "materials", gltfRuntime);
  97583. }
  97584. if (parsedData.animations) {
  97585. parseObject(parsedData.animations, "animations", gltfRuntime);
  97586. }
  97587. if (parsedData.skins) {
  97588. parseObject(parsedData.skins, "skins", gltfRuntime);
  97589. }
  97590. if (parsedData.scenes) {
  97591. gltfRuntime.scenes = parsedData.scenes;
  97592. }
  97593. if (parsedData.scene && parsedData.scenes) {
  97594. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  97595. }
  97596. return gltfRuntime;
  97597. };
  97598. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  97599. var buffer = gltfRuntime.buffers[id];
  97600. if (BABYLON.Tools.IsBase64(buffer.uri)) {
  97601. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(buffer.uri))); });
  97602. }
  97603. else {
  97604. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  97605. if (request) {
  97606. onError(request.status + " " + request.statusText);
  97607. }
  97608. });
  97609. }
  97610. };
  97611. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  97612. var texture = gltfRuntime.textures[id];
  97613. if (!texture || !texture.source) {
  97614. onError("");
  97615. return;
  97616. }
  97617. if (texture.babylonTexture) {
  97618. onSuccess(null);
  97619. return;
  97620. }
  97621. var source = gltfRuntime.images[texture.source];
  97622. if (BABYLON.Tools.IsBase64(source.uri)) {
  97623. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(source.uri))); });
  97624. }
  97625. else {
  97626. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  97627. if (request) {
  97628. onError(request.status + " " + request.statusText);
  97629. }
  97630. });
  97631. }
  97632. };
  97633. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  97634. var texture = gltfRuntime.textures[id];
  97635. if (texture.babylonTexture) {
  97636. onSuccess(texture.babylonTexture);
  97637. return;
  97638. }
  97639. var sampler = gltfRuntime.samplers[texture.sampler];
  97640. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  97641. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  97642. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  97643. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  97644. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  97645. var blob = new Blob([buffer]);
  97646. var blobURL = URL.createObjectURL(blob);
  97647. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  97648. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  97649. if (sampler.wrapS !== undefined) {
  97650. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  97651. }
  97652. if (sampler.wrapT !== undefined) {
  97653. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  97654. }
  97655. newTexture.name = id;
  97656. texture.babylonTexture = newTexture;
  97657. onSuccess(newTexture);
  97658. };
  97659. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  97660. var shader = gltfRuntime.shaders[id];
  97661. if (BABYLON.Tools.IsBase64(shader.uri)) {
  97662. var shaderString = atob(shader.uri.split(",")[1]);
  97663. if (onSuccess) {
  97664. onSuccess(shaderString);
  97665. }
  97666. }
  97667. else {
  97668. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  97669. if (request && onError) {
  97670. onError(request.status + " " + request.statusText);
  97671. }
  97672. });
  97673. }
  97674. };
  97675. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  97676. var material = gltfRuntime.materials[id];
  97677. if (!material.technique) {
  97678. if (onError) {
  97679. onError("No technique found.");
  97680. }
  97681. return;
  97682. }
  97683. var technique = gltfRuntime.techniques[material.technique];
  97684. if (!technique) {
  97685. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  97686. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  97687. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  97688. onSuccess(defaultMaterial);
  97689. return;
  97690. }
  97691. var program = gltfRuntime.programs[technique.program];
  97692. var states = technique.states;
  97693. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  97694. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  97695. var newVertexShader = "";
  97696. var newPixelShader = "";
  97697. var vertexTokenizer = new Tokenizer(vertexShader);
  97698. var pixelTokenizer = new Tokenizer(pixelShader);
  97699. var unTreatedUniforms = {};
  97700. var uniforms = [];
  97701. var attributes = [];
  97702. var samplers = [];
  97703. // Fill uniform, sampler2D and attributes
  97704. for (var unif in technique.uniforms) {
  97705. var uniform = technique.uniforms[unif];
  97706. var uniformParameter = technique.parameters[uniform];
  97707. unTreatedUniforms[unif] = uniformParameter;
  97708. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  97709. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  97710. if (transformIndex !== -1) {
  97711. uniforms.push(babylonTransforms[transformIndex]);
  97712. delete unTreatedUniforms[unif];
  97713. }
  97714. else {
  97715. uniforms.push(unif);
  97716. }
  97717. }
  97718. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  97719. samplers.push(unif);
  97720. }
  97721. else {
  97722. uniforms.push(unif);
  97723. }
  97724. }
  97725. for (var attr in technique.attributes) {
  97726. var attribute = technique.attributes[attr];
  97727. var attributeParameter = technique.parameters[attribute];
  97728. if (attributeParameter.semantic) {
  97729. attributes.push(getAttribute(attributeParameter));
  97730. }
  97731. }
  97732. // Configure vertex shader
  97733. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  97734. var tokenType = vertexTokenizer.currentToken;
  97735. if (tokenType !== ETokenType.IDENTIFIER) {
  97736. newVertexShader += vertexTokenizer.currentString;
  97737. continue;
  97738. }
  97739. var foundAttribute = false;
  97740. for (var attr in technique.attributes) {
  97741. var attribute = technique.attributes[attr];
  97742. var attributeParameter = technique.parameters[attribute];
  97743. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  97744. newVertexShader += getAttribute(attributeParameter);
  97745. foundAttribute = true;
  97746. break;
  97747. }
  97748. }
  97749. if (foundAttribute) {
  97750. continue;
  97751. }
  97752. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  97753. }
  97754. // Configure pixel shader
  97755. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  97756. var tokenType = pixelTokenizer.currentToken;
  97757. if (tokenType !== ETokenType.IDENTIFIER) {
  97758. newPixelShader += pixelTokenizer.currentString;
  97759. continue;
  97760. }
  97761. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  97762. }
  97763. // Create shader material
  97764. var shaderPath = {
  97765. vertex: program.vertexShader + id,
  97766. fragment: program.fragmentShader + id
  97767. };
  97768. var options = {
  97769. attributes: attributes,
  97770. uniforms: uniforms,
  97771. samplers: samplers,
  97772. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  97773. };
  97774. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  97775. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  97776. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  97777. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  97778. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  97779. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  97780. if (states && states.functions) {
  97781. var functions = states.functions;
  97782. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  97783. shaderMaterial.backFaceCulling = false;
  97784. }
  97785. var blendFunc = functions.blendFuncSeparate;
  97786. if (blendFunc) {
  97787. 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) {
  97788. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  97789. }
  97790. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  97791. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  97792. }
  97793. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  97794. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  97795. }
  97796. 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) {
  97797. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  97798. }
  97799. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  97800. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  97801. }
  97802. 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) {
  97803. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  97804. }
  97805. }
  97806. }
  97807. };
  97808. return GLTFLoaderBase;
  97809. }());
  97810. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  97811. /**
  97812. * glTF V1 Loader
  97813. */
  97814. var GLTFLoader = /** @class */ (function () {
  97815. function GLTFLoader() {
  97816. // #region Stubs for IGLTFLoader interface
  97817. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  97818. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  97819. this.compileMaterials = false;
  97820. this.useClipPlane = false;
  97821. this.compileShadowGenerators = false;
  97822. this.onDisposeObservable = new BABYLON.Observable();
  97823. this.onMeshLoadedObservable = new BABYLON.Observable();
  97824. this.onTextureLoadedObservable = new BABYLON.Observable();
  97825. this.onMaterialLoadedObservable = new BABYLON.Observable();
  97826. this.onAnimationGroupLoadedObservable = new BABYLON.Observable();
  97827. this.onCompleteObservable = new BABYLON.Observable();
  97828. this.onExtensionLoadedObservable = new BABYLON.Observable();
  97829. this.state = null;
  97830. }
  97831. GLTFLoader.RegisterExtension = function (extension) {
  97832. if (GLTFLoader.Extensions[extension.name]) {
  97833. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  97834. return;
  97835. }
  97836. GLTFLoader.Extensions[extension.name] = extension;
  97837. };
  97838. GLTFLoader.prototype.dispose = function () { };
  97839. // #endregion
  97840. GLTFLoader.prototype._importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  97841. var _this = this;
  97842. scene.useRightHandedSystem = true;
  97843. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  97844. gltfRuntime.importOnlyMeshes = true;
  97845. if (meshesNames === "") {
  97846. gltfRuntime.importMeshesNames = [];
  97847. }
  97848. else if (typeof meshesNames === "string") {
  97849. gltfRuntime.importMeshesNames = [meshesNames];
  97850. }
  97851. else if (meshesNames && !(meshesNames instanceof Array)) {
  97852. gltfRuntime.importMeshesNames = [meshesNames];
  97853. }
  97854. else {
  97855. gltfRuntime.importMeshesNames = [];
  97856. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  97857. }
  97858. // Create nodes
  97859. _this._createNodes(gltfRuntime);
  97860. var meshes = new Array();
  97861. var skeletons = new Array();
  97862. // Fill arrays of meshes and skeletons
  97863. for (var nde in gltfRuntime.nodes) {
  97864. var node = gltfRuntime.nodes[nde];
  97865. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  97866. meshes.push(node.babylonNode);
  97867. }
  97868. }
  97869. for (var skl in gltfRuntime.skins) {
  97870. var skin = gltfRuntime.skins[skl];
  97871. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  97872. skeletons.push(skin.babylonSkeleton);
  97873. }
  97874. }
  97875. // Load buffers, shaders, materials, etc.
  97876. _this._loadBuffersAsync(gltfRuntime, function () {
  97877. _this._loadShadersAsync(gltfRuntime, function () {
  97878. importMaterials(gltfRuntime);
  97879. postLoad(gltfRuntime);
  97880. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  97881. onSuccess(meshes, [], skeletons);
  97882. }
  97883. });
  97884. }, onProgress);
  97885. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  97886. onSuccess(meshes, [], skeletons);
  97887. }
  97888. }, onError);
  97889. return true;
  97890. };
  97891. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  97892. var _this = this;
  97893. return new Promise(function (resolve, reject) {
  97894. _this._importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  97895. resolve({
  97896. meshes: meshes,
  97897. particleSystems: particleSystems,
  97898. skeletons: skeletons
  97899. });
  97900. }, onProgress, function (message) {
  97901. reject(new Error(message));
  97902. });
  97903. });
  97904. };
  97905. GLTFLoader.prototype._loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  97906. var _this = this;
  97907. scene.useRightHandedSystem = true;
  97908. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  97909. // Load runtime extensios
  97910. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  97911. // Create nodes
  97912. _this._createNodes(gltfRuntime);
  97913. // Load buffers, shaders, materials, etc.
  97914. _this._loadBuffersAsync(gltfRuntime, function () {
  97915. _this._loadShadersAsync(gltfRuntime, function () {
  97916. importMaterials(gltfRuntime);
  97917. postLoad(gltfRuntime);
  97918. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  97919. onSuccess();
  97920. }
  97921. });
  97922. });
  97923. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  97924. onSuccess();
  97925. }
  97926. }, onError);
  97927. }, onError);
  97928. };
  97929. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  97930. var _this = this;
  97931. return new Promise(function (resolve, reject) {
  97932. _this._loadAsync(scene, data, rootUrl, function () {
  97933. resolve();
  97934. }, onProgress, function (message) {
  97935. reject(new Error(message));
  97936. });
  97937. });
  97938. };
  97939. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  97940. var hasShaders = false;
  97941. var processShader = function (sha, shader) {
  97942. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  97943. if (shaderString instanceof ArrayBuffer) {
  97944. return;
  97945. }
  97946. gltfRuntime.loadedShaderCount++;
  97947. if (shaderString) {
  97948. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  97949. }
  97950. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  97951. onload();
  97952. }
  97953. }, function () {
  97954. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  97955. });
  97956. };
  97957. for (var sha in gltfRuntime.shaders) {
  97958. hasShaders = true;
  97959. var shader = gltfRuntime.shaders[sha];
  97960. if (shader) {
  97961. processShader.bind(this, sha, shader)();
  97962. }
  97963. else {
  97964. BABYLON.Tools.Error("No shader named: " + sha);
  97965. }
  97966. }
  97967. if (!hasShaders) {
  97968. onload();
  97969. }
  97970. };
  97971. ;
  97972. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  97973. var hasBuffers = false;
  97974. var processBuffer = function (buf, buffer) {
  97975. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  97976. gltfRuntime.loadedBufferCount++;
  97977. if (bufferView) {
  97978. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  97979. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  97980. }
  97981. gltfRuntime.loadedBufferViews[buf] = bufferView;
  97982. }
  97983. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  97984. onLoad();
  97985. }
  97986. }, function () {
  97987. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  97988. });
  97989. };
  97990. for (var buf in gltfRuntime.buffers) {
  97991. hasBuffers = true;
  97992. var buffer = gltfRuntime.buffers[buf];
  97993. if (buffer) {
  97994. processBuffer.bind(this, buf, buffer)();
  97995. }
  97996. else {
  97997. BABYLON.Tools.Error("No buffer named: " + buf);
  97998. }
  97999. }
  98000. if (!hasBuffers) {
  98001. onLoad();
  98002. }
  98003. };
  98004. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  98005. var currentScene = gltfRuntime.currentScene;
  98006. if (currentScene) {
  98007. // Only one scene even if multiple scenes are defined
  98008. for (var i = 0; i < currentScene.nodes.length; i++) {
  98009. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  98010. }
  98011. }
  98012. else {
  98013. // Load all scenes
  98014. for (var thing in gltfRuntime.scenes) {
  98015. currentScene = gltfRuntime.scenes[thing];
  98016. for (var i = 0; i < currentScene.nodes.length; i++) {
  98017. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  98018. }
  98019. }
  98020. }
  98021. };
  98022. GLTFLoader.Extensions = {};
  98023. return GLTFLoader;
  98024. }());
  98025. GLTF1.GLTFLoader = GLTFLoader;
  98026. ;
  98027. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  98028. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  98029. })(BABYLON || (BABYLON = {}));
  98030. //# sourceMappingURL=babylon.glTFLoader.js.map
  98031. "use strict";
  98032. var BABYLON;
  98033. (function (BABYLON) {
  98034. var GLTF1;
  98035. (function (GLTF1) {
  98036. /**
  98037. * Utils functions for GLTF
  98038. */
  98039. var GLTFUtils = /** @class */ (function () {
  98040. function GLTFUtils() {
  98041. }
  98042. /**
  98043. * Sets the given "parameter" matrix
  98044. * @param scene: the {BABYLON.Scene} object
  98045. * @param source: the source node where to pick the matrix
  98046. * @param parameter: the GLTF technique parameter
  98047. * @param uniformName: the name of the shader's uniform
  98048. * @param shaderMaterial: the shader material
  98049. */
  98050. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  98051. var mat = null;
  98052. if (parameter.semantic === "MODEL") {
  98053. mat = source.getWorldMatrix();
  98054. }
  98055. else if (parameter.semantic === "PROJECTION") {
  98056. mat = scene.getProjectionMatrix();
  98057. }
  98058. else if (parameter.semantic === "VIEW") {
  98059. mat = scene.getViewMatrix();
  98060. }
  98061. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  98062. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  98063. }
  98064. else if (parameter.semantic === "MODELVIEW") {
  98065. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  98066. }
  98067. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  98068. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  98069. }
  98070. else if (parameter.semantic === "MODELINVERSE") {
  98071. mat = source.getWorldMatrix().invert();
  98072. }
  98073. else if (parameter.semantic === "VIEWINVERSE") {
  98074. mat = scene.getViewMatrix().invert();
  98075. }
  98076. else if (parameter.semantic === "PROJECTIONINVERSE") {
  98077. mat = scene.getProjectionMatrix().invert();
  98078. }
  98079. else if (parameter.semantic === "MODELVIEWINVERSE") {
  98080. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  98081. }
  98082. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  98083. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  98084. }
  98085. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  98086. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  98087. }
  98088. else {
  98089. debugger;
  98090. }
  98091. if (mat) {
  98092. switch (parameter.type) {
  98093. case GLTF1.EParameterType.FLOAT_MAT2:
  98094. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  98095. break;
  98096. case GLTF1.EParameterType.FLOAT_MAT3:
  98097. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  98098. break;
  98099. case GLTF1.EParameterType.FLOAT_MAT4:
  98100. shaderMaterial.setMatrix(uniformName, mat);
  98101. break;
  98102. default: break;
  98103. }
  98104. }
  98105. };
  98106. /**
  98107. * Sets the given "parameter" matrix
  98108. * @param shaderMaterial: the shader material
  98109. * @param uniform: the name of the shader's uniform
  98110. * @param value: the value of the uniform
  98111. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  98112. */
  98113. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  98114. switch (type) {
  98115. case GLTF1.EParameterType.FLOAT:
  98116. shaderMaterial.setFloat(uniform, value);
  98117. return true;
  98118. case GLTF1.EParameterType.FLOAT_VEC2:
  98119. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  98120. return true;
  98121. case GLTF1.EParameterType.FLOAT_VEC3:
  98122. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  98123. return true;
  98124. case GLTF1.EParameterType.FLOAT_VEC4:
  98125. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  98126. return true;
  98127. default: return false;
  98128. }
  98129. };
  98130. /**
  98131. * Returns the wrap mode of the texture
  98132. * @param mode: the mode value
  98133. */
  98134. GLTFUtils.GetWrapMode = function (mode) {
  98135. switch (mode) {
  98136. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  98137. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  98138. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  98139. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  98140. }
  98141. };
  98142. /**
  98143. * Returns the byte stride giving an accessor
  98144. * @param accessor: the GLTF accessor objet
  98145. */
  98146. GLTFUtils.GetByteStrideFromType = function (accessor) {
  98147. // Needs this function since "byteStride" isn't requiered in glTF format
  98148. var type = accessor.type;
  98149. switch (type) {
  98150. case "VEC2": return 2;
  98151. case "VEC3": return 3;
  98152. case "VEC4": return 4;
  98153. case "MAT2": return 4;
  98154. case "MAT3": return 9;
  98155. case "MAT4": return 16;
  98156. default: return 1;
  98157. }
  98158. };
  98159. /**
  98160. * Returns the texture filter mode giving a mode value
  98161. * @param mode: the filter mode value
  98162. */
  98163. GLTFUtils.GetTextureFilterMode = function (mode) {
  98164. switch (mode) {
  98165. case GLTF1.ETextureFilterType.LINEAR:
  98166. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  98167. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  98168. case GLTF1.ETextureFilterType.NEAREST:
  98169. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  98170. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  98171. }
  98172. };
  98173. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  98174. var byteOffset = bufferView.byteOffset + byteOffset;
  98175. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  98176. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  98177. throw new Error("Buffer access is out of range");
  98178. }
  98179. var buffer = loadedBufferView.buffer;
  98180. byteOffset += loadedBufferView.byteOffset;
  98181. switch (componentType) {
  98182. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  98183. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  98184. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  98185. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  98186. default: return new Float32Array(buffer, byteOffset, byteLength);
  98187. }
  98188. };
  98189. /**
  98190. * Returns a buffer from its accessor
  98191. * @param gltfRuntime: the GLTF runtime
  98192. * @param accessor: the GLTF accessor
  98193. */
  98194. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  98195. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  98196. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  98197. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  98198. };
  98199. /**
  98200. * Decodes a buffer view into a string
  98201. * @param view: the buffer view
  98202. */
  98203. GLTFUtils.DecodeBufferToText = function (view) {
  98204. var result = "";
  98205. var length = view.byteLength;
  98206. for (var i = 0; i < length; ++i) {
  98207. result += String.fromCharCode(view[i]);
  98208. }
  98209. return result;
  98210. };
  98211. /**
  98212. * Returns the default material of gltf. Related to
  98213. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  98214. * @param scene: the Babylon.js scene
  98215. */
  98216. GLTFUtils.GetDefaultMaterial = function (scene) {
  98217. if (!GLTFUtils._DefaultMaterial) {
  98218. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  98219. "precision highp float;",
  98220. "",
  98221. "uniform mat4 worldView;",
  98222. "uniform mat4 projection;",
  98223. "",
  98224. "attribute vec3 position;",
  98225. "",
  98226. "void main(void)",
  98227. "{",
  98228. " gl_Position = projection * worldView * vec4(position, 1.0);",
  98229. "}"
  98230. ].join("\n");
  98231. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  98232. "precision highp float;",
  98233. "",
  98234. "uniform vec4 u_emission;",
  98235. "",
  98236. "void main(void)",
  98237. "{",
  98238. " gl_FragColor = u_emission;",
  98239. "}"
  98240. ].join("\n");
  98241. var shaderPath = {
  98242. vertex: "GLTFDefaultMaterial",
  98243. fragment: "GLTFDefaultMaterial"
  98244. };
  98245. var options = {
  98246. attributes: ["position"],
  98247. uniforms: ["worldView", "projection", "u_emission"],
  98248. samplers: new Array(),
  98249. needAlphaBlending: false
  98250. };
  98251. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  98252. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  98253. }
  98254. return GLTFUtils._DefaultMaterial;
  98255. };
  98256. // The GLTF default material
  98257. GLTFUtils._DefaultMaterial = null;
  98258. return GLTFUtils;
  98259. }());
  98260. GLTF1.GLTFUtils = GLTFUtils;
  98261. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  98262. })(BABYLON || (BABYLON = {}));
  98263. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  98264. "use strict";
  98265. var BABYLON;
  98266. (function (BABYLON) {
  98267. var GLTF1;
  98268. (function (GLTF1) {
  98269. var GLTFLoaderExtension = /** @class */ (function () {
  98270. function GLTFLoaderExtension(name) {
  98271. this._name = name;
  98272. }
  98273. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  98274. get: function () {
  98275. return this._name;
  98276. },
  98277. enumerable: true,
  98278. configurable: true
  98279. });
  98280. /**
  98281. * Defines an override for loading the runtime
  98282. * Return true to stop further extensions from loading the runtime
  98283. */
  98284. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  98285. return false;
  98286. };
  98287. /**
  98288. * Defines an onverride for creating gltf runtime
  98289. * Return true to stop further extensions from creating the runtime
  98290. */
  98291. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  98292. return false;
  98293. };
  98294. /**
  98295. * Defines an override for loading buffers
  98296. * Return true to stop further extensions from loading this buffer
  98297. */
  98298. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  98299. return false;
  98300. };
  98301. /**
  98302. * Defines an override for loading texture buffers
  98303. * Return true to stop further extensions from loading this texture data
  98304. */
  98305. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  98306. return false;
  98307. };
  98308. /**
  98309. * Defines an override for creating textures
  98310. * Return true to stop further extensions from loading this texture
  98311. */
  98312. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  98313. return false;
  98314. };
  98315. /**
  98316. * Defines an override for loading shader strings
  98317. * Return true to stop further extensions from loading this shader data
  98318. */
  98319. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  98320. return false;
  98321. };
  98322. /**
  98323. * Defines an override for loading materials
  98324. * Return true to stop further extensions from loading this material
  98325. */
  98326. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  98327. return false;
  98328. };
  98329. // ---------
  98330. // Utilities
  98331. // ---------
  98332. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  98333. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  98334. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  98335. }, function () {
  98336. setTimeout(function () {
  98337. if (!onSuccess) {
  98338. return;
  98339. }
  98340. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  98341. });
  98342. });
  98343. };
  98344. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  98345. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  98346. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  98347. }, function () {
  98348. setTimeout(function () {
  98349. onSuccess();
  98350. });
  98351. });
  98352. };
  98353. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  98354. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  98355. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  98356. }, function () {
  98357. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  98358. });
  98359. };
  98360. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  98361. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  98362. if (buffer) {
  98363. GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  98364. }
  98365. }, onError);
  98366. };
  98367. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  98368. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  98369. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  98370. }, function () {
  98371. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  98372. });
  98373. };
  98374. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  98375. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  98376. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  98377. }, function () {
  98378. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  98379. });
  98380. };
  98381. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  98382. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  98383. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  98384. }, function () {
  98385. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  98386. });
  98387. };
  98388. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  98389. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  98390. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  98391. }, function () {
  98392. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  98393. });
  98394. };
  98395. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  98396. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  98397. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  98398. if (func(loaderExtension)) {
  98399. return;
  98400. }
  98401. }
  98402. defaultFunc();
  98403. };
  98404. return GLTFLoaderExtension;
  98405. }());
  98406. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  98407. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  98408. })(BABYLON || (BABYLON = {}));
  98409. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  98410. "use strict";
  98411. var BABYLON;
  98412. (function (BABYLON) {
  98413. var GLTF1;
  98414. (function (GLTF1) {
  98415. var BinaryExtensionBufferName = "binary_glTF";
  98416. ;
  98417. ;
  98418. var GLTFBinaryExtension = /** @class */ (function (_super) {
  98419. __extends(GLTFBinaryExtension, _super);
  98420. function GLTFBinaryExtension() {
  98421. return _super.call(this, "KHR_binary_glTF") || this;
  98422. }
  98423. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  98424. var extensionsUsed = data.json.extensionsUsed;
  98425. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  98426. return false;
  98427. }
  98428. this._bin = data.bin;
  98429. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  98430. return true;
  98431. };
  98432. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  98433. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  98434. return false;
  98435. }
  98436. if (id !== BinaryExtensionBufferName) {
  98437. return false;
  98438. }
  98439. onSuccess(this._bin);
  98440. return true;
  98441. };
  98442. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  98443. var texture = gltfRuntime.textures[id];
  98444. var source = gltfRuntime.images[texture.source];
  98445. if (!source.extensions || !(this.name in source.extensions)) {
  98446. return false;
  98447. }
  98448. var sourceExt = source.extensions[this.name];
  98449. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  98450. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  98451. onSuccess(buffer);
  98452. return true;
  98453. };
  98454. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  98455. var shader = gltfRuntime.shaders[id];
  98456. if (!shader.extensions || !(this.name in shader.extensions)) {
  98457. return false;
  98458. }
  98459. var binaryExtensionShader = shader.extensions[this.name];
  98460. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  98461. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  98462. setTimeout(function () {
  98463. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  98464. onSuccess(shaderString);
  98465. });
  98466. return true;
  98467. };
  98468. return GLTFBinaryExtension;
  98469. }(GLTF1.GLTFLoaderExtension));
  98470. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  98471. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  98472. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  98473. })(BABYLON || (BABYLON = {}));
  98474. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  98475. "use strict";
  98476. var BABYLON;
  98477. (function (BABYLON) {
  98478. var GLTF1;
  98479. (function (GLTF1) {
  98480. ;
  98481. ;
  98482. ;
  98483. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  98484. __extends(GLTFMaterialsCommonExtension, _super);
  98485. function GLTFMaterialsCommonExtension() {
  98486. return _super.call(this, "KHR_materials_common") || this;
  98487. }
  98488. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  98489. if (!gltfRuntime.extensions)
  98490. return false;
  98491. var extension = gltfRuntime.extensions[this.name];
  98492. if (!extension)
  98493. return false;
  98494. // Create lights
  98495. var lights = extension.lights;
  98496. if (lights) {
  98497. for (var thing in lights) {
  98498. var light = lights[thing];
  98499. switch (light.type) {
  98500. case "ambient":
  98501. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  98502. var ambient = light.ambient;
  98503. if (ambient) {
  98504. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  98505. }
  98506. break;
  98507. case "point":
  98508. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  98509. var point = light.point;
  98510. if (point) {
  98511. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  98512. }
  98513. break;
  98514. case "directional":
  98515. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  98516. var directional = light.directional;
  98517. if (directional) {
  98518. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  98519. }
  98520. break;
  98521. case "spot":
  98522. var spot = light.spot;
  98523. if (spot) {
  98524. 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);
  98525. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  98526. }
  98527. break;
  98528. default:
  98529. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  98530. break;
  98531. }
  98532. }
  98533. }
  98534. return false;
  98535. };
  98536. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  98537. var material = gltfRuntime.materials[id];
  98538. if (!material || !material.extensions)
  98539. return false;
  98540. var extension = material.extensions[this.name];
  98541. if (!extension)
  98542. return false;
  98543. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  98544. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  98545. if (extension.technique === "CONSTANT") {
  98546. standardMaterial.disableLighting = true;
  98547. }
  98548. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  98549. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  98550. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  98551. // Ambient
  98552. if (typeof extension.values.ambient === "string") {
  98553. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  98554. }
  98555. else {
  98556. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  98557. }
  98558. // Diffuse
  98559. if (typeof extension.values.diffuse === "string") {
  98560. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  98561. }
  98562. else {
  98563. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  98564. }
  98565. // Emission
  98566. if (typeof extension.values.emission === "string") {
  98567. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  98568. }
  98569. else {
  98570. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  98571. }
  98572. // Specular
  98573. if (typeof extension.values.specular === "string") {
  98574. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  98575. }
  98576. else {
  98577. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  98578. }
  98579. return true;
  98580. };
  98581. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  98582. // Create buffer from texture url
  98583. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  98584. // Create texture from buffer
  98585. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  98586. }, onError);
  98587. };
  98588. return GLTFMaterialsCommonExtension;
  98589. }(GLTF1.GLTFLoaderExtension));
  98590. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  98591. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  98592. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  98593. })(BABYLON || (BABYLON = {}));
  98594. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  98595. "use strict";
  98596. var BABYLON;
  98597. (function (BABYLON) {
  98598. var GLTF2;
  98599. (function (GLTF2) {
  98600. var ArrayItem = /** @class */ (function () {
  98601. function ArrayItem() {
  98602. }
  98603. ArrayItem.Assign = function (values) {
  98604. if (values) {
  98605. for (var index = 0; index < values.length; index++) {
  98606. values[index]._index = index;
  98607. }
  98608. }
  98609. };
  98610. return ArrayItem;
  98611. }());
  98612. GLTF2.ArrayItem = ArrayItem;
  98613. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  98614. })(BABYLON || (BABYLON = {}));
  98615. //# sourceMappingURL=babylon.glTFLoaderUtilities.js.map
  98616. "use strict";
  98617. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  98618. "use strict";
  98619. var BABYLON;
  98620. (function (BABYLON) {
  98621. var GLTF2;
  98622. (function (GLTF2) {
  98623. var GLTFLoader = /** @class */ (function () {
  98624. function GLTFLoader() {
  98625. this._completePromises = new Array();
  98626. this._disposed = false;
  98627. this._state = null;
  98628. this._extensions = {};
  98629. this._defaultSampler = {};
  98630. this._defaultBabylonMaterials = {};
  98631. this._requests = new Array();
  98632. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  98633. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  98634. this.compileMaterials = false;
  98635. this.useClipPlane = false;
  98636. this.compileShadowGenerators = false;
  98637. this.onDisposeObservable = new BABYLON.Observable();
  98638. this.onMeshLoadedObservable = new BABYLON.Observable();
  98639. this.onTextureLoadedObservable = new BABYLON.Observable();
  98640. this.onMaterialLoadedObservable = new BABYLON.Observable();
  98641. this.onAnimationGroupLoadedObservable = new BABYLON.Observable();
  98642. this.onExtensionLoadedObservable = new BABYLON.Observable();
  98643. this.onCompleteObservable = new BABYLON.Observable();
  98644. }
  98645. GLTFLoader._Register = function (name, factory) {
  98646. if (GLTFLoader._Factories[name]) {
  98647. BABYLON.Tools.Error("Extension with the name '" + name + "' already exists");
  98648. return;
  98649. }
  98650. GLTFLoader._Factories[name] = factory;
  98651. // Keep the order of registration so that extensions registered first are called first.
  98652. GLTFLoader._Names.push(name);
  98653. };
  98654. Object.defineProperty(GLTFLoader.prototype, "state", {
  98655. get: function () {
  98656. return this._state;
  98657. },
  98658. enumerable: true,
  98659. configurable: true
  98660. });
  98661. GLTFLoader.prototype.dispose = function () {
  98662. if (this._disposed) {
  98663. return;
  98664. }
  98665. this._disposed = true;
  98666. this.onDisposeObservable.notifyObservers(this);
  98667. this.onDisposeObservable.clear();
  98668. this._clear();
  98669. };
  98670. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  98671. var _this = this;
  98672. return Promise.resolve().then(function () {
  98673. var nodes = null;
  98674. if (meshesNames) {
  98675. var nodeMap_1 = {};
  98676. if (_this._gltf.nodes) {
  98677. for (var _i = 0, _a = _this._gltf.nodes; _i < _a.length; _i++) {
  98678. var node = _a[_i];
  98679. if (node.name) {
  98680. nodeMap_1[node.name] = node;
  98681. }
  98682. }
  98683. }
  98684. var names = (meshesNames instanceof Array) ? meshesNames : [meshesNames];
  98685. nodes = names.map(function (name) {
  98686. var node = nodeMap_1[name];
  98687. if (!node) {
  98688. throw new Error("Failed to find node '" + name + "'");
  98689. }
  98690. return node;
  98691. });
  98692. }
  98693. return _this._loadAsync(nodes, scene, data, rootUrl, onProgress).then(function () {
  98694. return {
  98695. meshes: _this._getMeshes(),
  98696. particleSystems: [],
  98697. skeletons: _this._getSkeletons(),
  98698. };
  98699. });
  98700. });
  98701. };
  98702. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  98703. return this._loadAsync(null, scene, data, rootUrl, onProgress);
  98704. };
  98705. GLTFLoader.prototype._loadAsync = function (nodes, scene, data, rootUrl, onProgress) {
  98706. var _this = this;
  98707. return Promise.resolve().then(function () {
  98708. _this._loadExtensions();
  98709. _this._babylonScene = scene;
  98710. _this._rootUrl = rootUrl;
  98711. _this._progressCallback = onProgress;
  98712. _this._state = BABYLON.GLTFLoaderState.Loading;
  98713. _this._loadData(data);
  98714. _this._checkExtensions();
  98715. var promises = new Array();
  98716. if (nodes) {
  98717. promises.push(_this._loadNodesAsync(nodes));
  98718. }
  98719. else {
  98720. var scene_1 = GLTFLoader._GetProperty("#/scene", _this._gltf.scenes, _this._gltf.scene || 0);
  98721. promises.push(_this._loadSceneAsync("#/scenes/" + scene_1._index, scene_1));
  98722. }
  98723. if (_this.compileMaterials) {
  98724. promises.push(_this._compileMaterialsAsync());
  98725. }
  98726. if (_this.compileShadowGenerators) {
  98727. promises.push(_this._compileShadowGeneratorsAsync());
  98728. }
  98729. var resultPromise = Promise.all(promises).then(function () {
  98730. _this._state = BABYLON.GLTFLoaderState.Ready;
  98731. _this._startAnimations();
  98732. });
  98733. resultPromise.then(function () {
  98734. _this._rootBabylonMesh.setEnabled(true);
  98735. BABYLON.Tools.SetImmediate(function () {
  98736. if (!_this._disposed) {
  98737. Promise.all(_this._completePromises).then(function () {
  98738. _this._state = BABYLON.GLTFLoaderState.Complete;
  98739. _this.onCompleteObservable.notifyObservers(_this);
  98740. _this.onCompleteObservable.clear();
  98741. _this._clear();
  98742. }).catch(function (error) {
  98743. BABYLON.Tools.Error("glTF Loader: " + error.message);
  98744. _this._clear();
  98745. });
  98746. }
  98747. });
  98748. });
  98749. return resultPromise;
  98750. }).catch(function (error) {
  98751. BABYLON.Tools.Error("glTF Loader: " + error.message);
  98752. _this._clear();
  98753. throw error;
  98754. });
  98755. };
  98756. GLTFLoader.prototype._loadExtensions = function () {
  98757. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  98758. var name_1 = _a[_i];
  98759. var extension = GLTFLoader._Factories[name_1](this);
  98760. this._extensions[name_1] = extension;
  98761. this.onExtensionLoadedObservable.notifyObservers(extension);
  98762. }
  98763. this.onExtensionLoadedObservable.clear();
  98764. };
  98765. GLTFLoader.prototype._loadData = function (data) {
  98766. this._gltf = data.json;
  98767. this._setupData();
  98768. if (data.bin) {
  98769. var buffers = this._gltf.buffers;
  98770. if (buffers && buffers[0] && !buffers[0].uri) {
  98771. var binaryBuffer = buffers[0];
  98772. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  98773. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  98774. }
  98775. binaryBuffer._data = Promise.resolve(data.bin);
  98776. }
  98777. else {
  98778. BABYLON.Tools.Warn("Unexpected BIN chunk");
  98779. }
  98780. }
  98781. };
  98782. GLTFLoader.prototype._setupData = function () {
  98783. GLTF2.ArrayItem.Assign(this._gltf.accessors);
  98784. GLTF2.ArrayItem.Assign(this._gltf.animations);
  98785. GLTF2.ArrayItem.Assign(this._gltf.buffers);
  98786. GLTF2.ArrayItem.Assign(this._gltf.bufferViews);
  98787. GLTF2.ArrayItem.Assign(this._gltf.cameras);
  98788. GLTF2.ArrayItem.Assign(this._gltf.images);
  98789. GLTF2.ArrayItem.Assign(this._gltf.materials);
  98790. GLTF2.ArrayItem.Assign(this._gltf.meshes);
  98791. GLTF2.ArrayItem.Assign(this._gltf.nodes);
  98792. GLTF2.ArrayItem.Assign(this._gltf.samplers);
  98793. GLTF2.ArrayItem.Assign(this._gltf.scenes);
  98794. GLTF2.ArrayItem.Assign(this._gltf.skins);
  98795. GLTF2.ArrayItem.Assign(this._gltf.textures);
  98796. if (this._gltf.nodes) {
  98797. var nodeParents = {};
  98798. for (var _i = 0, _a = this._gltf.nodes; _i < _a.length; _i++) {
  98799. var node = _a[_i];
  98800. if (node.children) {
  98801. for (var _b = 0, _c = node.children; _b < _c.length; _b++) {
  98802. var index = _c[_b];
  98803. nodeParents[index] = node._index;
  98804. }
  98805. }
  98806. }
  98807. var rootNode = this._createRootNode();
  98808. for (var _d = 0, _e = this._gltf.nodes; _d < _e.length; _d++) {
  98809. var node = _e[_d];
  98810. var parentIndex = nodeParents[node._index];
  98811. node._parent = parentIndex === undefined ? rootNode : this._gltf.nodes[parentIndex];
  98812. }
  98813. }
  98814. };
  98815. GLTFLoader.prototype._checkExtensions = function () {
  98816. if (this._gltf.extensionsRequired) {
  98817. for (var _i = 0, _a = this._gltf.extensionsRequired; _i < _a.length; _i++) {
  98818. var name_2 = _a[_i];
  98819. var extension = this._extensions[name_2];
  98820. if (!extension || !extension.enabled) {
  98821. throw new Error("Require extension " + name_2 + " is not available");
  98822. }
  98823. }
  98824. }
  98825. };
  98826. GLTFLoader.prototype._createRootNode = function () {
  98827. this._rootBabylonMesh = new BABYLON.Mesh("__root__", this._babylonScene);
  98828. this._rootBabylonMesh.setEnabled(false);
  98829. var rootNode = { _babylonMesh: this._rootBabylonMesh };
  98830. switch (this.coordinateSystemMode) {
  98831. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  98832. if (!this._babylonScene.useRightHandedSystem) {
  98833. rootNode.rotation = [0, 1, 0, 0];
  98834. rootNode.scale = [1, 1, -1];
  98835. GLTFLoader._LoadTransform(rootNode, this._rootBabylonMesh);
  98836. }
  98837. break;
  98838. }
  98839. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  98840. this._babylonScene.useRightHandedSystem = true;
  98841. break;
  98842. }
  98843. default: {
  98844. throw new Error("Invalid coordinate system mode (" + this.coordinateSystemMode + ")");
  98845. }
  98846. }
  98847. this.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh);
  98848. return rootNode;
  98849. };
  98850. GLTFLoader.prototype._loadNodesAsync = function (nodes) {
  98851. var promises = new Array();
  98852. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  98853. var node = nodes_1[_i];
  98854. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  98855. }
  98856. promises.push(this._loadAnimationsAsync());
  98857. return Promise.all(promises).then(function () { });
  98858. };
  98859. GLTFLoader.prototype._loadSceneAsync = function (context, scene) {
  98860. var promise = GLTF2.GLTFLoaderExtension._LoadSceneAsync(this, context, scene);
  98861. if (promise) {
  98862. return promise;
  98863. }
  98864. var promises = new Array();
  98865. for (var _i = 0, _a = scene.nodes; _i < _a.length; _i++) {
  98866. var index = _a[_i];
  98867. var node = GLTFLoader._GetProperty(context + "/nodes/" + index, this._gltf.nodes, index);
  98868. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  98869. }
  98870. promises.push(this._loadAnimationsAsync());
  98871. return Promise.all(promises).then(function () { });
  98872. };
  98873. GLTFLoader.prototype._forEachPrimitive = function (node, callback) {
  98874. if (node._primitiveBabylonMeshes) {
  98875. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  98876. var babylonMesh = _a[_i];
  98877. callback(babylonMesh);
  98878. }
  98879. }
  98880. else {
  98881. callback(node._babylonMesh);
  98882. }
  98883. };
  98884. GLTFLoader.prototype._getMeshes = function () {
  98885. var meshes = new Array();
  98886. // Root mesh is always first.
  98887. meshes.push(this._rootBabylonMesh);
  98888. var nodes = this._gltf.nodes;
  98889. if (nodes) {
  98890. for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) {
  98891. var node = nodes_2[_i];
  98892. if (node._babylonMesh) {
  98893. meshes.push(node._babylonMesh);
  98894. }
  98895. if (node._primitiveBabylonMeshes) {
  98896. for (var _a = 0, _b = node._primitiveBabylonMeshes; _a < _b.length; _a++) {
  98897. var babylonMesh = _b[_a];
  98898. meshes.push(babylonMesh);
  98899. }
  98900. }
  98901. }
  98902. }
  98903. return meshes;
  98904. };
  98905. GLTFLoader.prototype._getSkeletons = function () {
  98906. var skeletons = new Array();
  98907. var skins = this._gltf.skins;
  98908. if (skins) {
  98909. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  98910. var skin = skins_1[_i];
  98911. if (skin._babylonSkeleton) {
  98912. skeletons.push(skin._babylonSkeleton);
  98913. }
  98914. }
  98915. }
  98916. return skeletons;
  98917. };
  98918. GLTFLoader.prototype._startAnimations = function () {
  98919. var animations = this._gltf.animations;
  98920. if (!animations) {
  98921. return;
  98922. }
  98923. switch (this.animationStartMode) {
  98924. case BABYLON.GLTFLoaderAnimationStartMode.NONE: {
  98925. // do nothing
  98926. break;
  98927. }
  98928. case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {
  98929. var animation = animations[0];
  98930. animation._babylonAnimationGroup.start(true);
  98931. break;
  98932. }
  98933. case BABYLON.GLTFLoaderAnimationStartMode.ALL: {
  98934. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  98935. var animation = animations_1[_i];
  98936. animation._babylonAnimationGroup.start(true);
  98937. }
  98938. break;
  98939. }
  98940. default: {
  98941. BABYLON.Tools.Error("Invalid animation start mode (" + this.animationStartMode + ")");
  98942. return;
  98943. }
  98944. }
  98945. };
  98946. GLTFLoader.prototype._loadNodeAsync = function (context, node) {
  98947. var promise = GLTF2.GLTFLoaderExtension._LoadNodeAsync(this, context, node);
  98948. if (promise) {
  98949. return promise;
  98950. }
  98951. if (node._babylonMesh) {
  98952. throw new Error(context + ": Invalid recursive node hierarchy");
  98953. }
  98954. var promises = new Array();
  98955. var babylonMesh = new BABYLON.Mesh(node.name || "node" + node._index, this._babylonScene, node._parent._babylonMesh);
  98956. node._babylonMesh = babylonMesh;
  98957. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  98958. node._babylonAnimationTargets.push(babylonMesh);
  98959. GLTFLoader._LoadTransform(node, babylonMesh);
  98960. if (node.mesh != undefined) {
  98961. var mesh = GLTFLoader._GetProperty(context + "/mesh", this._gltf.meshes, node.mesh);
  98962. promises.push(this._loadMeshAsync("#/meshes/" + mesh._index, node, mesh, babylonMesh));
  98963. }
  98964. if (node.children) {
  98965. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  98966. var index = _a[_i];
  98967. var childNode = GLTFLoader._GetProperty(context + "/children/" + index, this._gltf.nodes, index);
  98968. promises.push(this._loadNodeAsync("#/nodes/" + index, childNode));
  98969. }
  98970. }
  98971. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  98972. return Promise.all(promises).then(function () { });
  98973. };
  98974. GLTFLoader.prototype._loadMeshAsync = function (context, node, mesh, babylonMesh) {
  98975. // TODO: instancing
  98976. var _this = this;
  98977. var promises = new Array();
  98978. var primitives = mesh.primitives;
  98979. if (!primitives || primitives.length === 0) {
  98980. throw new Error(context + ": Primitives are missing");
  98981. }
  98982. GLTF2.ArrayItem.Assign(primitives);
  98983. if (primitives.length === 1) {
  98984. var primitive = primitives[0];
  98985. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, babylonMesh));
  98986. }
  98987. else {
  98988. node._primitiveBabylonMeshes = [];
  98989. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  98990. var primitive = primitives_1[_i];
  98991. var primitiveBabylonMesh = new BABYLON.Mesh((mesh.name || babylonMesh.name) + "_" + primitive._index, this._babylonScene, babylonMesh);
  98992. node._primitiveBabylonMeshes.push(primitiveBabylonMesh);
  98993. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, primitiveBabylonMesh));
  98994. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  98995. }
  98996. }
  98997. if (node.skin != undefined) {
  98998. var skin = GLTFLoader._GetProperty(context + "/skin", this._gltf.skins, node.skin);
  98999. promises.push(this._loadSkinAsync("#/skins/" + skin._index, node, mesh, skin));
  99000. }
  99001. return Promise.all(promises).then(function () {
  99002. _this._forEachPrimitive(node, function (babylonMesh) {
  99003. babylonMesh._refreshBoundingInfo(true);
  99004. });
  99005. });
  99006. };
  99007. GLTFLoader.prototype._loadPrimitiveAsync = function (context, node, mesh, primitive, babylonMesh) {
  99008. var _this = this;
  99009. var promises = new Array();
  99010. this._createMorphTargets(context, node, mesh, primitive, babylonMesh);
  99011. promises.push(this._loadVertexDataAsync(context, primitive, babylonMesh).then(function (babylonVertexData) {
  99012. new BABYLON.Geometry(babylonMesh.name, _this._babylonScene, babylonVertexData, false, babylonMesh);
  99013. return _this._loadMorphTargetsAsync(context, primitive, babylonMesh, babylonVertexData);
  99014. }));
  99015. var babylonDrawMode = GLTFLoader._GetDrawMode(context, primitive.mode);
  99016. if (primitive.material == undefined) {
  99017. babylonMesh.material = this._getDefaultMaterial(babylonDrawMode);
  99018. }
  99019. else {
  99020. var material = GLTFLoader._GetProperty(context + "/material}", this._gltf.materials, primitive.material);
  99021. promises.push(this._loadMaterialAsync("#/materials/" + material._index, material, babylonMesh, babylonDrawMode, function (babylonMaterial) {
  99022. babylonMesh.material = babylonMaterial;
  99023. }));
  99024. }
  99025. return Promise.all(promises).then(function () { });
  99026. };
  99027. GLTFLoader.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  99028. var _this = this;
  99029. var promise = GLTF2.GLTFLoaderExtension._LoadVertexDataAsync(this, context, primitive, babylonMesh);
  99030. if (promise) {
  99031. return promise;
  99032. }
  99033. var attributes = primitive.attributes;
  99034. if (!attributes) {
  99035. throw new Error(context + ": Attributes are missing");
  99036. }
  99037. var promises = new Array();
  99038. var babylonVertexData = new BABYLON.VertexData();
  99039. if (primitive.indices == undefined) {
  99040. var positionAccessorIndex = attributes["POSITION"];
  99041. if (positionAccessorIndex != undefined) {
  99042. var accessor = GLTFLoader._GetProperty(context + "/attributes/POSITION", this._gltf.accessors, positionAccessorIndex);
  99043. babylonVertexData.indices = new Uint32Array(accessor.count);
  99044. for (var i = 0; i < babylonVertexData.indices.length; i++) {
  99045. babylonVertexData.indices[i] = i;
  99046. }
  99047. }
  99048. }
  99049. else {
  99050. var indicesAccessor = GLTFLoader._GetProperty(context + "/indices", this._gltf.accessors, primitive.indices);
  99051. promises.push(this._loadAccessorAsync("#/accessors/" + indicesAccessor._index, indicesAccessor).then(function (data) {
  99052. babylonVertexData.indices = data;
  99053. }));
  99054. }
  99055. var loadAttribute = function (attribute, kind) {
  99056. if (attributes[attribute] == undefined) {
  99057. return;
  99058. }
  99059. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  99060. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  99061. babylonMesh._delayInfo.push(kind);
  99062. }
  99063. if (attribute === "COLOR_0") {
  99064. // Assume vertex color has alpha on the mesh. The alphaMode of the material controls whether the material should use alpha or not.
  99065. babylonMesh.hasVertexAlpha = true;
  99066. }
  99067. var accessor = GLTFLoader._GetProperty(context + "/attributes/" + attribute, _this._gltf.accessors, attributes[attribute]);
  99068. promises.push(_this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  99069. var attributeData = GLTFLoader._ConvertToFloat32Array(context, accessor, data);
  99070. if (attribute === "COLOR_0" && accessor.type === "VEC3") {
  99071. attributeData = GLTFLoader._ConvertVec3ToVec4(context, attributeData);
  99072. }
  99073. babylonVertexData.set(attributeData, kind);
  99074. }));
  99075. };
  99076. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  99077. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  99078. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  99079. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  99080. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  99081. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  99082. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  99083. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  99084. return Promise.all(promises).then(function () {
  99085. return babylonVertexData;
  99086. });
  99087. };
  99088. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh, primitive, babylonMesh) {
  99089. if (!primitive.targets) {
  99090. return;
  99091. }
  99092. if (node._numMorphTargets == undefined) {
  99093. node._numMorphTargets = primitive.targets.length;
  99094. }
  99095. else if (primitive.targets.length !== node._numMorphTargets) {
  99096. throw new Error(context + ": Primitives do not have the same number of targets");
  99097. }
  99098. babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  99099. for (var index = 0; index < primitive.targets.length; index++) {
  99100. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  99101. babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  99102. // TODO: tell the target whether it has positions, normals, tangents
  99103. }
  99104. };
  99105. GLTFLoader.prototype._loadMorphTargetsAsync = function (context, primitive, babylonMesh, babylonVertexData) {
  99106. if (!primitive.targets) {
  99107. return Promise.resolve();
  99108. }
  99109. var promises = new Array();
  99110. var morphTargetManager = babylonMesh.morphTargetManager;
  99111. for (var index = 0; index < morphTargetManager.numTargets; index++) {
  99112. var babylonMorphTarget = morphTargetManager.getTarget(index);
  99113. promises.push(this._loadMorphTargetVertexDataAsync(context + "/targets/" + index, babylonVertexData, primitive.targets[index], babylonMorphTarget));
  99114. }
  99115. return Promise.all(promises).then(function () { });
  99116. };
  99117. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, babylonVertexData, attributes, babylonMorphTarget) {
  99118. var _this = this;
  99119. var promises = new Array();
  99120. var loadAttribute = function (attribute, setData) {
  99121. if (attributes[attribute] == undefined) {
  99122. return;
  99123. }
  99124. var accessor = GLTFLoader._GetProperty(context + "/" + attribute, _this._gltf.accessors, attributes[attribute]);
  99125. promises.push(_this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  99126. setData(data);
  99127. }));
  99128. };
  99129. loadAttribute("POSITION", function (data) {
  99130. if (babylonVertexData.positions) {
  99131. for (var i = 0; i < data.length; i++) {
  99132. data[i] += babylonVertexData.positions[i];
  99133. }
  99134. babylonMorphTarget.setPositions(data);
  99135. }
  99136. });
  99137. loadAttribute("NORMAL", function (data) {
  99138. if (babylonVertexData.normals) {
  99139. for (var i = 0; i < data.length; i++) {
  99140. data[i] += babylonVertexData.normals[i];
  99141. }
  99142. babylonMorphTarget.setNormals(data);
  99143. }
  99144. });
  99145. loadAttribute("TANGENT", function (data) {
  99146. if (babylonVertexData.tangents) {
  99147. // Tangent data for morph targets is stored as xyz delta.
  99148. // The vertexData.tangent is stored as xyzw.
  99149. // So we need to skip every fourth vertexData.tangent.
  99150. for (var i = 0, j = 0; i < data.length; i++) {
  99151. data[i] += babylonVertexData.tangents[j++];
  99152. if ((i + 1) % 3 == 0) {
  99153. j++;
  99154. }
  99155. }
  99156. babylonMorphTarget.setTangents(data);
  99157. }
  99158. });
  99159. return Promise.all(promises).then(function () { });
  99160. };
  99161. GLTFLoader._ConvertToFloat32Array = function (context, accessor, data) {
  99162. if (accessor.componentType == 5126 /* FLOAT */) {
  99163. return data;
  99164. }
  99165. var factor = 1;
  99166. if (accessor.normalized) {
  99167. switch (accessor.componentType) {
  99168. case 5121 /* UNSIGNED_BYTE */: {
  99169. factor = 1 / 255;
  99170. break;
  99171. }
  99172. case 5123 /* UNSIGNED_SHORT */: {
  99173. factor = 1 / 65535;
  99174. break;
  99175. }
  99176. default: {
  99177. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  99178. }
  99179. }
  99180. }
  99181. var result = new Float32Array(accessor.count * GLTFLoader._GetNumComponents(context, accessor.type));
  99182. for (var i = 0; i < result.length; i++) {
  99183. result[i] = data[i] * factor;
  99184. }
  99185. return result;
  99186. };
  99187. GLTFLoader._ConvertVec3ToVec4 = function (context, data) {
  99188. var result = new Float32Array(data.length / 3 * 4);
  99189. var offset = 0;
  99190. for (var i = 0; i < result.length; i++) {
  99191. if ((i + 1) % 4 === 0) {
  99192. result[i] = 1;
  99193. }
  99194. else {
  99195. result[i] = data[offset++];
  99196. }
  99197. }
  99198. return result;
  99199. };
  99200. GLTFLoader._LoadTransform = function (node, babylonNode) {
  99201. var position = BABYLON.Vector3.Zero();
  99202. var rotation = BABYLON.Quaternion.Identity();
  99203. var scaling = BABYLON.Vector3.One();
  99204. if (node.matrix) {
  99205. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  99206. matrix.decompose(scaling, rotation, position);
  99207. }
  99208. else {
  99209. if (node.translation)
  99210. position = BABYLON.Vector3.FromArray(node.translation);
  99211. if (node.rotation)
  99212. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  99213. if (node.scale)
  99214. scaling = BABYLON.Vector3.FromArray(node.scale);
  99215. }
  99216. babylonNode.position = position;
  99217. babylonNode.rotationQuaternion = rotation;
  99218. babylonNode.scaling = scaling;
  99219. };
  99220. GLTFLoader.prototype._loadSkinAsync = function (context, node, mesh, skin) {
  99221. var _this = this;
  99222. var assignSkeleton = function () {
  99223. _this._forEachPrimitive(node, function (babylonMesh) {
  99224. babylonMesh.skeleton = skin._babylonSkeleton;
  99225. });
  99226. node._babylonMesh.parent = _this._rootBabylonMesh;
  99227. node._babylonMesh.position = BABYLON.Vector3.Zero();
  99228. node._babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  99229. node._babylonMesh.scaling = BABYLON.Vector3.One();
  99230. };
  99231. if (skin._loaded) {
  99232. return skin._loaded.then(function () {
  99233. assignSkeleton();
  99234. });
  99235. }
  99236. // TODO: split into two parts so that bones are created before inverseBindMatricesData is loaded (for compiling materials).
  99237. return (skin._loaded = this._loadSkinInverseBindMatricesDataAsync(context, skin).then(function (inverseBindMatricesData) {
  99238. var skeletonId = "skeleton" + skin._index;
  99239. var babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, _this._babylonScene);
  99240. skin._babylonSkeleton = babylonSkeleton;
  99241. _this._loadBones(context, skin, inverseBindMatricesData);
  99242. assignSkeleton();
  99243. }));
  99244. };
  99245. GLTFLoader.prototype._loadSkinInverseBindMatricesDataAsync = function (context, skin) {
  99246. if (skin.inverseBindMatrices == undefined) {
  99247. return Promise.resolve(null);
  99248. }
  99249. var accessor = GLTFLoader._GetProperty(context + "/inverseBindMatrices", this._gltf.accessors, skin.inverseBindMatrices);
  99250. return this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  99251. return data;
  99252. });
  99253. };
  99254. GLTFLoader.prototype._createBone = function (node, skin, parent, localMatrix, baseMatrix, index) {
  99255. var babylonBone = new BABYLON.Bone(node.name || "joint" + node._index, skin._babylonSkeleton, parent, localMatrix, null, baseMatrix, index);
  99256. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  99257. node._babylonAnimationTargets.push(babylonBone);
  99258. return babylonBone;
  99259. };
  99260. GLTFLoader.prototype._loadBones = function (context, skin, inverseBindMatricesData) {
  99261. var babylonBones = {};
  99262. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  99263. var index = _a[_i];
  99264. var node = GLTFLoader._GetProperty(context + "/joints/" + index, this._gltf.nodes, index);
  99265. this._loadBone(node, skin, inverseBindMatricesData, babylonBones);
  99266. }
  99267. };
  99268. GLTFLoader.prototype._loadBone = function (node, skin, inverseBindMatricesData, babylonBones) {
  99269. var babylonBone = babylonBones[node._index];
  99270. if (babylonBone) {
  99271. return babylonBone;
  99272. }
  99273. var boneIndex = skin.joints.indexOf(node._index);
  99274. var baseMatrix = BABYLON.Matrix.Identity();
  99275. if (inverseBindMatricesData && boneIndex !== -1) {
  99276. baseMatrix = BABYLON.Matrix.FromArray(inverseBindMatricesData, boneIndex * 16);
  99277. baseMatrix.invertToRef(baseMatrix);
  99278. }
  99279. var babylonParentBone = null;
  99280. if (node._parent._babylonMesh !== this._rootBabylonMesh) {
  99281. babylonParentBone = this._loadBone(node._parent, skin, inverseBindMatricesData, babylonBones);
  99282. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  99283. }
  99284. babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex);
  99285. babylonBones[node._index] = babylonBone;
  99286. return babylonBone;
  99287. };
  99288. GLTFLoader.prototype._getNodeMatrix = function (node) {
  99289. return node.matrix ?
  99290. BABYLON.Matrix.FromArray(node.matrix) :
  99291. 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());
  99292. };
  99293. GLTFLoader.prototype._loadAnimationsAsync = function () {
  99294. var animations = this._gltf.animations;
  99295. if (!animations) {
  99296. return Promise.resolve();
  99297. }
  99298. var promises = new Array();
  99299. for (var index = 0; index < animations.length; index++) {
  99300. var animation = animations[index];
  99301. promises.push(this._loadAnimationAsync("#/animations/" + index, animation));
  99302. }
  99303. return Promise.all(promises).then(function () { });
  99304. };
  99305. GLTFLoader.prototype._loadAnimationAsync = function (context, animation) {
  99306. var babylonAnimationGroup = new BABYLON.AnimationGroup(animation.name || "animation" + animation._index, this._babylonScene);
  99307. animation._babylonAnimationGroup = babylonAnimationGroup;
  99308. var promises = new Array();
  99309. GLTF2.ArrayItem.Assign(animation.channels);
  99310. GLTF2.ArrayItem.Assign(animation.samplers);
  99311. for (var _i = 0, _a = animation.channels; _i < _a.length; _i++) {
  99312. var channel = _a[_i];
  99313. promises.push(this._loadAnimationChannelAsync(context + "/channels/" + channel._index, context, animation, channel, babylonAnimationGroup));
  99314. }
  99315. this.onAnimationGroupLoadedObservable.notifyObservers(babylonAnimationGroup);
  99316. return Promise.all(promises).then(function () {
  99317. babylonAnimationGroup.normalize();
  99318. });
  99319. };
  99320. GLTFLoader.prototype._loadAnimationChannelAsync = function (context, animationContext, animation, channel, babylonAnimationGroup) {
  99321. var _this = this;
  99322. var targetNode = GLTFLoader._GetProperty(context + "/target/node", this._gltf.nodes, channel.target.node);
  99323. if (!targetNode._babylonMesh || targetNode.skin != undefined) {
  99324. return Promise.resolve();
  99325. }
  99326. var sampler = GLTFLoader._GetProperty(context + "/sampler", animation.samplers, channel.sampler);
  99327. return this._loadAnimationSamplerAsync(animationContext + "/samplers/" + channel.sampler, sampler).then(function (data) {
  99328. var targetPath;
  99329. var animationType;
  99330. switch (channel.target.path) {
  99331. case "translation" /* TRANSLATION */: {
  99332. targetPath = "position";
  99333. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  99334. break;
  99335. }
  99336. case "rotation" /* ROTATION */: {
  99337. targetPath = "rotationQuaternion";
  99338. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  99339. break;
  99340. }
  99341. case "scale" /* SCALE */: {
  99342. targetPath = "scaling";
  99343. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  99344. break;
  99345. }
  99346. case "weights" /* WEIGHTS */: {
  99347. targetPath = "influence";
  99348. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  99349. break;
  99350. }
  99351. default: {
  99352. throw new Error(context + ": Invalid target path (" + channel.target.path + ")");
  99353. }
  99354. }
  99355. var outputBufferOffset = 0;
  99356. var getNextOutputValue;
  99357. switch (targetPath) {
  99358. case "position": {
  99359. getNextOutputValue = function () {
  99360. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  99361. outputBufferOffset += 3;
  99362. return value;
  99363. };
  99364. break;
  99365. }
  99366. case "rotationQuaternion": {
  99367. getNextOutputValue = function () {
  99368. var value = BABYLON.Quaternion.FromArray(data.output, outputBufferOffset);
  99369. outputBufferOffset += 4;
  99370. return value;
  99371. };
  99372. break;
  99373. }
  99374. case "scaling": {
  99375. getNextOutputValue = function () {
  99376. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  99377. outputBufferOffset += 3;
  99378. return value;
  99379. };
  99380. break;
  99381. }
  99382. case "influence": {
  99383. getNextOutputValue = function () {
  99384. var value = new Array(targetNode._numMorphTargets);
  99385. for (var i = 0; i < targetNode._numMorphTargets; i++) {
  99386. value[i] = data.output[outputBufferOffset++];
  99387. }
  99388. return value;
  99389. };
  99390. break;
  99391. }
  99392. }
  99393. var getNextKey;
  99394. switch (data.interpolation) {
  99395. case "STEP" /* STEP */: {
  99396. getNextKey = function (frameIndex) { return ({
  99397. frame: data.input[frameIndex],
  99398. value: getNextOutputValue(),
  99399. interpolation: BABYLON.AnimationKeyInterpolation.STEP
  99400. }); };
  99401. break;
  99402. }
  99403. case "LINEAR" /* LINEAR */: {
  99404. getNextKey = function (frameIndex) { return ({
  99405. frame: data.input[frameIndex],
  99406. value: getNextOutputValue()
  99407. }); };
  99408. break;
  99409. }
  99410. case "CUBICSPLINE" /* CUBICSPLINE */: {
  99411. getNextKey = function (frameIndex) { return ({
  99412. frame: data.input[frameIndex],
  99413. inTangent: getNextOutputValue(),
  99414. value: getNextOutputValue(),
  99415. outTangent: getNextOutputValue()
  99416. }); };
  99417. break;
  99418. }
  99419. }
  99420. var keys = new Array(data.input.length);
  99421. for (var frameIndex = 0; frameIndex < data.input.length; frameIndex++) {
  99422. keys[frameIndex] = getNextKey(frameIndex);
  99423. }
  99424. if (targetPath === "influence") {
  99425. var _loop_1 = function (targetIndex) {
  99426. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  99427. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  99428. babylonAnimation.setKeys(keys.map(function (key) { return ({
  99429. frame: key.frame,
  99430. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  99431. value: key.value[targetIndex],
  99432. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  99433. }); }));
  99434. _this._forEachPrimitive(targetNode, function (babylonMesh) {
  99435. var morphTarget = babylonMesh.morphTargetManager.getTarget(targetIndex);
  99436. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, morphTarget);
  99437. });
  99438. };
  99439. for (var targetIndex = 0; targetIndex < targetNode._numMorphTargets; targetIndex++) {
  99440. _loop_1(targetIndex);
  99441. }
  99442. }
  99443. else {
  99444. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  99445. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  99446. babylonAnimation.setKeys(keys);
  99447. if (targetNode._babylonAnimationTargets) {
  99448. for (var _i = 0, _a = targetNode._babylonAnimationTargets; _i < _a.length; _i++) {
  99449. var target = _a[_i];
  99450. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, target);
  99451. }
  99452. }
  99453. }
  99454. });
  99455. };
  99456. GLTFLoader.prototype._loadAnimationSamplerAsync = function (context, sampler) {
  99457. if (sampler._data) {
  99458. return sampler._data;
  99459. }
  99460. var interpolation = sampler.interpolation || "LINEAR" /* LINEAR */;
  99461. switch (interpolation) {
  99462. case "STEP" /* STEP */:
  99463. case "LINEAR" /* LINEAR */:
  99464. case "CUBICSPLINE" /* CUBICSPLINE */: {
  99465. break;
  99466. }
  99467. default: {
  99468. throw new Error(context + ": Invalid interpolation (" + sampler.interpolation + ")");
  99469. }
  99470. }
  99471. var inputData;
  99472. var outputData;
  99473. var inputAccessor = GLTFLoader._GetProperty(context + "/input", this._gltf.accessors, sampler.input);
  99474. var outputAccessor = GLTFLoader._GetProperty(context + "/output", this._gltf.accessors, sampler.output);
  99475. sampler._data = Promise.all([
  99476. this._loadAccessorAsync("#/accessors/" + inputAccessor._index, inputAccessor).then(function (data) {
  99477. inputData = data;
  99478. }),
  99479. this._loadAccessorAsync("#/accessors/" + outputAccessor._index, outputAccessor).then(function (data) {
  99480. outputData = data;
  99481. })
  99482. ]).then(function () {
  99483. return {
  99484. input: inputData,
  99485. interpolation: interpolation,
  99486. output: outputData,
  99487. };
  99488. });
  99489. return sampler._data;
  99490. };
  99491. GLTFLoader.prototype._loadBufferAsync = function (context, buffer) {
  99492. if (buffer._data) {
  99493. return buffer._data;
  99494. }
  99495. if (!buffer.uri) {
  99496. throw new Error(context + ": Uri is missing");
  99497. }
  99498. buffer._data = this._loadUriAsync(context, buffer.uri);
  99499. return buffer._data;
  99500. };
  99501. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView) {
  99502. if (bufferView._data) {
  99503. return bufferView._data;
  99504. }
  99505. var buffer = GLTFLoader._GetProperty(context + "/buffer", this._gltf.buffers, bufferView.buffer);
  99506. bufferView._data = this._loadBufferAsync("#/buffers/" + buffer._index, buffer).then(function (bufferData) {
  99507. try {
  99508. return new Uint8Array(bufferData.buffer, bufferData.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  99509. }
  99510. catch (e) {
  99511. throw new Error(context + ": " + e.message);
  99512. }
  99513. });
  99514. return bufferView._data;
  99515. };
  99516. GLTFLoader.prototype._loadAccessorAsync = function (context, accessor) {
  99517. var _this = this;
  99518. if (accessor.sparse) {
  99519. throw new Error(context + ": Sparse accessors are not currently supported");
  99520. }
  99521. if (accessor._data) {
  99522. return accessor._data;
  99523. }
  99524. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  99525. accessor._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (bufferViewData) {
  99526. var numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
  99527. var byteOffset = accessor.byteOffset || 0;
  99528. var byteStride = bufferView.byteStride;
  99529. if (byteStride === 0) {
  99530. BABYLON.Tools.Warn(context + ": Byte stride of 0 is not valid");
  99531. }
  99532. try {
  99533. switch (accessor.componentType) {
  99534. case 5120 /* BYTE */: {
  99535. return _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  99536. }
  99537. case 5121 /* UNSIGNED_BYTE */: {
  99538. return _this._buildArrayBuffer(Uint8Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  99539. }
  99540. case 5122 /* SHORT */: {
  99541. return _this._buildArrayBuffer(Int16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  99542. }
  99543. case 5123 /* UNSIGNED_SHORT */: {
  99544. return _this._buildArrayBuffer(Uint16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  99545. }
  99546. case 5125 /* UNSIGNED_INT */: {
  99547. return _this._buildArrayBuffer(Uint32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  99548. }
  99549. case 5126 /* FLOAT */: {
  99550. return _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  99551. }
  99552. default: {
  99553. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  99554. }
  99555. }
  99556. }
  99557. catch (e) {
  99558. throw new Error(context + ": " + e.messsage);
  99559. }
  99560. });
  99561. return accessor._data;
  99562. };
  99563. GLTFLoader.prototype._buildArrayBuffer = function (typedArray, data, byteOffset, count, numComponents, byteStride) {
  99564. byteOffset += data.byteOffset;
  99565. var targetLength = count * numComponents;
  99566. if (!byteStride || byteStride === numComponents * typedArray.BYTES_PER_ELEMENT) {
  99567. return new typedArray(data.buffer, byteOffset, targetLength);
  99568. }
  99569. var elementStride = byteStride / typedArray.BYTES_PER_ELEMENT;
  99570. var sourceBuffer = new typedArray(data.buffer, byteOffset, elementStride * count);
  99571. var targetBuffer = new typedArray(targetLength);
  99572. var sourceIndex = 0;
  99573. var targetIndex = 0;
  99574. while (targetIndex < targetLength) {
  99575. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  99576. targetBuffer[targetIndex] = sourceBuffer[sourceIndex + componentIndex];
  99577. targetIndex++;
  99578. }
  99579. sourceIndex += elementStride;
  99580. }
  99581. return targetBuffer;
  99582. };
  99583. GLTFLoader.prototype._getDefaultMaterial = function (drawMode) {
  99584. var babylonMaterial = this._defaultBabylonMaterials[drawMode];
  99585. if (!babylonMaterial) {
  99586. babylonMaterial = this._createMaterial(BABYLON.PBRMaterial, "__gltf_default", drawMode);
  99587. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  99588. babylonMaterial.metallic = 1;
  99589. babylonMaterial.roughness = 1;
  99590. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  99591. }
  99592. return babylonMaterial;
  99593. };
  99594. GLTFLoader.prototype._loadMaterialMetallicRoughnessPropertiesAsync = function (context, material, babylonMaterial) {
  99595. var promises = new Array();
  99596. // Ensure metallic workflow
  99597. babylonMaterial.metallic = 1;
  99598. babylonMaterial.roughness = 1;
  99599. var properties = material.pbrMetallicRoughness;
  99600. if (properties) {
  99601. if (properties.baseColorFactor) {
  99602. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  99603. babylonMaterial.alpha = properties.baseColorFactor[3];
  99604. }
  99605. else {
  99606. babylonMaterial.albedoColor = BABYLON.Color3.White();
  99607. }
  99608. babylonMaterial.metallic = properties.metallicFactor == undefined ? 1 : properties.metallicFactor;
  99609. babylonMaterial.roughness = properties.roughnessFactor == undefined ? 1 : properties.roughnessFactor;
  99610. if (properties.baseColorTexture) {
  99611. promises.push(this._loadTextureAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  99612. babylonMaterial.albedoTexture = texture;
  99613. }));
  99614. }
  99615. if (properties.metallicRoughnessTexture) {
  99616. promises.push(this._loadTextureAsync(context + "/metallicRoughnessTexture", properties.metallicRoughnessTexture, function (texture) {
  99617. babylonMaterial.metallicTexture = texture;
  99618. }));
  99619. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  99620. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  99621. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  99622. }
  99623. }
  99624. this._loadMaterialAlphaProperties(context, material, babylonMaterial);
  99625. return Promise.all(promises).then(function () { });
  99626. };
  99627. GLTFLoader.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  99628. var promise = GLTF2.GLTFLoaderExtension._LoadMaterialAsync(this, context, material, babylonMesh, babylonDrawMode, assign);
  99629. if (promise) {
  99630. return promise;
  99631. }
  99632. material._babylonData = material._babylonData || {};
  99633. var babylonData = material._babylonData[babylonDrawMode];
  99634. if (!babylonData) {
  99635. var promises = new Array();
  99636. var name_3 = material.name || "materialSG_" + material._index;
  99637. var babylonMaterial = this._createMaterial(BABYLON.PBRMaterial, name_3, babylonDrawMode);
  99638. promises.push(this._loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  99639. promises.push(this._loadMaterialMetallicRoughnessPropertiesAsync(context, material, babylonMaterial));
  99640. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  99641. babylonData = {
  99642. material: babylonMaterial,
  99643. meshes: [],
  99644. loaded: Promise.all(promises).then(function () { })
  99645. };
  99646. material._babylonData[babylonDrawMode] = babylonData;
  99647. }
  99648. babylonData.meshes.push(babylonMesh);
  99649. assign(babylonData.material);
  99650. return babylonData.loaded;
  99651. };
  99652. GLTFLoader.prototype._createMaterial = function (type, name, drawMode) {
  99653. var babylonMaterial = new type(name, this._babylonScene);
  99654. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  99655. babylonMaterial.fillMode = drawMode;
  99656. return babylonMaterial;
  99657. };
  99658. GLTFLoader.prototype._loadMaterialBasePropertiesAsync = function (context, material, babylonMaterial) {
  99659. var promises = new Array();
  99660. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  99661. if (material.doubleSided) {
  99662. babylonMaterial.backFaceCulling = false;
  99663. babylonMaterial.twoSidedLighting = true;
  99664. }
  99665. if (material.normalTexture) {
  99666. promises.push(this._loadTextureAsync(context + "/normalTexture", material.normalTexture, function (texture) {
  99667. babylonMaterial.bumpTexture = texture;
  99668. }));
  99669. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  99670. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  99671. if (material.normalTexture.scale != undefined) {
  99672. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  99673. }
  99674. }
  99675. if (material.occlusionTexture) {
  99676. promises.push(this._loadTextureAsync(context + "/occlusionTexture", material.occlusionTexture, function (texture) {
  99677. babylonMaterial.ambientTexture = texture;
  99678. }));
  99679. babylonMaterial.useAmbientInGrayScale = true;
  99680. if (material.occlusionTexture.strength != undefined) {
  99681. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  99682. }
  99683. }
  99684. if (material.emissiveTexture) {
  99685. promises.push(this._loadTextureAsync(context + "/emissiveTexture", material.emissiveTexture, function (texture) {
  99686. babylonMaterial.emissiveTexture = texture;
  99687. }));
  99688. }
  99689. return Promise.all(promises).then(function () { });
  99690. };
  99691. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material, babylonMaterial) {
  99692. var alphaMode = material.alphaMode || "OPAQUE" /* OPAQUE */;
  99693. switch (alphaMode) {
  99694. case "OPAQUE" /* OPAQUE */: {
  99695. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  99696. break;
  99697. }
  99698. case "MASK" /* MASK */: {
  99699. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  99700. babylonMaterial.alphaCutOff = (material.alphaCutoff == undefined ? 0.5 : material.alphaCutoff);
  99701. if (babylonMaterial.albedoTexture) {
  99702. babylonMaterial.albedoTexture.hasAlpha = true;
  99703. }
  99704. break;
  99705. }
  99706. case "BLEND" /* BLEND */: {
  99707. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  99708. if (babylonMaterial.albedoTexture) {
  99709. babylonMaterial.albedoTexture.hasAlpha = true;
  99710. babylonMaterial.useAlphaFromAlbedoTexture = true;
  99711. }
  99712. break;
  99713. }
  99714. default: {
  99715. throw new Error(context + ": Invalid alpha mode (" + material.alphaMode + ")");
  99716. }
  99717. }
  99718. };
  99719. GLTFLoader.prototype._loadTextureAsync = function (context, textureInfo, assign) {
  99720. var _this = this;
  99721. var texture = GLTFLoader._GetProperty(context + "/index", this._gltf.textures, textureInfo.index);
  99722. context = "#/textures/" + textureInfo.index;
  99723. var promises = new Array();
  99724. var sampler = (texture.sampler == undefined ? this._defaultSampler : GLTFLoader._GetProperty(context + "/sampler", this._gltf.samplers, texture.sampler));
  99725. var samplerData = this._loadSampler("#/samplers/" + sampler._index, sampler);
  99726. var deferred = new BABYLON.Deferred();
  99727. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, samplerData.noMipMaps, false, samplerData.samplingMode, function () {
  99728. if (!_this._disposed) {
  99729. deferred.resolve();
  99730. }
  99731. }, function (message, exception) {
  99732. if (!_this._disposed) {
  99733. deferred.reject(new Error(context + ": " + ((exception && exception.message) ? exception.message : message || "Failed to load texture")));
  99734. }
  99735. });
  99736. promises.push(deferred.promise);
  99737. babylonTexture.name = texture.name || "texture" + texture._index;
  99738. babylonTexture.wrapU = samplerData.wrapU;
  99739. babylonTexture.wrapV = samplerData.wrapV;
  99740. babylonTexture.coordinatesIndex = textureInfo.texCoord || 0;
  99741. var image = GLTFLoader._GetProperty(context + "/source", this._gltf.images, texture.source);
  99742. promises.push(this._loadImageAsync("#/images/" + image._index, image).then(function (objectURL) {
  99743. babylonTexture.updateURL(objectURL);
  99744. }));
  99745. assign(babylonTexture);
  99746. this.onTextureLoadedObservable.notifyObservers(babylonTexture);
  99747. return Promise.all(promises).then(function () { });
  99748. };
  99749. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  99750. if (!sampler._data) {
  99751. sampler._data = {
  99752. noMipMaps: (sampler.minFilter === 9728 /* NEAREST */ || sampler.minFilter === 9729 /* LINEAR */),
  99753. samplingMode: GLTFLoader._GetTextureSamplingMode(context, sampler.magFilter, sampler.minFilter),
  99754. wrapU: GLTFLoader._GetTextureWrapMode(context, sampler.wrapS),
  99755. wrapV: GLTFLoader._GetTextureWrapMode(context, sampler.wrapT)
  99756. };
  99757. }
  99758. ;
  99759. return sampler._data;
  99760. };
  99761. GLTFLoader.prototype._loadImageAsync = function (context, image) {
  99762. if (image._objectURL) {
  99763. return image._objectURL;
  99764. }
  99765. var promise;
  99766. if (image.uri) {
  99767. promise = this._loadUriAsync(context, image.uri);
  99768. }
  99769. else {
  99770. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, image.bufferView);
  99771. promise = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView);
  99772. }
  99773. image._objectURL = promise.then(function (data) {
  99774. return URL.createObjectURL(new Blob([data], { type: image.mimeType }));
  99775. });
  99776. return image._objectURL;
  99777. };
  99778. GLTFLoader.prototype._loadUriAsync = function (context, uri) {
  99779. var _this = this;
  99780. var promise = GLTF2.GLTFLoaderExtension._LoadUriAsync(this, context, uri);
  99781. if (promise) {
  99782. return promise;
  99783. }
  99784. if (!GLTFLoader._ValidateUri(uri)) {
  99785. throw new Error(context + ": Uri '" + uri + "' is invalid");
  99786. }
  99787. if (BABYLON.Tools.IsBase64(uri)) {
  99788. return Promise.resolve(new Uint8Array(BABYLON.Tools.DecodeBase64(uri)));
  99789. }
  99790. return new Promise(function (resolve, reject) {
  99791. var request = BABYLON.Tools.LoadFile(_this._rootUrl + uri, function (data) {
  99792. if (!_this._disposed) {
  99793. resolve(new Uint8Array(data));
  99794. }
  99795. }, function (event) {
  99796. if (!_this._disposed) {
  99797. try {
  99798. if (request && _this._state === BABYLON.GLTFLoaderState.Loading) {
  99799. request._lengthComputable = event.lengthComputable;
  99800. request._loaded = event.loaded;
  99801. request._total = event.total;
  99802. _this._onProgress();
  99803. }
  99804. }
  99805. catch (e) {
  99806. reject(e);
  99807. }
  99808. }
  99809. }, _this._babylonScene.database, true, function (request, exception) {
  99810. if (!_this._disposed) {
  99811. reject(new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request));
  99812. }
  99813. });
  99814. _this._requests.push(request);
  99815. });
  99816. };
  99817. GLTFLoader.prototype._onProgress = function () {
  99818. if (!this._progressCallback) {
  99819. return;
  99820. }
  99821. var lengthComputable = true;
  99822. var loaded = 0;
  99823. var total = 0;
  99824. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  99825. var request = _a[_i];
  99826. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  99827. return;
  99828. }
  99829. lengthComputable = lengthComputable && request._lengthComputable;
  99830. loaded += request._loaded;
  99831. total += request._total;
  99832. }
  99833. this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  99834. };
  99835. GLTFLoader._GetProperty = function (context, array, index) {
  99836. if (!array || index == undefined || !array[index]) {
  99837. throw new Error(context + ": Failed to find index (" + index + ")");
  99838. }
  99839. return array[index];
  99840. };
  99841. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  99842. // Set defaults if undefined
  99843. mode = mode == undefined ? 10497 /* REPEAT */ : mode;
  99844. switch (mode) {
  99845. case 33071 /* CLAMP_TO_EDGE */: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  99846. case 33648 /* MIRRORED_REPEAT */: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  99847. case 10497 /* REPEAT */: return BABYLON.Texture.WRAP_ADDRESSMODE;
  99848. default:
  99849. BABYLON.Tools.Warn(context + ": Invalid texture wrap mode (" + mode + ")");
  99850. return BABYLON.Texture.WRAP_ADDRESSMODE;
  99851. }
  99852. };
  99853. GLTFLoader._GetTextureSamplingMode = function (context, magFilter, minFilter) {
  99854. // Set defaults if undefined
  99855. magFilter = magFilter == undefined ? 9729 /* LINEAR */ : magFilter;
  99856. minFilter = minFilter == undefined ? 9987 /* LINEAR_MIPMAP_LINEAR */ : minFilter;
  99857. if (magFilter === 9729 /* LINEAR */) {
  99858. switch (minFilter) {
  99859. case 9728 /* NEAREST */: return BABYLON.Texture.LINEAR_NEAREST;
  99860. case 9729 /* LINEAR */: return BABYLON.Texture.LINEAR_LINEAR;
  99861. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  99862. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  99863. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  99864. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  99865. default:
  99866. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  99867. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  99868. }
  99869. }
  99870. else {
  99871. if (magFilter !== 9728 /* NEAREST */) {
  99872. BABYLON.Tools.Warn(context + ": Invalid texture magnification filter (" + magFilter + ")");
  99873. }
  99874. switch (minFilter) {
  99875. case 9728 /* NEAREST */: return BABYLON.Texture.NEAREST_NEAREST;
  99876. case 9729 /* LINEAR */: return BABYLON.Texture.NEAREST_LINEAR;
  99877. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  99878. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  99879. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  99880. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  99881. default:
  99882. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  99883. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  99884. }
  99885. }
  99886. };
  99887. GLTFLoader._GetNumComponents = function (context, type) {
  99888. switch (type) {
  99889. case "SCALAR": return 1;
  99890. case "VEC2": return 2;
  99891. case "VEC3": return 3;
  99892. case "VEC4": return 4;
  99893. case "MAT2": return 4;
  99894. case "MAT3": return 9;
  99895. case "MAT4": return 16;
  99896. }
  99897. throw new Error(context + ": Invalid type (" + type + ")");
  99898. };
  99899. GLTFLoader._ValidateUri = function (uri) {
  99900. return (BABYLON.Tools.IsBase64(uri) || uri.indexOf("..") === -1);
  99901. };
  99902. GLTFLoader._GetDrawMode = function (context, mode) {
  99903. if (mode == undefined) {
  99904. mode = 4 /* TRIANGLES */;
  99905. }
  99906. switch (mode) {
  99907. case 0 /* POINTS */: return BABYLON.Material.PointListDrawMode;
  99908. case 1 /* LINES */: return BABYLON.Material.LineListDrawMode;
  99909. case 2 /* LINE_LOOP */: return BABYLON.Material.LineLoopDrawMode;
  99910. case 3 /* LINE_STRIP */: return BABYLON.Material.LineStripDrawMode;
  99911. case 4 /* TRIANGLES */: return BABYLON.Material.TriangleFillMode;
  99912. case 5 /* TRIANGLE_STRIP */: return BABYLON.Material.TriangleStripDrawMode;
  99913. case 6 /* TRIANGLE_FAN */: return BABYLON.Material.TriangleFanDrawMode;
  99914. }
  99915. throw new Error(context + ": Invalid mesh primitive mode (" + mode + ")");
  99916. };
  99917. GLTFLoader.prototype._compileMaterialsAsync = function () {
  99918. var promises = new Array();
  99919. if (this._gltf.materials) {
  99920. for (var _i = 0, _a = this._gltf.materials; _i < _a.length; _i++) {
  99921. var material = _a[_i];
  99922. if (material._babylonData) {
  99923. for (var babylonDrawMode in material._babylonData) {
  99924. var babylonData = material._babylonData[babylonDrawMode];
  99925. for (var _b = 0, _c = babylonData.meshes; _b < _c.length; _b++) {
  99926. var babylonMesh = _c[_b];
  99927. // Ensure nonUniformScaling is set if necessary.
  99928. babylonMesh.computeWorldMatrix(true);
  99929. var babylonMaterial = babylonData.material;
  99930. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh));
  99931. if (this.useClipPlane) {
  99932. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true }));
  99933. }
  99934. }
  99935. }
  99936. }
  99937. }
  99938. }
  99939. return Promise.all(promises).then(function () { });
  99940. };
  99941. GLTFLoader.prototype._compileShadowGeneratorsAsync = function () {
  99942. var promises = new Array();
  99943. var lights = this._babylonScene.lights;
  99944. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  99945. var light = lights_1[_i];
  99946. var generator = light.getShadowGenerator();
  99947. if (generator) {
  99948. promises.push(generator.forceCompilationAsync());
  99949. }
  99950. }
  99951. return Promise.all(promises).then(function () { });
  99952. };
  99953. GLTFLoader.prototype._clear = function () {
  99954. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  99955. var request = _a[_i];
  99956. request.abort();
  99957. }
  99958. this._requests.length = 0;
  99959. if (this._gltf && this._gltf.images) {
  99960. for (var _b = 0, _c = this._gltf.images; _b < _c.length; _b++) {
  99961. var image = _c[_b];
  99962. if (image._objectURL) {
  99963. image._objectURL.then(function (value) {
  99964. URL.revokeObjectURL(value);
  99965. });
  99966. image._objectURL = undefined;
  99967. }
  99968. }
  99969. }
  99970. delete this._gltf;
  99971. delete this._babylonScene;
  99972. this._completePromises.length = 0;
  99973. for (var name_4 in this._extensions) {
  99974. this._extensions[name_4].dispose();
  99975. }
  99976. this._extensions = {};
  99977. delete this._rootBabylonMesh;
  99978. delete this._progressCallback;
  99979. this.onMeshLoadedObservable.clear();
  99980. this.onTextureLoadedObservable.clear();
  99981. this.onMaterialLoadedObservable.clear();
  99982. };
  99983. GLTFLoader.prototype._applyExtensions = function (actionAsync) {
  99984. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  99985. var name_5 = _a[_i];
  99986. var extension = this._extensions[name_5];
  99987. if (extension.enabled) {
  99988. var promise = actionAsync(extension);
  99989. if (promise) {
  99990. return promise;
  99991. }
  99992. }
  99993. }
  99994. return null;
  99995. };
  99996. GLTFLoader._Names = new Array();
  99997. GLTFLoader._Factories = {};
  99998. return GLTFLoader;
  99999. }());
  100000. GLTF2.GLTFLoader = GLTFLoader;
  100001. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function () { return new GLTFLoader(); };
  100002. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  100003. })(BABYLON || (BABYLON = {}));
  100004. //# sourceMappingURL=babylon.glTFLoader.js.map
  100005. "use strict";
  100006. var BABYLON;
  100007. (function (BABYLON) {
  100008. var GLTF2;
  100009. (function (GLTF2) {
  100010. var GLTFLoaderExtension = /** @class */ (function () {
  100011. function GLTFLoaderExtension(loader) {
  100012. this.enabled = true;
  100013. this._loader = loader;
  100014. }
  100015. GLTFLoaderExtension.prototype.dispose = function () {
  100016. delete this._loader;
  100017. };
  100018. // #region Overridable Methods
  100019. /** Override this method to modify the default behavior for loading scenes. */
  100020. GLTFLoaderExtension.prototype._loadSceneAsync = function (context, node) { return null; };
  100021. /** Override this method to modify the default behavior for loading nodes. */
  100022. GLTFLoaderExtension.prototype._loadNodeAsync = function (context, node) { return null; };
  100023. /** Override this method to modify the default behavior for loading mesh primitive vertex data. */
  100024. GLTFLoaderExtension.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) { return null; };
  100025. /** Override this method to modify the default behavior for loading materials. */
  100026. GLTFLoaderExtension.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) { return null; };
  100027. /** Override this method to modify the default behavior for loading uris. */
  100028. GLTFLoaderExtension.prototype._loadUriAsync = function (context, uri) { return null; };
  100029. // #endregion
  100030. /** Helper method called by a loader extension to load an glTF extension. */
  100031. GLTFLoaderExtension.prototype._loadExtensionAsync = function (context, property, actionAsync) {
  100032. if (!property.extensions) {
  100033. return null;
  100034. }
  100035. var extensions = property.extensions;
  100036. var extension = extensions[this.name];
  100037. if (!extension) {
  100038. return null;
  100039. }
  100040. // Clear out the extension before executing the action to avoid recursing into the same property.
  100041. delete extensions[this.name];
  100042. try {
  100043. return actionAsync(context + "/extensions/" + this.name, extension);
  100044. }
  100045. finally {
  100046. // Restore the extension after executing the action.
  100047. extensions[this.name] = extension;
  100048. }
  100049. };
  100050. /** Helper method called by the loader to allow extensions to override loading scenes. */
  100051. GLTFLoaderExtension._LoadSceneAsync = function (loader, context, scene) {
  100052. return loader._applyExtensions(function (extension) { return extension._loadSceneAsync(context, scene); });
  100053. };
  100054. /** Helper method called by the loader to allow extensions to override loading nodes. */
  100055. GLTFLoaderExtension._LoadNodeAsync = function (loader, context, node) {
  100056. return loader._applyExtensions(function (extension) { return extension._loadNodeAsync(context, node); });
  100057. };
  100058. /** Helper method called by the loader to allow extensions to override loading mesh primitive vertex data. */
  100059. GLTFLoaderExtension._LoadVertexDataAsync = function (loader, context, primitive, babylonMesh) {
  100060. return loader._applyExtensions(function (extension) { return extension._loadVertexDataAsync(context, primitive, babylonMesh); });
  100061. };
  100062. /** Helper method called by the loader to allow extensions to override loading materials. */
  100063. GLTFLoaderExtension._LoadMaterialAsync = function (loader, context, material, babylonMesh, babylonDrawMode, assign) {
  100064. return loader._applyExtensions(function (extension) { return extension._loadMaterialAsync(context, material, babylonMesh, babylonDrawMode, assign); });
  100065. };
  100066. /** Helper method called by the loader to allow extensions to override loading uris. */
  100067. GLTFLoaderExtension._LoadUriAsync = function (loader, context, uri) {
  100068. return loader._applyExtensions(function (extension) { return extension._loadUriAsync(context, uri); });
  100069. };
  100070. return GLTFLoaderExtension;
  100071. }());
  100072. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  100073. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  100074. })(BABYLON || (BABYLON = {}));
  100075. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  100076. "use strict";
  100077. var BABYLON;
  100078. (function (BABYLON) {
  100079. var GLTF2;
  100080. (function (GLTF2) {
  100081. var Extensions;
  100082. (function (Extensions) {
  100083. // https://github.com/sbtron/glTF/tree/MSFT_lod/extensions/Vendor/MSFT_lod
  100084. var NAME = "MSFT_lod";
  100085. var MSFT_lod = /** @class */ (function (_super) {
  100086. __extends(MSFT_lod, _super);
  100087. function MSFT_lod() {
  100088. var _this = _super !== null && _super.apply(this, arguments) || this;
  100089. _this.name = NAME;
  100090. /**
  100091. * Maximum number of LODs to load, starting from the lowest LOD.
  100092. */
  100093. _this.maxLODsToLoad = Number.MAX_VALUE;
  100094. _this._loadingNodeLOD = null;
  100095. _this._loadNodeSignals = {};
  100096. _this._loadingMaterialLOD = null;
  100097. _this._loadMaterialSignals = {};
  100098. return _this;
  100099. }
  100100. MSFT_lod.prototype._loadNodeAsync = function (context, node) {
  100101. var _this = this;
  100102. return this._loadExtensionAsync(context, node, function (context, extension) {
  100103. var firstPromise;
  100104. var nodeLODs = _this._getLODs(context, node, _this._loader._gltf.nodes, extension.ids);
  100105. var _loop_1 = function (indexLOD) {
  100106. var nodeLOD = nodeLODs[indexLOD];
  100107. if (indexLOD !== 0) {
  100108. _this._loadingNodeLOD = nodeLOD;
  100109. if (!_this._loadNodeSignals[nodeLOD._index]) {
  100110. _this._loadNodeSignals[nodeLOD._index] = new BABYLON.Deferred();
  100111. }
  100112. }
  100113. var promise = _this._loader._loadNodeAsync("#/nodes/" + nodeLOD._index, nodeLOD).then(function () {
  100114. if (indexLOD !== 0) {
  100115. var previousNodeLOD = nodeLODs[indexLOD - 1];
  100116. if (previousNodeLOD._babylonMesh) {
  100117. previousNodeLOD._babylonMesh.dispose(false, true);
  100118. delete previousNodeLOD._babylonMesh;
  100119. }
  100120. }
  100121. if (indexLOD !== nodeLODs.length - 1) {
  100122. var nodeIndex = nodeLODs[indexLOD + 1]._index;
  100123. if (_this._loadNodeSignals[nodeIndex]) {
  100124. _this._loadNodeSignals[nodeIndex].resolve();
  100125. delete _this._loadNodeSignals[nodeIndex];
  100126. }
  100127. }
  100128. });
  100129. if (indexLOD === 0) {
  100130. firstPromise = promise;
  100131. }
  100132. else {
  100133. _this._loader._completePromises.push(promise);
  100134. _this._loadingNodeLOD = null;
  100135. }
  100136. };
  100137. for (var indexLOD = 0; indexLOD < nodeLODs.length; indexLOD++) {
  100138. _loop_1(indexLOD);
  100139. }
  100140. return firstPromise;
  100141. });
  100142. };
  100143. MSFT_lod.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  100144. var _this = this;
  100145. // Don't load material LODs if already loading a node LOD.
  100146. if (this._loadingNodeLOD) {
  100147. return null;
  100148. }
  100149. return this._loadExtensionAsync(context, material, function (context, extension) {
  100150. var firstPromise;
  100151. var materialLODs = _this._getLODs(context, material, _this._loader._gltf.materials, extension.ids);
  100152. var _loop_2 = function (indexLOD) {
  100153. var materialLOD = materialLODs[indexLOD];
  100154. if (indexLOD !== 0) {
  100155. _this._loadingMaterialLOD = materialLOD;
  100156. if (!_this._loadMaterialSignals[materialLOD._index]) {
  100157. _this._loadMaterialSignals[materialLOD._index] = new BABYLON.Deferred();
  100158. }
  100159. }
  100160. var promise = _this._loader._loadMaterialAsync("#/materials/" + materialLOD._index, materialLOD, babylonMesh, babylonDrawMode, indexLOD === 0 ? assign : function () { }).then(function () {
  100161. if (indexLOD !== 0) {
  100162. var babylonDataLOD = materialLOD._babylonData;
  100163. assign(babylonDataLOD[babylonDrawMode].material);
  100164. var previousBabylonDataLOD = materialLODs[indexLOD - 1]._babylonData;
  100165. if (previousBabylonDataLOD[babylonDrawMode]) {
  100166. previousBabylonDataLOD[babylonDrawMode].material.dispose();
  100167. delete previousBabylonDataLOD[babylonDrawMode];
  100168. }
  100169. }
  100170. if (indexLOD !== materialLODs.length - 1) {
  100171. var materialIndex = materialLODs[indexLOD + 1]._index;
  100172. if (_this._loadMaterialSignals[materialIndex]) {
  100173. _this._loadMaterialSignals[materialIndex].resolve();
  100174. delete _this._loadMaterialSignals[materialIndex];
  100175. }
  100176. }
  100177. });
  100178. if (indexLOD === 0) {
  100179. firstPromise = promise;
  100180. }
  100181. else {
  100182. _this._loader._completePromises.push(promise);
  100183. _this._loadingMaterialLOD = null;
  100184. }
  100185. };
  100186. for (var indexLOD = 0; indexLOD < materialLODs.length; indexLOD++) {
  100187. _loop_2(indexLOD);
  100188. }
  100189. return firstPromise;
  100190. });
  100191. };
  100192. MSFT_lod.prototype._loadUriAsync = function (context, uri) {
  100193. var _this = this;
  100194. // Defer the loading of uris if loading a material or node LOD.
  100195. if (this._loadingMaterialLOD) {
  100196. var index = this._loadingMaterialLOD._index;
  100197. return this._loadMaterialSignals[index].promise.then(function () {
  100198. return _this._loader._loadUriAsync(context, uri);
  100199. });
  100200. }
  100201. else if (this._loadingNodeLOD) {
  100202. var index = this._loadingNodeLOD._index;
  100203. return this._loadNodeSignals[index].promise.then(function () {
  100204. return _this._loader._loadUriAsync(context, uri);
  100205. });
  100206. }
  100207. return null;
  100208. };
  100209. /**
  100210. * Gets an array of LOD properties from lowest to highest.
  100211. */
  100212. MSFT_lod.prototype._getLODs = function (context, property, array, ids) {
  100213. if (this.maxLODsToLoad <= 0) {
  100214. throw new Error("maxLODsToLoad must be greater than zero");
  100215. }
  100216. var properties = new Array();
  100217. for (var i = ids.length - 1; i >= 0; i--) {
  100218. properties.push(GLTF2.GLTFLoader._GetProperty(context + "/ids/" + ids[i], array, ids[i]));
  100219. if (properties.length === this.maxLODsToLoad) {
  100220. return properties;
  100221. }
  100222. }
  100223. properties.push(property);
  100224. return properties;
  100225. };
  100226. return MSFT_lod;
  100227. }(GLTF2.GLTFLoaderExtension));
  100228. Extensions.MSFT_lod = MSFT_lod;
  100229. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_lod(loader); });
  100230. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  100231. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  100232. })(BABYLON || (BABYLON = {}));
  100233. //# sourceMappingURL=MSFT_lod.js.map
  100234. "use strict";
  100235. var BABYLON;
  100236. (function (BABYLON) {
  100237. var GLTF2;
  100238. (function (GLTF2) {
  100239. var Extensions;
  100240. (function (Extensions) {
  100241. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression
  100242. var NAME = "KHR_draco_mesh_compression";
  100243. var KHR_draco_mesh_compression = /** @class */ (function (_super) {
  100244. __extends(KHR_draco_mesh_compression, _super);
  100245. function KHR_draco_mesh_compression(loader) {
  100246. var _this = _super.call(this, loader) || this;
  100247. _this.name = NAME;
  100248. _this._dracoCompression = null;
  100249. // Disable extension if decoder is not available.
  100250. if (!BABYLON.DracoCompression.DecoderUrl) {
  100251. _this.enabled = false;
  100252. }
  100253. return _this;
  100254. }
  100255. KHR_draco_mesh_compression.prototype.dispose = function () {
  100256. if (this._dracoCompression) {
  100257. this._dracoCompression.dispose();
  100258. }
  100259. _super.prototype.dispose.call(this);
  100260. };
  100261. KHR_draco_mesh_compression.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  100262. var _this = this;
  100263. return this._loadExtensionAsync(context, primitive, function (extensionContext, extension) {
  100264. if (primitive.mode != undefined) {
  100265. if (primitive.mode !== 5 /* TRIANGLE_STRIP */ &&
  100266. primitive.mode !== 4 /* TRIANGLES */) {
  100267. throw new Error(context + ": Unsupported mode " + primitive.mode);
  100268. }
  100269. // TODO: handle triangle strips
  100270. if (primitive.mode === 5 /* TRIANGLE_STRIP */) {
  100271. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  100272. }
  100273. }
  100274. var attributes = {};
  100275. var loadAttribute = function (name, kind) {
  100276. var uniqueId = extension.attributes[name];
  100277. if (uniqueId == undefined) {
  100278. return;
  100279. }
  100280. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  100281. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  100282. babylonMesh._delayInfo.push(kind);
  100283. }
  100284. attributes[kind] = uniqueId;
  100285. };
  100286. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  100287. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  100288. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  100289. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  100290. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  100291. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  100292. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  100293. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  100294. var bufferView = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._loader._gltf.bufferViews, extension.bufferView);
  100295. return _this._loader._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  100296. try {
  100297. if (!_this._dracoCompression) {
  100298. _this._dracoCompression = new BABYLON.DracoCompression();
  100299. }
  100300. return _this._dracoCompression.decodeMeshAsync(data, attributes);
  100301. }
  100302. catch (e) {
  100303. throw new Error(context + ": " + e.message);
  100304. }
  100305. });
  100306. });
  100307. };
  100308. return KHR_draco_mesh_compression;
  100309. }(GLTF2.GLTFLoaderExtension));
  100310. Extensions.KHR_draco_mesh_compression = KHR_draco_mesh_compression;
  100311. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_draco_mesh_compression(loader); });
  100312. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  100313. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  100314. })(BABYLON || (BABYLON = {}));
  100315. //# sourceMappingURL=KHR_draco_mesh_compression.js.map
  100316. "use strict";
  100317. var BABYLON;
  100318. (function (BABYLON) {
  100319. var GLTF2;
  100320. (function (GLTF2) {
  100321. var Extensions;
  100322. (function (Extensions) {
  100323. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness
  100324. var NAME = "KHR_materials_pbrSpecularGlossiness";
  100325. var KHR_materials_pbrSpecularGlossiness = /** @class */ (function (_super) {
  100326. __extends(KHR_materials_pbrSpecularGlossiness, _super);
  100327. function KHR_materials_pbrSpecularGlossiness() {
  100328. var _this = _super !== null && _super.apply(this, arguments) || this;
  100329. _this.name = NAME;
  100330. return _this;
  100331. }
  100332. KHR_materials_pbrSpecularGlossiness.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  100333. var _this = this;
  100334. return this._loadExtensionAsync(context, material, function (context, extension) {
  100335. material._babylonData = material._babylonData || {};
  100336. var babylonData = material._babylonData[babylonDrawMode];
  100337. if (!babylonData) {
  100338. var promises = new Array();
  100339. var name_1 = material.name || "materialSG_" + material._index;
  100340. var babylonMaterial = _this._loader._createMaterial(BABYLON.PBRMaterial, name_1, babylonDrawMode);
  100341. promises.push(_this._loader._loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  100342. promises.push(_this._loadSpecularGlossinessPropertiesAsync(context, material, extension, babylonMaterial));
  100343. _this._loader.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  100344. babylonData = {
  100345. material: babylonMaterial,
  100346. meshes: [],
  100347. loaded: Promise.all(promises).then(function () { })
  100348. };
  100349. material._babylonData[babylonDrawMode] = babylonData;
  100350. }
  100351. babylonData.meshes.push(babylonMesh);
  100352. assign(babylonData.material);
  100353. return babylonData.loaded;
  100354. });
  100355. };
  100356. KHR_materials_pbrSpecularGlossiness.prototype._loadSpecularGlossinessPropertiesAsync = function (context, material, properties, babylonMaterial) {
  100357. var promises = new Array();
  100358. if (properties.diffuseFactor) {
  100359. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.diffuseFactor);
  100360. babylonMaterial.alpha = properties.diffuseFactor[3];
  100361. }
  100362. else {
  100363. babylonMaterial.albedoColor = BABYLON.Color3.White();
  100364. }
  100365. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : BABYLON.Color3.White();
  100366. babylonMaterial.microSurface = properties.glossinessFactor == undefined ? 1 : properties.glossinessFactor;
  100367. if (properties.diffuseTexture) {
  100368. promises.push(this._loader._loadTextureAsync(context + "/diffuseTexture", properties.diffuseTexture, function (texture) {
  100369. babylonMaterial.albedoTexture = texture;
  100370. }));
  100371. }
  100372. if (properties.specularGlossinessTexture) {
  100373. promises.push(this._loader._loadTextureAsync(context + "/specularGlossinessTexture", properties.specularGlossinessTexture, function (texture) {
  100374. babylonMaterial.reflectivityTexture = texture;
  100375. }));
  100376. babylonMaterial.reflectivityTexture.hasAlpha = true;
  100377. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  100378. }
  100379. this._loader._loadMaterialAlphaProperties(context, material, babylonMaterial);
  100380. return Promise.all(promises).then(function () { });
  100381. };
  100382. return KHR_materials_pbrSpecularGlossiness;
  100383. }(GLTF2.GLTFLoaderExtension));
  100384. Extensions.KHR_materials_pbrSpecularGlossiness = KHR_materials_pbrSpecularGlossiness;
  100385. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_pbrSpecularGlossiness(loader); });
  100386. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  100387. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  100388. })(BABYLON || (BABYLON = {}));
  100389. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  100390. "use strict";
  100391. var BABYLON;
  100392. (function (BABYLON) {
  100393. var GLTF2;
  100394. (function (GLTF2) {
  100395. var Extensions;
  100396. (function (Extensions) {
  100397. // https://github.com/MiiBond/glTF/tree/khr_lights_v1/extensions/Khronos/KHR_lights
  100398. var NAME = "KHR_lights";
  100399. var LightType;
  100400. (function (LightType) {
  100401. LightType["AMBIENT"] = "ambient";
  100402. LightType["DIRECTIONAL"] = "directional";
  100403. LightType["POINT"] = "point";
  100404. LightType["SPOT"] = "spot";
  100405. })(LightType || (LightType = {}));
  100406. var KHR_lights = /** @class */ (function (_super) {
  100407. __extends(KHR_lights, _super);
  100408. function KHR_lights() {
  100409. var _this = _super !== null && _super.apply(this, arguments) || this;
  100410. _this.name = NAME;
  100411. return _this;
  100412. }
  100413. KHR_lights.prototype._loadSceneAsync = function (context, scene) {
  100414. var _this = this;
  100415. return this._loadExtensionAsync(context, scene, function (context, extension) {
  100416. var promise = _this._loader._loadSceneAsync(context, scene);
  100417. var light = GLTF2.GLTFLoader._GetProperty(context, _this._lights, extension.light);
  100418. if (light.type !== LightType.AMBIENT) {
  100419. throw new Error(context + ": Only ambient lights are allowed on a scene");
  100420. }
  100421. _this._loader._babylonScene.ambientColor = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.Black();
  100422. return promise;
  100423. });
  100424. };
  100425. KHR_lights.prototype._loadNodeAsync = function (context, node) {
  100426. var _this = this;
  100427. return this._loadExtensionAsync(context, node, function (context, extension) {
  100428. var promise = _this._loader._loadNodeAsync(context, node);
  100429. var babylonLight;
  100430. var light = GLTF2.GLTFLoader._GetProperty(context, _this._lights, extension.light);
  100431. var name = node._babylonMesh.name;
  100432. switch (light.type) {
  100433. case LightType.AMBIENT: {
  100434. throw new Error(context + ": Ambient lights are not allowed on a node");
  100435. }
  100436. case LightType.DIRECTIONAL: {
  100437. babylonLight = new BABYLON.DirectionalLight(name, BABYLON.Vector3.Forward(), _this._loader._babylonScene);
  100438. break;
  100439. }
  100440. case LightType.POINT: {
  100441. babylonLight = new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), _this._loader._babylonScene);
  100442. break;
  100443. }
  100444. case LightType.SPOT: {
  100445. var spotLight = light;
  100446. // TODO: support inner and outer cone angles
  100447. //const innerConeAngle = spotLight.innerConeAngle || 0;
  100448. var outerConeAngle = spotLight.outerConeAngle || Math.PI / 4;
  100449. babylonLight = new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward(), outerConeAngle, 2, _this._loader._babylonScene);
  100450. break;
  100451. }
  100452. default: {
  100453. throw new Error(context + ": Invalid light type (" + light.type + ")");
  100454. }
  100455. }
  100456. babylonLight.diffuse = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.White();
  100457. babylonLight.intensity = light.intensity == undefined ? 1 : light.intensity;
  100458. babylonLight.parent = node._babylonMesh;
  100459. return promise;
  100460. });
  100461. };
  100462. Object.defineProperty(KHR_lights.prototype, "_lights", {
  100463. get: function () {
  100464. var extensions = this._loader._gltf.extensions;
  100465. if (!extensions || !extensions[this.name]) {
  100466. throw new Error("#/extensions: '" + this.name + "' not found");
  100467. }
  100468. var extension = extensions[this.name];
  100469. return extension.lights;
  100470. },
  100471. enumerable: true,
  100472. configurable: true
  100473. });
  100474. return KHR_lights;
  100475. }(GLTF2.GLTFLoaderExtension));
  100476. Extensions.KHR_lights = KHR_lights;
  100477. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_lights(loader); });
  100478. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  100479. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  100480. })(BABYLON || (BABYLON = {}));
  100481. //# sourceMappingURL=KHR_lights.js.map
  100482. return BABYLON;
  100483. });
  100484. /***/ }),
  100485. /* 34 */
  100486. /***/ (function(module, exports, __webpack_require__) {
  100487. /*!
  100488. * PEP v0.4.3 | https://github.com/jquery/PEP
  100489. * Copyright jQuery Foundation and other contributors | http://jquery.org/license
  100490. */
  100491. !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);
  100492. // define inherited MouseEvent properties
  100493. // skip bubbles and cancelable since they're set above in initEvent()
  100494. for(var d,e=2;e<m.length;e++)d=m[e],c[d]=b[d]||n[e];c.buttons=b.buttons||0;
  100495. // Spec requires that pointers without pressure specified use 0.5 for down
  100496. // state and 0 for up state.
  100497. var f=0;
  100498. // add x/y properties aliased to clientX/Y
  100499. // define the properties of the PointerEvent interface
  100500. 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(){
  100501. // only activate if this platform does not have pointer events
  100502. 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}})}/**
  100503. * This is the constructor for new PointerEvents.
  100504. *
  100505. * New Pointer Events must be given a type, and an optional dictionary of
  100506. * initialization properties.
  100507. *
  100508. * Due to certain platform requirements, events returned from the constructor
  100509. * identify as MouseEvents.
  100510. *
  100511. * @constructor
  100512. * @param {String} inType The type of the event to create.
  100513. * @param {Object} [inDict] An optional dictionary of initial event properties.
  100514. * @return {Event} A new PointerEvent of type `inType`, initialized with properties from `inDict`.
  100515. */
  100516. 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},
  100517. // return value, key, map
  100518. forEach:function(a,b){return this.array.forEach(function(c,d){a.call(b,c,d,this)},this)}};var q=[
  100519. // MouseEvent
  100520. "bubbles","cancelable","view","detail","screenX","screenY","clientX","clientY","ctrlKey","altKey","shiftKey","metaKey","button","relatedTarget",
  100521. // DOM Level 3
  100522. "buttons",
  100523. // PointerEvent
  100524. "pointerId","width","height","pressure","tiltX","tiltY","pointerType","hwTimestamp","isPrimary",
  100525. // event instance
  100526. "type","target","currentTarget","which","pageX","pageY","timeStamp"],r=[
  100527. // MouseEvent
  100528. !1,!1,null,null,0,0,0,0,!1,!1,!1,!1,0,null,
  100529. // DOM Level 3
  100530. 0,
  100531. // PointerEvent
  100532. 0,0,0,0,0,0,"",0,!1,
  100533. // event instance
  100534. "",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),
  100535. // Scope objects for native events.
  100536. // This exists for ease of testing.
  100537. eventSources:Object.create(null),eventSourceList:[],/**
  100538. * Add a new event source that will generate pointer events.
  100539. *
  100540. * `inSource` must contain an array of event names named `events`, and
  100541. * functions with the names specified in the `events` array.
  100542. * @param {string} name A name for the event source
  100543. * @param {Object} source A new source of platform events.
  100544. */
  100545. 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++)
  100546. // call eventsource register
  100547. b.register.call(b,a)},unregister:function(a){for(var b,c=this.eventSourceList.length,d=0;d<c&&(b=this.eventSourceList[d]);d++)
  100548. // call eventsource register
  100549. b.unregister.call(b,a)},contains:/*scope.external.contains || */function(a,b){try{return a.contains(b)}catch(c){
  100550. // most likely: https://bugzilla.mozilla.org/show_bug.cgi?id=208427
  100551. return!1}},
  100552. // EVENTS
  100553. 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)},
  100554. // LISTENER LOGIC
  100555. eventHandler:function(a){
  100556. // This is used to prevent multiple dispatch of pointerevents from
  100557. // platform events. This can happen when two elements in different scopes
  100558. // are set up to create pointer events, which is relevant to Shadow DOM.
  100559. if(!a._handledByPE){var b=a.type,c=this.eventMap&&this.eventMap[b];c&&c(a),a._handledByPE=!0}},
  100560. // set up event listeners
  100561. listen:function(a,b){b.forEach(function(b){this.addEvent(a,b)},this)},
  100562. // remove event listeners
  100563. 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)},
  100564. // EVENT CREATION AND TRACKING
  100565. /**
  100566. * Creates a new Event of type `inType`, based on the information in
  100567. * `inEvent`.
  100568. *
  100569. * @param {string} inType A string representing the type of event to create
  100570. * @param {Event} inEvent A platform event with a target
  100571. * @return {Event} A PointerEvent of type `inType`
  100572. */
  100573. makeEvent:function(b,c){
  100574. // relatedTarget must be null if pointer is captured
  100575. 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},
  100576. // make and dispatch an event in one call
  100577. fireEvent:function(a,b){var c=this.makeEvent(a,b);return this.dispatchEvent(c)},/**
  100578. * Returns a snapshot of inEvent, with writable properties.
  100579. *
  100580. * @param {Event} inEvent An event that contains properties to copy.
  100581. * @return {Object} An object containing shallow copies of `inEvent`'s
  100582. * properties.
  100583. */
  100584. 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],
  100585. // Work around SVGInstanceElement shadow tree
  100586. // Return the <use> element that is represented by the instance for Safari, Chrome, IE.
  100587. // This is the behavior implemented by Firefox.
  100588. !t||"target"!==b&&"relatedTarget"!==b||c[b]instanceof SVGElementInstance&&(c[b]=c[b].correspondingUseElement);
  100589. // keep the semantics of preventDefault
  100590. 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){
  100591. // Order of conditions due to document.contains() missing in IE.
  100592. for(var d=a.target,e=[];d!==document&&!d.contains(a.relatedTarget);)
  100593. // Touch: Do not propagate if node is detached.
  100594. 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)}},/**
  100595. * Dispatches the event to its target.
  100596. *
  100597. * @param {Event} inEvent The event to be dispatched.
  100598. * @return {Boolean} True if an event handler returns true, false otherwise.
  100599. */
  100600. 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(
  100601. // is element a shadow host?
  100602. e=this.targetingShadow(f);e;){if(
  100603. // find the the element inside the shadow root
  100604. d=e.elementFromPoint(b,c)){
  100605. // shadowed element may contain a shadow root
  100606. var g=this.targetingShadow(d);return this.searchRoot(g,b,c)||d}
  100607. // check for older shadows
  100608. e=this.olderShadow(e)}
  100609. // light dom element is the target
  100610. return f}},owner:function(a){
  100611. // walk up until you hit the shadow root or document
  100612. for(var b=a;b.parentNode;)b=b.parentNode;
  100613. // the owner element is expected to be a Document or ShadowRoot
  100614. 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);
  100615. // if x, y is not in this root, fall back to document search
  100616. 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){
  100617. // Only watch scopes that can target find, as these are top-level.
  100618. // Otherwise we can see duplicate additions and removals that add noise.
  100619. //
  100620. // TODO(dfreedman): For some instances with ShadowDOMPolyfill, we can see
  100621. // a removal without an insertion when a node is redistributed among
  100622. // shadows. Since it all ends up correct in the document, watching only
  100623. // the document will yield the correct mutations to watch.
  100624. 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))},
  100625. // register all touch-action = none nodes on document load
  100626. 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){
  100627. // find children with touch-action
  100628. var b=x(a,this.findElements,this);
  100629. // flatten the list
  100630. // make sure the added nodes are accounted for
  100631. 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){}
  100632. // handler block for native mouse events
  100633. 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:[],
  100634. // collide with the global mouse listener
  100635. 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++){
  100636. // simulated mouse events will be swallowed near a primary touchend
  100637. 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);
  100638. // Update buttons state after possible out-of-document mouseup.
  100639. 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];
  100640. // Produces wrong state of buttons in Browsers without `buttons` support
  100641. // when a mouse button that was pressed outside the document is released
  100642. // inside and other buttons are still pressed down.
  100643. c.buttons=b?b.buttons&~d:0,a.buttons=c.buttons}H.set(this.POINTER_ID,a),
  100644. // Support: Firefox <=44 only
  100645. // FF Ubuntu includes the lifted button in the `buttons` property on
  100646. // mouseup.
  100647. // https://bugzilla.mozilla.org/show_bug.cgi?id=1223366
  100648. 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),
  100649. // set touch-action on shadows as well
  100650. 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),
  100651. // remove touch-action from shadow
  100652. 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);
  100653. // simply update scrollType if listeners are already established
  100654. 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){
  100655. // set primary touch if there no pointers, or the only pointer is the mouse
  100656. (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,
  100657. // forward modifier keys
  100658. c.altKey=b.altKey,c.ctrlKey=b.ctrlKey,c.metaKey=b.metaKey,c.shiftKey=b.shiftKey;
  100659. // forward touch preventDefaults
  100660. 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))},
  100661. // For single axis scrollers, determines whether the element should emit
  100662. // pointer events or behave as a scroller
  100663. shouldScroll:function(a){if(this.firstXY){var b,c=a.currentTarget._scrollType;if("none"===c)
  100664. // this element is a touch-action: none, should never scroll
  100665. b=!1;else if("XY"===c)
  100666. // this element should always scroll
  100667. 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]);
  100668. // if delta in the scroll axis > delta other axis, scroll instead of
  100669. // making events
  100670. 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},
  100671. // In some instances, a touchstart can happen without a touchend. This
  100672. // leaves the pointermap in a broken state.
  100673. // Therefore, on every touchstart, we remove the touches that did not fire a
  100674. // touchend event.
  100675. // To keep state globally consistent, we fire a
  100676. // pointercancel for this "abandoned" touch
  100677. vacuumTouches:function(a){var b=a.touches;
  100678. // pointermap.size should be < tl.length here, as the touchstart has not
  100679. // been processed yet.
  100680. if(R.size>=b.length){var c=[];R.forEach(function(a,d){
  100681. // Never remove pointerId == 1, which is mouse.
  100682. // Touch identifiers are 2 smaller than their pointerId, which is the
  100683. // index in pointermap.
  100684. 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);
  100685. // a finger drifted off the screen, ignore it
  100686. if(c){var d=c.out,e=c.outTarget;u.move(b),d&&e!==b.target&&(d.relatedTarget=b.target,b.relatedTarget=e,
  100687. // recover from retargeting by shadow
  100688. d.target=e,b.target?(u.leaveOut(d),u.enterOver(b)):(
  100689. // clean up case when finger leaves the screen
  100690. 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)},
  100691. // prevent synth mouse events from creating pointer events
  100692. dedupSynthMouse:function(a){var b=N.lastTouches,c=a.changedTouches[0];
  100693. // only the primary finger will synth mouse events
  100694. if(this.isPrimaryTouch(c)){
  100695. // remember x/y of last touch
  100696. 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});
  100697. /***/ }),
  100698. /* 35 */
  100699. /***/ (function(module, exports, __webpack_require__) {
  100700. "use strict";
  100701. Object.defineProperty(exports, "__esModule", { value: true });
  100702. var defaultViewer_1 = __webpack_require__(5);
  100703. var mappers_1 = __webpack_require__(1);
  100704. function InitTags(selector) {
  100705. if (selector === void 0) { selector = 'babylon'; }
  100706. var elements = document.querySelectorAll(selector);
  100707. for (var i = 0; i < elements.length; ++i) {
  100708. var element = elements.item(i);
  100709. var configMapper = mappers_1.mapperManager.getMapper('dom');
  100710. var config = configMapper.map(element);
  100711. var viewer = new defaultViewer_1.DefaultViewer(element, config);
  100712. }
  100713. }
  100714. exports.InitTags = InitTags;
  100715. /***/ })
  100716. /******/ ]);
  100717. return BabylonViewer;
  100718. });